diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0.json b/i18n/zh/docusaurus-plugin-content-docs/version-1.0.json new file mode 100644 index 0000000000..6c7e8fe775 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0.json @@ -0,0 +1,230 @@ +{ + "sidebar.docs.doc.Overview": { + "message": "概述", + "description": "The ZH label for Overview" + }, + "sidebar.docs.category.Getting Started": { + "message": "立即开始", + "description": "The label for category Getting Started in sidebar docs" + }, + "sidebar.docs.category.Installation": { + "message": "安装", + "description": "The label for category Installation in sidebar docs" + }, + "sidebar.docs.category.User Guide": { + "message": "用户指南", + "description": "The label for category User Guide in sidebar docs" + }, + "sidebar.docs.category.Concepts": { + "message": "基础概念", + "description": "The label for category Concepts in sidebar docs" + }, + "sidebar.docs.category.Migrate to GreptimeDB": { + "message": "迁移到 GreptimeDB", + "description": "The label for category Migrate to GreptimeDB in sidebar docs" + }, + "sidebar.docs.category.Write Data": { + "message": "写入数据", + "description": "The label for category Write Data in sidebar docs" + }, + "sidebar.docs.category.Query Data": { + "message": "查询数据", + "description": "The label for category Query Data in sidebar docs" + }, + "sidebar.docs.category.Flow Computation": { + "message": "流计算", + "description": "The label for category Flow Computation in sidebar docs" + }, + "sidebar.docs.category.Logs": { + "message": "日志", + "description": "The label for category Logs in sidebar docs" + }, + "sidebar.docs.category.Client Libraries": { + "message": "客户端库", + "description": "The label for category Client Libraries in sidebar docs" + }, + "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 & Administration": { + "message": "运维部署及管理", + "description": "The label for category Deployments & Administration in sidebar docs" + }, + "sidebar.docs.category.Write-Ahead Logging (WAL)": { + "message": "预写日志(WAL)", + "description": "The label for category Write-Ahead Logging (WAL) in sidebar docs" + }, + "sidebar.docs.category.Performance Tuning": { + "message": "性能调优", + "description": "The label for category Performance Tuning 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" + }, + "sidebar.docs.category.Elasticsearch Compatibility": { + "message": "Elasticsearch 兼容性", + "description": "The label for category Elasticsearch Compatibility in sidebar docs" + }, + "sidebar.docs.category.Remote WAL": { + "message": "Remote WAL", + "description": "The label for category Remote WAL in sidebar docs" + }, + "sidebar.docs.category.GreptimeCloud": { + "message": "GreptimeCloud", + "description": "The label for category GreptimeCloud in sidebar docs" + }, + "sidebar.docs.category.Integrations": { + "message": "集成", + "description": "The label for category Integrations in sidebar docs" + }, + "sidebar.docs.category.Prometheus": { + "message": "Prometheus", + "description": "The label for category Prometheus in sidebar docs" + }, + "sidebar.docs.category.SDK Libraries": { + "message": "SDK Libraries", + "description": "The label for category SDK Libraries in sidebar docs" + }, + "sidebar.docs.category.Migrate to GreptimeCloud": { + "message": "迁移到 GreptimeCloud", + "description": "The label for category Migrate to GreptimeCloud in sidebar docs" + }, + "sidebar.docs.category.Usage & Billing": { + "message": "用量及费用", + "description": "The label for category Usage & Billing in sidebar docs" + }, + "sidebar.docs.category.Tutorials": { + "message": "教程", + "description": "The label for category Tutorials 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": "参考手册", + "description": "The label for category Reference in sidebar docs" + }, + "sidebar.docs.category.GreptimeDB Command Line Interface": { + "message": "GreptimeDB 命令行工具", + "description": "The label for category GreptimeDB Command Line Interface in sidebar docs" + }, + "sidebar.docs.category.Utilities": { + "message": "实用工具", + "description": "The label for category Utilities in sidebar docs" + }, + "sidebar.docs.category.SQL": { + "message": "SQL", + "description": "The label for category SQL in sidebar docs" + }, + "sidebar.docs.category.Functions": { + "message": "Functions", + "description": "The label for category Functions in sidebar docs" + }, + "sidebar.docs.category.Information Schema": { + "message": "Information Schema", + "description": "The label for category Information Schema in sidebar docs" + }, + "sidebar.docs.category.Contributor Guide": { + "message": "贡献者指南", + "description": "The label for category Contributor Guide in sidebar docs" + }, + "sidebar.docs.category.Frontend": { + "message": "Frontend", + "description": "The label for category Frontend in sidebar docs" + }, + "sidebar.docs.category.Datanode": { + "message": "Datanode", + "description": "The label for category Datanode in sidebar docs" + }, + "sidebar.docs.category.Metasrv": { + "message": "Metasrv", + "description": "The label for category Metasrv in sidebar docs" + }, + "sidebar.docs.category.Flownode": { + "message": "Flownode", + "description": "The label for category Flownode in sidebar docs" + }, + "sidebar.docs.category.Tests": { + "message": "测试", + "description": "The label for category Tests in sidebar docs" + }, + "sidebar.docs.category.How To": { + "message": "指南", + "description": "The label for category How To in sidebar docs" + }, + "sidebar.docs.category.FAQ and Others": { + "message": "常见问题及其他", + "description": "The label for category FAQ and Others in sidebar docs" + }, + "sidebar.docs.category.Release Notes": { + "message": "发版说明", + "description": "The label for link Release Notes in sidebar docs, linking to /release-notes" + }, + "sidebar.docs.link.Releases": { + "message": "版本列表", + "description": "The label for link Release Notes in sidebar docs, linking to /release-notes" + }, + "sidebar.docs.category.Ingest Data": { + "message": "写入数据", + "description": "The label for category Ingest Data in sidebar docs" + }, + "sidebar.docs.category.For observability": { + "message": "可观测场景", + "description": "The label for category For observability 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.Manage Metadata": { + "message": "管理元数据", + "description": "The label for category Manage Metadata in sidebar docs" + }, + "sidebar.docs.category.Protocols": { + "message": "协议", + "description": "The label for category Manage Data in sidebar docs" + }, + "sidebar.docs.category.Monitoring": { + "message": "监控", + "description": "The label for category Monitoring in sidebar docs" + }, + "sidebar.docs.category.Maintenance": { + "message": "维护", + "description": "The label for category Maintenance in sidebar docs" + }, + "sidebar.docs.category.Vector Storage": { + "message": "向量存储", + "description": "The label for category Vector Storage in sidebar docs" + }, + "sidebar.docs.category.Read Replicas": { + "message": "读副本", + "description": "The label for category Read Replicas in sidebar docs" + } +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/data-persistence-indexing.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/data-persistence-indexing.md new file mode 100644 index 0000000000..65f3b04ec2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/data-persistence-indexing.md @@ -0,0 +1,87 @@ +--- +keywords: [数据持久化, 索引机制, SST 文件, 倒排索引] +description: 介绍了 GreptimeDB 的数据持久化和索引机制,包括 SST 文件格式、数据持久化过程和倒排索引的实现。 +--- + +# 数据持久化与索引 + +与所有类似 LSMT 的存储引擎一样,MemTables 中的数据被持久化到耐久性存储,例如本地磁盘文件系统或对象存储服务。GreptimeDB 采用 [Apache Parquet][1] 作为其持久文件格式。 + +## SST 文件格式 + +Parquet 是一种提供快速数据查询的开源列式存储格式,已经被许多项目采用,例如 Delta Lake。 + +Parquet 具有层次结构,类似于“行组 - 列-数据页”。Parquet 文件中的数据被水平分区为行组(row group),在其中相同列的所有值一起存储以形成数据页(data pages)。数据页是最小的存储单元。这种结构极大地提高了性能。 + +首先,数据按列聚集,这使得文件扫描更加高效,特别是当查询只涉及少数列时,这在分析系统中非常常见。 + +其次,相同列的数据往往是同质的(比如具备近似的值),这有助于在采用字典和 Run-Length Encoding(RLE)等技术进行压缩。 + +Parquet file format + +## 数据持久化 + +GreptimeDB 提供了 `storage.flush.global_write_buffer_size` 的配置项来设置全局的 Memtable 大小阈值。当数据库所有 MemTable 中的数据量之和达到阈值时将自动触发持久化操作,将 MemTable 的数据 flush 到 SST 文件中。 + + +## SST 文件中的索引数据 + +Apache Parquet 文件格式在列块和数据页的头部提供了内置的统计信息,用于剪枝和跳过。 + +Column chunk header + +例如,在上述 Parquet 文件中,如果你想要过滤 `name` 等于 `Emily` 的行,你可以轻松跳过行组 0,因为 `name` 字段的最大值是 `Charlie`。这些统计信息减少了 IO 操作。 + + +## 索引文件 + +对于每个 SST 文件,GreptimeDB 不但维护 SST 文件内部索引,还会单独生成一个文件用于存储针对该 SST 文件的索引结构。 + +索引文件采用 [Puffin][3] 格式,这种格式具有较大的灵活性,能够存储更多的元数据,并支持更多的索引结构。 + +![Puffin](/puffin.png) + +目前,倒排索引是 GreptimeDB 第一个支持的单独索引结构,以 Blob 的形式存储在索引文件中。 + + +## 倒排索引 + +在 v0.7 版本中,GreptimeDB 引入了倒排索引(Inverted Index)来加速查询。 + +倒排索引是一种常见的用于全文搜索的索引结构,它将文档中的每个单词映射到包含该单词的文档列表,GreptimeDB 把这项源自于搜索引擎的技术应用到了时间序列数据库中。 + +搜索引擎和时间序列数据库虽然运行在不同的领域,但是应用的倒排索引技术背后的原理是相似的。这种相似性需要一些概念上的调整: +1. 单词:在 GreptimeDB 中,指时间线的列值。 +2. 文档:在 GreptimeDB 中,指包含多个时间线的数据段。 + +倒排索引的引入,使得 GreptimeDB 可以跳过不符合查询条件的数据段,从而提高扫描效率。 + +![Inverted index searching](/inverted-index-searching.png) + +例如,上述查询使用倒排索引来定位数据段,数据段满足条件:`job` 等于 `apiserver`,`handler` 符合正则匹配 `.*users` 及 `status` 符合正则匹配 `4..`,然后扫描这些数据段以产生满足所有条件的最终结果,从而显着减少 IO 操作的次数。 + +### 倒排索引格式 + +![Inverted index format](/inverted-index-format.png) + +GreptimeDB 按列构建倒排索引,每个倒排索引包含一个 FST 和多个 Bitmap。 + +FST(Finite State Transducer)允许 GreptimeDB 以紧凑的格式存储列值到 Bitmap 位置的映射,并且提供了优秀的搜索性能和支持复杂搜索(例如正则表达式匹配);Bitmap 则维护了数据段 ID 列表,每个位表示一个数据段。 + + +### 索引数据段 + +GreptimeDB 把一个 SST 文件分割成多个索引数据段,每个数据段包含相同行数的数据。这种分段的目的是通过只扫描符合查询条件的数据段来优化查询性能。 + +例如,当数据段的行数为 1024,如果查询条件应用倒排索引后,得到的数据段列表为 `[0, 2]`,那么只需扫描 SST 文件中的第 0 和第 2 个数据段(即第 0 行到第 1023 行和第 2048 行到第 3071 行)即可。 + +数据段的行数由引擎选项 `index.inverted_index.segment_row_count` 控制,默认为 `1024`。较小的值意味着更精确的索引,往往会得到更好的查询性能,但会增加索引存储成本。通过调整该选项,可以在存储成本和查询性能之间进行权衡。 + + +## 统一数据访问层:OpenDAL + +GreptimeDB 使用 [OpenDAL][2] 提供统一的数据访问层,因此,存储引擎无需与不同的存储 API 交互,数据可以无缝迁移到基于云的存储,如 AWS S3。 + +[1]: https://parquet.apache.org +[2]: https://github.com/datafuselabs/opendal +[3]: https://iceberg.apache.org/puffin-spec diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/metric-engine.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/metric-engine.md new file mode 100644 index 0000000000..5fa0f6bb77 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/metric-engine.md @@ -0,0 +1,42 @@ +--- +keywords: [Metric 引擎, 逻辑表, 物理表, DDL 操作] +description: 介绍了 Metric 引擎的概念、架构及设计,重点描述了逻辑表与物理表的区别和批量 DDL 操作的实现。 +--- + +# Metric 引擎 + +## 概述 + +`Metric` 引擎是 GreptimeDB 的一个组件,属于存储引擎的一种实现,主要针对可观测 metrics 等存在大量小表的场景。 + +它的主要特点是利用合成的物理宽表来存储大量的小表数据,实现相同列复用和元数据复用等效果,从而达到减少小表的存储开销以及提高列式压缩效率等目标。表这一概念在 `Metric` 引擎下变得更更加轻量。 + +## 概念 + +`Metric` 引擎引入了两个新的概念,分别是逻辑表与物理表。从用户视角看,逻辑表与普通表完全一样。从存储视角看,物理 Region 就是一个普通的 Region。 + +### 逻辑表 +逻辑表,即用户定义的表。与普通的表都完全一样,逻辑表的定义包括表的名称、列的定义、索引的定义等。用户的查询、写入等操作都是基于逻辑表进行的。用户在使用过程中不需要关心逻辑表和普通表的区别。 + +从实现层面来说,逻辑表是一个虚拟的表,它并不直接读写物理的数据,而是通过将读写请求映射成对应物理表的请求来实现数据的存储与查询。 + +### 物理表 +物理表是真实存储数据的表,它拥有若干个由分区规则定义的物理 Region。 + +## 架构及设计 + +`Metric` 引擎的主要设计架构如下: + +![Arch](/metric-engine-arch.png) + +在目前版本的实现中,`Metric` 引擎复用了 `Mito` 引擎来实现物理数据的存储及查询能力,并在此之上同时提供物理表与逻辑表的访问能力。 + +在分区方面,逻辑表拥有与物理表完全一致的分区规则及 Region 分布。这是非常自然的,因为逻辑表的数据直接存储在物理表中,所以分区规则也是一致的。 + +在路由元数据方面,逻辑表的路由地址为逻辑地址,即该逻辑表所对应的物理表是什么,而后通过该物理表进行二次路由取得真正的物理地址。这一间接路由方式能够显著减少 `Metric` 引擎的 Region 发生迁移调度时所需要修改的元数据数量。 + +在操作方面,`Metric` 引擎仅对物理表的操作进行了有限的支持以防止误操作,例如通过禁止写入物理表、删除物理表等操作防止影响用户逻辑表的数据。总体上可以认为物理表是对用户只读的。 + +为了提升对大量表同时进行 DDL(Data Definition Language,数据操作语言)操作时性能,如 Prometheus Remote Write 冷启动时大量 metrics 带来的自动建表请求,以及前面提到的迁移物理 Region 时大量路由表的修改请求等,`Metric` 引擎引入了一些批量 DDL 操作。这些批量 DDL 操作能够将大量的 DDL 操作合并成一个请求,从而减少了元数据的查询及修改次数,提升了性能。 + +除了物理表的物理数据 Region 之外,`Metric` 引擎还额外为每一个物理数据 Region 创建了一个物理的元数据 Region,用于存储 `Metric` 引擎自身为了维护映射等状态所需要的一些元数据。这些元数据包括逻辑表与物理表的映射关系,逻辑列与物理列的映射关系等等。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/overview.md new file mode 100644 index 0000000000..0a1b674d7c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/overview.md @@ -0,0 +1,28 @@ +--- +keywords: [Datanode, gRPC 服务, HTTP 服务, Heartbeat Task, Region Manager] +description: 介绍了 Datanode 的主要职责和组件,包括 gRPC 服务、HTTP 服务、Heartbeat Task 和 Region Manager。 +--- + +# Datanode + +## Introduction + +`Datanode` 主要的职责是为 GreptimeDB 存储数据,我们知道在 GreptimeDB 中一个 `table` 可以有一个或者多个 `Region`, +而 `Datanode` 的职责便是管理这些 `Region` 的读写。`Datanode` 不感知 `table`,可以认为它是一个 `region server`。 +所以 `Frontend` 和 `Metasrv` 按照 `Region` 粒度来操作 `Datanode`。 + +![Datanode](/datanode.png) + +## Components + +一个 datanode 包含了 region server 所需的全部组件。这里列出了比较重要的部分: + +- 一个 gRPC 服务来提供对 `Region` 数据的读写,`Frontend` 便是使用这个服务来从 `Datanode` 读写数据。 +- 一个 HTTP 服务,可以通过它来获得当前节点的 metrics、配置信息等 +- `Heartbeat Task` 用来向 `Metasrv` 发送心跳,心跳在 GreptimeDB 的分布式架构中发挥着至关重要的作用, + 是分布式协调和调度的基础通信通道,心跳的上行消息中包含了重要信息比如 `Region` 的负载,如果 `Metasrv` 做出了调度 + 决定(比如 Region 转移),它会通过心跳的下行消息发送指令到 `Datanode` +- `Datanode` 不包含物理规划器(Physical planner)、优化器(optimizer)等组件(这些被放置在 `Frontend` 中),用户对 + 一个或多个 `Table` 的查询请求会在 `Frontend` 中被转换为 `Region` 的查询请求,`Datanode` 负责处理这些 `Region` 查询请求 +- 一个 `Region Manager` 用来管理 `Datanode` 上的所有 `Region`s +- GreptimeDB 支持可插拔的多引擎架构,目前已有的 engine 包括 `File Engine` 和 `Mito Engine` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/python-scripts.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/python-scripts.md new file mode 100644 index 0000000000..831278e80d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/python-scripts.md @@ -0,0 +1,30 @@ +--- +keywords: [Python 脚本, 数据分析, CPython, RustPython] +description: 介绍了在 GreptimeDB 中使用 Python 脚本进行数据分析的两种后端实现:CPython 和嵌入式 RustPython 解释器。 +--- + +# Python 脚本 + +## 简介 + +Python 脚本是分析本地数据库中的数据的便捷方式, +通过将脚本直接在数据库内运行而不是从数据库拉取数据的方式,可以节省大量的数据传输时间。 +下图描述了 Python 脚本的工作原理。 +`RecordBatch`(基本上是表中的一列,带有类型和元数据)可以来自数据库中的任何地方, +而返回的 `RecordBatch` 可以用 Python 语法注释以指示其元数据,例如类型或空。 +脚本将尽其所能将返回的对象转换为 `RecordBatch`,无论它是 Python 列表、从参数计算出的 `RecordBatch` 还是常量(它被扩展到与输入参数相同的长度)。 + +![Python Coprocessor](/python-coprocessor.png) + +## 两种可选的后端 + +### CPython 后端 + +该后端由 [PyO3](https://pyo3.rs/v0.18.1/) 提供支持,可以使用您最喜欢的 Python 库(如 NumPy、Pandas 等),并允许 Conda 管理您的 Python 环境。 + +但是使用它也涉及一些复杂性。您必须设置正确的 Python 共享库,这可能有点棘手。一般来说,您只需要安装 `python-dev` 包。但是,如果您使用 Homebrew 在 macOS 上安装 Python,则必须创建一个适当的软链接到 `Library/Frameworks/Python.framework`。有关使用 PyO3 crate 与不同 Python 版本的详细说明,请参见 [这里](https://pyo3.rs/v0.18.1/building_and_distribution#configuring-the-python-version) + +### 嵌入式 RustPython 解释器 + +可以运行脚本的实验性 [python 解释器](https://github.com/RustPython/RustPython),它支持 Python 3.10 语法。您可以使用所有的 Python 语法,更多信息请参见 [Python 脚本的用户指南](/user-guide/python-scripts/overview.md). + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/query-engine.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/query-engine.md new file mode 100644 index 0000000000..72b7a7f981 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/query-engine.md @@ -0,0 +1,47 @@ +--- +keywords: [查询引擎, DataFusion, 逻辑计划, 物理计划] +description: 介绍了 GreptimeDB 的查询引擎架构,基于 Apache DataFusion 构建,涵盖逻辑计划、物理计划、优化和执行过程。 +--- + +# Query Engine + +## 介绍 + +GreptimeDB 的查询引擎是基于[Apache DataFusion][1](属于[Apache Arrow][2]的子项目)构建的,它是一个用 Rust 编写的出色的查询引擎。它提供了一整套功能齐全的组件,从逻辑计划、物理计划到执行运行时。下面将解释每个组件如何被整合在一起,以及在执行过程中它们的位置。 + +![Execution Procedure](/execution-procedure.png) + +入口点是逻辑计划,它被用作查询或执行逻辑等的通用中间表示。逻辑计划的两个主要来源是:1. 用户查询,例如通过 SQL 解析器和规划器的 SQL;2. Frontend 的分布式查询,这将在下一节中详细解释。 + +接下来是物理计划,或称执行计划。与包含所有逻辑计划变体(除特殊扩展计划节点外)的大型枚举的逻辑计划不同,物理计划实际上是一个定义了在执行过程中调用的一组方法的特性。所有数据处理逻辑都包装在实现该特性的相应结构中。它们是对数据执行的实际操作,如聚合器 `MIN` 或 `AVG` ,以及表扫描 `SELECT ... FROM`。 + +优化阶段通过转换逻辑计划和物理计划来提高执行性能,现在全部基于规则。它也被称为“基于规则的优化”。一些规则是 DataFusion 原生的,其他一些是在 GreptimeDB 中自定义的。在未来,我们计划添加更多规则,并利用数据统计进行基于成本的优化 (CBO)。 + +最后一个阶段"执行"是一个动词,代表从存储读取数据、进行计算并生成预期结果的过程。虽然它比之前提到的概念更抽象,但你可以简单地将它想象为执行一个 Rust 异步函数,并且它确实是一个异步流。 + +当你想知道 SQL 是如何通过逻辑计划或物理计划中表示时,`EXPLAIN [VERBOSE] ` 是非常有用的。 + +## 数据表示 + +GreptimeDB 使用 [Apache Arrow][2]作为内存中的数据表示格式。它是面向列的,以跨平台格式,也包含许多高性能的基础操作。这些特性使得在许多不同的环境中共享数据和实现计算逻辑变得容易。 + +## 索引 + +在时序数据中,有两个重要的维度:时间戳和标签列(或者类似于关系数据库中的主键)。GreptimeDB 将数据分组到时间桶中,因此能在非常低的成本下定位和提取预期时间范围内的数据。GreptimeDB 中主要使用的持久文件格式 [Apache Parquet][3] 提供了多级索引和过滤器,使得在查询过程中很容易修剪数据。在未来,我们将更多地利用这个特性,并开发我们的分离索引来处理更复杂的用例。 + +## 拓展性 + + + +在 GreptimeDB 中扩展操作非常简单。你可以像 [这样][5] 实现你的算子。 + +## 分布式查询 + +参考 [Distributed Querying][6]. + +[1]: https://github.com/apache/arrow-datafusion +[2]: https://arrow.apache.org/ +[3]: https://parquet.apache.org +[4]: python-scripts.md +[5]: https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-write-aggregate-function.md +[6]: ../frontend/distributed-querying.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/storage-engine.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/storage-engine.md new file mode 100644 index 0000000000..6a55d2cb2f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/storage-engine.md @@ -0,0 +1,62 @@ +--- +keywords: [存储引擎, Mito, LSMT, 数据模型, Region] +description: 详细介绍了 GreptimeDB 的存储引擎架构、数据模型和 region 的概念,重点描述了 Mito 存储引擎的优化和组件。 +--- + +# 存储引擎 + +## 概述 + +`存储引擎` 负责存储数据库的数据。Mito 是我们默认使用的存储引擎,基于 [LSMT][1](Log-structured Merge-tree)。我们针对处理时间序列数据的场景做了很多优化,因此 mito 这个存储引擎并不适用于通用用途。 + +## 架构 +下图展示了存储引擎的架构和处理数据的流程。 + +![Architecture](/storage-engine-arch.png) + +该架构与传统的 LSMT 引擎相同: + +- [WAL][2] + - 为尚未刷盘的数据提供高持久性保证。 + - 基于 `LogStore` API 实现,不关心底层存储介质。 + - WAL 的日志记录可以存储在本地磁盘上,也可以存储在实现了 `LogStore` API 的分布式日志服务中。 +- Memtable + - 数据首先写入 `active memtable`,又称 `mutable memtable`。 + - 当 `mutable memtable` 已满时,它将变为只读的 `immutable memtable`。 +- SST + - SST 的全名为有序字符串表(`Sorted String Table`)。 + - `immutable memtable` 刷到持久存储后形成一个 SST 文件。 +- Compactor + - `Compactor` 通过 compaction 操作将小的 SST 合并为大的 SST。 + - 默认使用 [TWCS][3] 策略进行合并 +- Manifest + - `Manifest` 存储引擎的元数据,例如 SST 的元数据。 +- Cache + - 加速查询操作。 + +[1]: https://en.wikipedia.org/wiki/Log-structured_merge-tree +[2]: https://en.wikipedia.org/wiki/Write-ahead_logging +[3]: https://cassandra.apache.org/doc/latest/cassandra/operating/compaction/twcs.html + +## 数据模型 + +存储引擎提供的数据模型介于 `key-value` 模型和表模型之间 + +```txt +tag-1, ..., tag-m, timestamp -> field-1, ..., field-n +``` + +每一行数据包含多个 tag 列,一个 timestamp 列和多个 field 列 +- `0 ~ m` 个 tag 列 + - tag 列是可空的 + - 在建表时通过 `PRIMARY KEY` 指定 +- 必须包含一个 timestamp 列 + - timestamp 列非空 + - 在建表时通过 `TIME INDEX` 指定 +- `0 ~ n` 个 field 列 + - field 列是可空的 +- 数据按照 tag 列和 timestamp 列有序存储 + +## Region + +数据在存储引擎中以 `region` 的形式存储,`region` 是引擎中的一个逻辑隔离存储单元。`region` 中的行必须具有相同的 `schema`(模式),该 `schema` 定义了 `region` 中的 tag 列,timestamp 列和 field 列。数据库中表的数据存储在一到多个 `region` 中。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/wal.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/wal.md new file mode 100644 index 0000000000..ed67ce7ef3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/datanode/wal.md @@ -0,0 +1,26 @@ +--- +keywords: [预写日志, WAL, 数据持久化, 同步刷盘, 异步刷盘] +description: 介绍了 GreptimeDB 的预写日志(WAL)机制,包括其命名空间、同步/异步刷盘策略和在数据节点重启时的重放功能。 +--- + +# 预写日志 + +## 介绍 + +我们的存储引擎受到了日志结构合并树(Log-structured Merge Tree,LSMT)的启发。对数据的变更操作直接应用于 MemTable 而不是持久化到磁盘上的数据页,这显著提高了性能,但也带来了持久化相关的问题,特别是在 Datanode 意外崩溃时。与所有类似 LSMT 的存储引擎一样,GreptimeDB 使用预写日志(Write-Ahead Log,WAL)来确保数据被可靠地持久化,并且保证崩溃时的数据完整性。 + +预写日志是一个仅提供追加写的文件组。所有的 INSERT、UPDATE 和 DELETE 操作都被转换为操作日志,然后追加到 WAL。一旦操作日志被持久化到底层文件,该操作才可以进一步应用到 MemTable。 + +当数据节点重新启动时,WAL 中的操作条目将被重放,以重建正确的 MemTable 状态。 + +![WAL in Datanode](/wal.png) + +## 命名空间 + +WAL 的命名空间用于区分来自不同 region 的条目。追加和读取操作必须提供一个命名空间。目前,region ID 被用作命名空间,因为每个 region 都有一个在数据节点重新启动时需要重构的 MemTable。 + +## 同步/异步刷盘 + +默认情况下,WAL 的追加写是异步的,这意味着写入方不会等待操作日志被刷入到磁盘并持久化。这个默认设置提供了更高的性能,但在服务器意外关闭时可能会丢失数据。另一方面,同步刷新提供了更高的可靠性,但其代价是性能更低。 + +在 v0.4 版本中,新的 region worker 架构可以使用批处理来减轻同步刷盘的开销。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/flownode/arrangement.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/flownode/arrangement.md new file mode 100644 index 0000000000..dd3b6de090 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/contributor-guide/flownode/batching_mode.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/flownode/batching_mode.md new file mode 100644 index 0000000000..64edc38548 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/flownode/batching_mode.md @@ -0,0 +1,74 @@ +--- +keywords: [流处理, flow 管理, Flownode 组件, Flownode 限制, 批处理模式] +description: Flownode 批处理模式概述,一个为数据库提供持续数据聚合能力的组件,包括其架构和查询执行流程。 +--- + +# Flownode 批处理模式开发者指南 + +本指南简要概述了 `flownode` 中的批处理模式。它旨在帮助希望了解此模式内部工作原理的开发人员。 + +## 概述 + +`flownode` 中的批处理模式专为持续数据聚合而设计。它在离散的、微小的时间窗口上周期性地执行用户定义的 SQL 查询。这与数据在到达时即被处理的流处理模式形成对比。 + +其核心思想是: +1. 定义一个带有 SQL 查询的 `flow`,该查询将数据从源表聚合到目标表。 +2. 查询通常在时间戳列上包含一个时间窗口函数(例如 `date_bin`)。 +3. 当新数据插入源表时,系统会将相应的时间窗口标记为“脏”(dirty)。 +4. 一个后台任务会周期性地唤醒,识别这些脏窗口,并为那些特定的时间范围重新运行聚合查询。 +5. 然后将结果插入到目标表中,从而有效地更新聚合视图。 + +## 架构 + +批处理模式由几个协同工作的关键组件组成,以实现这种持续聚合。如下图所示: + +![batching mode architecture](/batching_mode_arch.png) + +### `BatchingEngine` + +`BatchingEngine` 是批处理模式的核心。它是一个管理所有活动 flow 的中心组件。其主要职责是: + +- **任务管理**: 维护一个从 `FlowId` 到 `BatchingTask` 的映射。它处理这些任务的创建、删除和检索。 +- **事件分发**: 当新数据到达(通过 `handle_inserts_inner`)或当时间窗口被显式标记为脏(`handle_mark_dirty_time_window`)时,`BatchingEngine` 会识别受影响的 flow,并将信息转发给相应的 `BatchingTask`。 + +### `BatchingTask` + +`BatchingTask` 代表一个独立的、单个的数据流。每个任务都与一个 `flow` 定义相关联,并在其自己的异步循环中运行。 + +- **配置 (`TaskConfig`)**: 此结构体持有 flow 的不可变配置,例如 SQL 查询、源表和目标表名以及时间窗口表达式。 +- **状态 (`TaskState`)**: 包含任务的动态、可变状态,最重要的是 `DirtyTimeWindows`。 +- **执行循环**: 任务运行一个无限循环 (`start_executing_loop`),该循环: + 1. 检查关闭信号。 + 2. 等待一个预定的时间间隔或直到被唤醒。 + 3. 基于当前的脏时间窗口集合生成一个新的查询计划 (`gen_insert_plan`)。 + 4. 对数据库执行查询 (`execute_logical_plan`)。 + 5. 清理已处理的脏窗口。 + +### `TaskState` 和 `DirtyTimeWindows` + +- **`TaskState`**: 此结构体跟踪 `BatchingTask` 的运行时状态。它包括 `dirty_time_windows`,这对于确定需要完成哪些操作至关重要。 +- **`DirtyTimeWindows`**: 这是一个关键的数据结构,用于跟踪自上次查询执行以来哪些时间窗口接收到了新数据。它存储一组不重叠的时间范围。当任务的执行循环运行时,它会参考此结构来构建一个 `WHERE` 子句,该子句仅过滤源表中的脏时间窗口。 + +### `TimeWindowExpr` + +`TimeWindowExpr` 是一个用于处理像 `TUMBLE` 这样的时间窗口函数的辅助工具。 + +- **求值**: 它可以接受一个时间戳并对时间窗口表达式求值,以确定该时间戳所属窗口的开始和结束。 +- **窗口大小**: 它还可以从表达式中确定时间窗口的大小(持续时间)。 + +这对于标记窗口为脏以及在查询源表时生成正确的过滤条件都至关重要。 + +## 查询执行流程 + +以下是批处理模式下查询执行的简化分步演练: + +1. **数据摄取**: 新数据被写入源表。 +2. **标记为脏**: `BatchingEngine` 收到有关新数据的通知。它使用与每个相关 flow 关联的 `TimeWindowExpr` 来确定哪些时间窗口受到新数据点的影响。然后将这些窗口添加到相应 `TaskState` 中的 `DirtyTimeWindows` 集合中。 +3. **任务唤醒**: `BatchingTask` 的执行循环被唤醒,原因可能是其周期性调度,也可能是因为它被通知有大量积压的脏窗口。 +4. **计划生成**: 任务调用 `gen_insert_plan`。此方法: + - 检查 `DirtyTimeWindows`。 + - 生成一系列 `OR` 连接的 `WHERE` 子句(例如 `(ts >= 't1' AND ts < 't2') OR (ts >= 't3' AND ts < 't4') ...`),覆盖所有脏窗口。 + - 重写原始 SQL 查询以包含此新过滤器,确保只处理必要的数据。 +5. **执行**: 修改后的查询计划被发送到 `Frontend` 执行。数据库处理已过滤数据的聚合。 +6. **Upsert**: 结果被插入到目标表中。目标表通常定义了一个包含时间窗口列的主键,因此现有窗口的新结果将覆盖(upsert)旧结果。 +7. **状态更新**: `DirtyTimeWindows` 集合中刚刚处理过的窗口被清除。然后任务返回睡眠状态,直到下一个时间间隔。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/flownode/dataflow.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/flownode/dataflow.md new file mode 100644 index 0000000000..9d07922542 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/contributor-guide/flownode/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/flownode/overview.md new file mode 100644 index 0000000000..b9759e9f42 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/flownode/overview.md @@ -0,0 +1,25 @@ +--- +keywords: [流处理, flow 管理, 单机模式, Flownode 组件, Flownode 限制] +description: Flownode 概览,一个为数据库提供流处理能力的组件,包括其组件和当前的限制。 +--- + +# Flownode + +## 简介 + +`Flownode` 为数据库提供了一种简单的流处理(称为 `flow`)能力。 +`Flownode` 管理 `flow`,这些 `flow` 是从 `source` 接收数据并将数据发送到 `sink` 的任务。 + +`Flownode` 支持 `standalone`(单机)和 `distributed`(分布式)两种模式。在 `standalone` 模式下,`Flownode` 与数据库运行在同一进程中。在 `distributed` 模式下,`Flownode` 运行在单独的进程中,并通过网络与数据库通信。 + +一个 flow 有两种执行模式: +- **流处理模式 (Streaming Mode)**: 原始的模式,数据在到达时即被处理。 +- **批处理模式 (Batching Mode)**: 一种为持续数据聚合设计的较新模式。它在离散的、微小的时间窗口上周期性地执行用户定义的 SQL 查询。目前所有的聚合查询都使用此模式。更多详情,请参阅[批处理模式开发者指南](./batching_mode.md)。 + +## 组件 + +`Flownode` 包含了执行一个 flow 所需的所有组件。所涉及的具体组件取决于执行模式(流处理 vs. 批处理)。在较高的层面上,关键部分包括: + +- **Flow Manager**: 一个负责管理所有 flow生命周期的中心组件。 +- **Task Executor**: flow 逻辑执行的运行时环境。在流处理模式下,这通常是一个 `FlowWorker`;在批处理模式下,它是一个 `BatchingTask`。 +- **Flow Task**: 代表一个独立的、单个的数据流,包含将数据从 source 转换为 sink 的逻辑。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/frontend/distributed-querying.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/frontend/distributed-querying.md new file mode 100644 index 0000000000..b73f58029d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/frontend/distributed-querying.md @@ -0,0 +1,40 @@ +--- +keywords: [分布式查询, 查询拆分, 查询合并, TableScan, 物理计划] +description: 介绍 GreptimeDB 中的分布式查询方法,包括查询的拆分和合并过程,以及 TableScan 节点的作用。 +--- + +# 分布式查询 + +我们知道在 GreptimeDB 中数据是如何分布的(参见“[表分片][1]”),那么如何查询呢?在 GreptimeDB 中,分布式查询非常简单。简单来说,我们只需将查询拆分为子查询,每个子查询负责查询表数据的一个部分,然后将所有结果合并为最终结果。这是一种典型的“拆分 - 合并”方法。具体来说,让我们从查询到达 `frontend` 开始。 + +当查询到达 `frontend` 时,它首先被解析为 SQL 抽象语法树(AST)。我们遍历 AST,并从中生成逻辑计划。顾名思义,逻辑计划只是如何“逻辑地”执行查询的“提示”,它不能被直接运行,因此我们进一步从中生成可执行的物理计划。物理计划是一种类似树形的数据结构,每个节点实际上表示查询的执行方法。一旦我们从上到下运行物理计划树,结果数据将从叶子到根流动,被合并或计算。最终,我们在根节点的输出处得到了查询的结果。 + +到目前为止,这只是一个典型的“volcano”查询执行模型,你可以在几乎每个 SQL 数据库中看到这种模型。那么“分布式”是在哪里发生的呢?这全部发生在一个名为“TableScan”的物理计划节点中。TableScan 是物理计划树中的一个叶子节点,它负责扫描表的数据(就像它的名称所暗示的)。当 `frontend` 即将扫描表时,它首先需要根据每个 `region` 的数据范围将表扫描拆分为较小的扫描。 + +[1]: ./table-sharding.md + +表的所有 `region` 都有它们存储数据的范围。以下表为例: + +```sql +CREATE TABLE my_table ( + a INT, + others STRING, +) +PARTITION ON COLUMNS (a) ( + n < 10, + n >= 10 AND n < 20, + n >= 20 +) +``` + +`my_table` 表创建时被设定了 3 个分区。在 GreptimeDB 的当前实现中,将为该表创建 3 个 `region`(分区与 `region` 的比例为 1:1)。这 3 个区域将分别包含以下范围:"[-∞, 10)", "[10, 20)" 和 "[20, +∞)"。例如,如果提供了值 "42",我们将搜索这些范围,并找到包含该值的相应的 `region`(在此示例中为第 3 个 `region`)。 + +对于查询,我们使用“过滤器”来查找 `region`。 "过滤器"是 "WHERE" 子句中的条件。例如,查询 `SELECT * FROM my_table WHERE a < 10 AND b > 10`,其“过滤器”为“a < 10 AND b > 10”。然后我们检查这些范围,找出包含满足过滤器条件的值的所有 `region`。 + +> 如果某个查询没有任何过滤器,则将其视为全表扫描。 + +找到所需的区域后,我们只需在其中组装子扫描。通过这种方式,我们将查询拆分为子查询,每个子查询都获取表数据的一部分。子查询在 `datanode` 中执行,并在 `frontend` 中等待完成。它们的结果将合并为表扫描请求的最终返回。 + +下面这张图片总结了分布式查询执行的过程: + +![Distributed Querying](/distributed-querying.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/frontend/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/frontend/overview.md new file mode 100644 index 0000000000..ee48da3ce3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/frontend/overview.md @@ -0,0 +1,43 @@ +--- +keywords: [frontend, proxy, protocol, routing, distributed query, tenant management, authorization, flow control, cloud deployment, endpoints] +description: GreptimeDB Frontend 组件概述 - 为客户端请求提供服务的无状态代理服务。 +--- + +# Frontend + +**Frontend** 是一个无状态服务,作为 GreptimeDB 中客户端请求的入口点。它为多种数据库协议提供统一接口,并充当代理,将读写请求转发到分布式系统中的相应 Datanode。 + +## 核心功能 + +- **协议支持**:支持多种数据库协议,包括 SQL、PromQL、MySQL 和 PostgreSQL。详见[协议][1] +- **请求路由**:基于元数据将请求路由到相应的 Datanode +- **查询分发**:将分布式查询拆分到多个节点 +- **响应聚合**:合并来自多个 Datanode 的结果 +- **认证授权**:安全和访问控制验证 + +## 架构 + +### 关键组件 +- **协议处理器**:处理不同的数据库协议 +- **目录管理器**:缓存来自 Metasrv 的元数据以实现高效的请求路由和 Schema 校验 +- **分布式规划器**:将逻辑计划转换为分布式执行计划 +- **请求路由器**:为每个请求确定目标 Datanodes + +### 请求流程 + +![request flow](/request_flow.png) + +### 部署 + +下图是 GreptimeDB 在云上的一个典型的部署。`Frontend` 实例组成了一个集群处理来自客户端的请求: + +![frontend](/frontend.png) + +## 详细信息 + +- [表分片][2] +- [分布式查询][3] + +[1]: /user-guide/protocols/overview.md +[2]: ./table-sharding.md +[3]: ./distributed-querying.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/frontend/table-sharding.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/frontend/table-sharding.md new file mode 100644 index 0000000000..02e8e43bbb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/frontend/table-sharding.md @@ -0,0 +1,53 @@ +--- +keywords: [表分片, 分区, Region, 数据存储, Region 自动移动] +description: 介绍 GreptimeDB 中表数据的分片方法,包括分区和 Region 的定义及其关系。 +--- + +# 表分片 + +对于任何分布式数据库来说,数据的分片都是必不可少的。本文将描述 GreptimeDB 中的表数据如何进行分片。 + +## 分区 + +有关创建分区表的语法,请参阅用户指南中的[表分片](/user-guide/deployments-administration/manage-data/table-sharding.md)部分。 + +## Region + +在创建分区后,表中的数据被逻辑上分割。你可能会问:"在 GreptimeDB 中,被逻辑上分区的数据是如何存储的?" 答案是保存在 `Region` 当中。 + +每个 `Region` 对应一个分区,并保存分区的数据。所有的 `Region` 分布在各个 `Datanode` 之中。我们的 `Metasrv` 会根据 `Datanode` +的状态在它们之间自动移动 `Region`。此外,`Metasrv` 还可以根据数据量或访问模式拆分或合并 `Region`。 + +分区和 Region 的关系参见下图: + +```text + ┌───────┐ + │ │ + │ Table │ + │ │ + └───┬───┘ + │ + Range [Start, end) │ Horizontally Split Data + ┌──────────────────┼──────────────────┐ + │ │ │ + │ │ │ + ┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐ + │ │ │ │ │ │ + │ Partition │ │ Partition │ │ Partition │ + │ │ │ │ │ │ + │ P0 │ │ P1 │ │ Px │ + └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ + │ │ │ + │ │ │ +┌───────┼──────────────────┼───────┐ │ Partition 和 Region 是一一对应的 +│ │ │ │ │ +│ ┌─────▼─────┐ ┌─────▼─────┐ │ ┌─────▼─────┐ +│ │ │ │ │ │ │ │ +│ │ Region │ │ Region │ │ │ Region │ +│ │ │ │ │ │ │ │ +│ │ R0 │ │ R1 │ │ │ Ry │ +│ └───────────┘ └───────────┘ │ └───────────┘ +│ │ +└──────────────────────────────────┘ + 可以放在同一个 Datanode 之中 +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/getting-started.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/getting-started.md new file mode 100644 index 0000000000..ba5ee05fbe --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/getting-started.md @@ -0,0 +1,70 @@ +--- +keywords: [编译, 运行, 源代码, 系统要求, 依赖项, Docker] +description: 介绍如何在本地环境中从源代码编译和运行 GreptimeDB,包括系统要求和依赖项。 +--- + +# 立即开始 + +本页面介绍如何在本地环境中从源代码运行 GreptimeDB。 + +## 先决条件 + +### 系统和架构 + +目前,GreptimeDB 支持 Linux(amd64 和 arm64)、macOS(amd64 和 Apple Silicone)和 Windows。 + +### 构建依赖项 + +- [Git](https://git-scm.com/book/en/v2/Getting-Started-The-Command-Line)(可选) +- C/C++ 工具链:提供编译和链接的基本工具。在 Ubuntu 上,这可用作 `build-essential`。在其他平台上,也有类似的命令。 +- Rust([指南][1]) + - 编译源代码 +- Protobuf([指南][2]) + - 编译 proto 文件 + - 请注意,版本需要 >= 3.15。你可以使用 `protoc --version` 检查它。 +- 机器:建议内存在 16GB 以上 或者 使用[mold](https://github.com/rui314/mold)工具以降低链接时的内存使用。 + +[1]: +[2]: + +## 编译和运行 + +只需几个命令即可使用以 Standalone 模式启动 GreptimeDB 实例: + +```shell +git clone https://github.com/GreptimeTeam/greptimedb.git +cd greptimedb +cargo run -- standalone start +``` + +接下来,你可以选择与 GreptimeDB 交互的协议。 + +如果你只想构建服务器而不运行它: + +```shell +cargo build # --release +``` + +根据构建的模式(是否传递了 `--release` 选项),构建后的文件可以在 `$REPO/target/debug` 或 `$REPO/target/release` 目录下找到。 + +## 单元测试 + +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 nextest run +``` + +## Docker + +我们还通过 Docker 提供预构建二进制文件,可以在 [Docker Hub 上获取](https://hub.docker.com/r/greptime/greptimedb)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/how-to/how-to-trace-greptimedb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/how-to/how-to-trace-greptimedb.md new file mode 100644 index 0000000000..6c1d922ac6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/how-to/how-to-trace-greptimedb.md @@ -0,0 +1,80 @@ +--- +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 的官方文档。 + +通过将 `trace_id` 等信息在整个分布式数据链路上透传,使得我们能够记录整个分布式链路的函数调用链,知道每个被追踪函数的调用时间等相关信息,从而对整个系统进行诊断。 + +## 在 RPC 中定义 tracing 上下文 + +因为 tracing 框架并没有原生支持分布式追踪,我们需要手动将 `trace_id` 等信息在 RPC 消息中传递,从而正确的识别函数的调用关系。我们使用基于 [w3c 的标准](https://www.w3.org/TR/trace-context/#traceparent-header-field-values) 将相关信息编码为 `tracing_context` ,将消息附在 RPC 的 header 中。主要定义在: + +- `frontend` 与 `datanode` 交互:`tracing_context` 定义在 [`RegionRequestHeader`](https://github.com/GreptimeTeam/greptime-proto/blob/main/proto/greptime/v1/region/server.proto) 中 +- `frontend` 与 `metasrv` 交互:`tracing_context` 定义在 [`RequestHeader`](https://github.com/GreptimeTeam/greptime-proto/blob/main/proto/greptime/v1/meta/common.proto) 中 +- Client 与 `frontend` 交互:`tracing_context` 定义在 [`RequestHeader`](https://github.com/GreptimeTeam/greptime-proto/blob/main/proto/greptime/v1/common.proto) 中 + +## 在 RPC 调用中传递 tracing 上下文 + +我们构建了一个 `TracingContext` 结构体,封装了与 tracing 上下文有关的操作。[相关代码](https://github.com/GreptimeTeam/greptimedb/blob/main/src/common/telemetry/src/tracing_context.rs) + +GreptimeDB 在使用 `TracingContext::from_current_span()` 获取当前 tracing 上下文,使用 `to_w3c()` 方法将 tracing 上下文编码为符合 w3c 的格式,并将其附在 RPC 消息中,从而使 tracing 上下文正确的在分布式组件之中传递。 + +下面的例子说明了如何获取当前 tracing 上下文,并在构造 RPC 消息时正确传递参数,从而使 tracing 上下文正确的在分布式组件之中传递。 + + +```rust +let request = RegionRequest { + header: Some(RegionRequestHeader { + tracing_context: TracingContext::from_current_span().to_w3c(), + ..Default::default() + }), + body: Some(region_request::Body::Alter(request)), +}; +``` + +在 RPC 消息的接收方,需要将 tracing 上下文正确解码,并且使用该上下文构建第一个 `span` 对函数调用进行追踪。比如下面的代码就将接收到的 RPC 消息中的 `tracing_context` 使用 `TracingContext::from_w3c` 方法正确解码。并使用 `attach` 方法将新建的 `info_span!("RegionServer::handle_read")`  附上了上下文消息,从而能够跨分布式组件对调用进行追踪。 + +```rust +... +let tracing_context = request + .header + .as_ref() + .map(|h| TracingContext::from_w3c(&h.tracing_context)) + .unwrap_or_default(); +let result = self + .handle_read(request) + .trace(tracing_context.attach(info_span!("RegionServer::handle_read"))) + .await?; +... +``` + +## 使用 `tracing::instrument` 对监测代码进行埋点 + +我们使用 tracing 提供的 `instrument` 宏对代码进行埋点,只要将 `instrument` 宏标记在需要进行埋点的函数即可。 `instrument` 宏会每次将函数调用的参数以 `Debug` 的形式打印到 span 中。对于没有实现 `Debug` trait 的参数,或者结构体过大、参数过多,最后导致 span 过大,希望避免这些情况就需要使用 `skip_all`,跳过所有的参数打印。 + +```rust +#[tracing::instrument(skip_all)] +async fn instrument_function(....) { + ... +} +``` + +## 跨越 runtime 的代码埋点 + +Rust 的 tracing 库会自动处理埋点函数间的嵌套关系,但如果某个函数的调用跨越 runtime 的话,tracing 不能自动对这类调用进行追踪,我们需要手动跨越 runtime 去传递上下文。 + +```rust +let tracing_context = TracingContext::from_current_span(); +let handle = runtime.spawn(async move { + handler + .handle(query) + .trace(tracing_context.attach(info_span!("xxxxx"))) + ... +}); +``` + +比如上面这段代码需要跨越 runtime 去进行 tracing,我们先通过 `TracingContext::from_current_span()` 获取当前 tracing 上下文,通过在另外一个 runtime 里新建一个 span,并将 span 附着在当前上下文中,我们就完成了跨越 runtime 的代码埋点,正确追踪到了调用链。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/how-to/how-to-use-tokio-console.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/how-to/how-to-use-tokio-console.md new file mode 100644 index 0000000000..605035d57e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/how-to/how-to-use-tokio-console.md @@ -0,0 +1,34 @@ +--- +keywords: [tokio-console, GreptimeDB, 构建配置, 启动配置, 调试工具] +description: 介绍如何在 GreptimeDB 中启用 tokio-console,包括构建和启动时的配置方法。 +--- + +# 如何在 GreptimeDB 中启用 tokio-console + +本文介绍了如何在 GreptimeDB 中启用 [tokio-console](https://github.com/tokio-rs/console)。 + +首先,在构建 GreptimeDB 时带上 feature `cmd/tokio-console`。同时 `tokio_unstable` cfg 也必须开启: + +```bash +RUSTFLAGS="--cfg tokio_unstable" cargo build -F cmd/tokio-console +``` + +启动 GreptimeDB,可设置 tokio console 绑定的地址,配置是 `--tokio-console-addr`。`tokio_unstable` 的 cfg 也需要同时开启。例如: + +```bash +RUSTFLAGS="--cfg tokio_unstable" greptime --tokio-console-addr="127.0.0.1:6669" standalone start +``` + +这样就可以使用 `tokio-console` 命令去连接 GreptimeDB 的 tokio console 服务了: + +```bash +tokio-console [TARGET_ADDR] +``` + +"`TARGET_ADDR`" 默认是 "\"。 + +:::tip Note + +`tokio-console` 命令的安装方法参见 [tokio-console](https://github.com/tokio-rs/console)。 + +::: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/how-to/how-to-write-sdk.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/how-to/how-to-write-sdk.md new file mode 100644 index 0000000000..28ff757763 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/how-to/how-to-write-sdk.md @@ -0,0 +1,73 @@ +--- +keywords: [gRPC SDK, GreptimeDatabase, GreptimeRequest, GreptimeResponse, 插入请求] +description: 介绍如何为 GreptimeDB 开发一个 gRPC SDK,包括 GreptimeDatabase 服务的定义、GreptimeRequest 和 GreptimeResponse 的结构。 +--- + +# 如何为 GreptimeDB 开发一个 gRPC SDK + +GreptimeDB 的 gRPC SDK 只需要处理写请求即可。读请求是标准 SQL 或 PromQL,可以由任何 JDBC 客户端或 Prometheus +客户端处理。这也是为什么所有的 GreptimeDB SDK 都命名为 "`greptimedb-ingester-`"。请确保你的 GreptimeDB SDK +遵循相同的命名约定。 + +## `GreptimeDatabase` 服务 + +GreptimeDB 自定义了一个 gRPC 服务:`GreptimeDatabase` +。你只需要实现这个服务即可。你可以在[这里](https://github.com/GreptimeTeam/greptime-proto/blob/main/proto/greptime/v1/database.proto) +找到它的 Protobuf 定义。 + +`GreptimeDatabase` 有 2 个 RPC 方法: + +```protobuf +service GreptimeDatabase { + rpc Handle(GreptimeRequest) returns (GreptimeResponse); + + rpc HandleRequests(stream GreptimeRequest) returns (GreptimeResponse); +} +``` + +`Handle` 方法是一个 unary 调用:当 GreptimeDB 服务接收到一个 `GreptimeRequest` 请求后,它立刻处理该请求并返回一个相应的 +`GreptimeResponse`。 + +`HandleRequests` 方法则是一个 "[Client Streaming RPC][3]" 方式的调用。 +它可以接受一个连续的 `GreptimeRequest` 请求流,持续地发给 GreptimeDB 服务。 +GreptimeDB 服务会在收到流中的每个请求时立刻进行处理,并最终(流结束时)返回一个总结性的 `GreptimeResponse`。 +通过 `HandleRequests`,我们可以获得一个非常高的请求吞吐量。 + +### `GreptimeRequest` + +`GreptimeRequest` 是一个 Protobuf 消息,定义如下: + +```protobuf +message GreptimeRequest { + RequestHeader header = 1; + oneof request { + InsertRequests inserts = 2; + QueryRequest query = 3; + DdlRequest ddl = 4; + DeleteRequests deletes = 5; + RowInsertRequests row_inserts = 6; + RowDeleteRequests row_deletes = 7; + } +} +``` + +`RequestHeader` 是必需,它包含了一些上下文,鉴权和其他信息。"oneof" 的字段包含了发往 GreptimeDB 服务的请求。 + +注意我们有两种类型的插入请求,一种是以 "列" 的形式(`InsertRequests`),另一种是以 "行" 的形式(`RowInsertRequests` +)。通常我们建议使用 "行" 的形式,因为它对于表的插入更自然,更容易使用。但是,如果需要一次插入大量列,或者有大量的 "null" +值需要插入,那么最好使用 "列" 的形式。 + +### `GreptimeResponse` + +`GreptimeResponse` 是一个 Protobuf 消息,定义如下: + +```protobuf +message GreptimeResponse { + ResponseHeader header = 1; + oneof response {AffectedRows affected_rows = 2;} +} +``` + +`ResponseHeader` 包含了返回值的状态码,以及错误信息(如果有的话)。"oneof" 的字段目前只有 "affected rows"。 + +GreptimeDB 现在有很多 SDK,你可以参考[这里](https://github.com/GreptimeTeam?q=ingester&type=all&language=&sort=)获取一些示例。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/metasrv/admin-api.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/metasrv/admin-api.md new file mode 100644 index 0000000000..6e3251dbd8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/metasrv/admin-api.md @@ -0,0 +1,258 @@ +--- +keywords: [Admin API, 健康检查, leader 查询, 心跳检测, 维护模式] +description: 介绍 Metasrv 的 Admin API,包括健康检查、leader 查询和心跳检测等功能。 +--- + +# Admin API + +Admin 提供了一种简单的方法来查看集群信息,包括 metasrv 健康检测、metasrv leader 查询、数据库元数据查询和数据节点心跳检测。 + +Admin API 是一个 HTTP 服务,提供一组可以通过 HTTP 请求调用的 RESTful API。Admin API 简单、用户友好且安全。 +可用的 API: + +- /health +- /leader +- /heartbeat +- /maintenance + +所有这些 API 都在父资源 `/admin` 下。 + +在以下部分中,我们假设你的 metasrv 实例运行在本地主机的 4000 端口。 + +## /health HTTP 端点 + +`/health` 端点接受 GET HTTP 请求,你可以使用此端点检查你的 metasrv 实例的健康状况。 + +### 定义 + +```bash +curl -X GET http://localhost:4000/admin/health +``` + +### 示例 + +#### 请求 + +```bash +curl -X GET http://localhost:4000/admin/health +``` + +#### 响应 + +```json +OK +``` + +## /leader HTTP 端点 + +`/leader` 端点接受 GET HTTP 请求,你可以使用此端点查询你的 metasrv 实例的 leader 地址。 + +### 定义 + +```bash +curl -X GET http://localhost:4000/admin/leader +``` + +### 示例 + +#### 请求 + +```bash +curl -X GET http://localhost:4000/admin/leader +``` + +#### 响应 + +```json +127.0.0.1:4000 +``` + +## /heartbeat HTTP 端点 + +`/heartbeat` 端点接受 GET HTTP 请求,你可以使用此端点查询所有数据节点的心跳。 + +你还可以查询指定 `addr` 的数据节点的心跳数据,但在路径中指定 `addr` 是可选的。 + +### 定义 + +```bash +curl -X GET http://localhost:4000/admin/heartbeat +``` + +| 查询字符串参数 | 类型 | 可选/必选 | 定义 | +|:---------------|:-------|:----------|:--------------------| +| addr | String | 可选 | 数据节点的地址。 | + +### 示例 + +#### 请求 + +```bash +curl -X GET 'http://localhost:4000/admin/heartbeat?addr=127.0.0.1:4100' +``` + +#### 响应 + +```json +[ + [{ + "timestamp_millis": 1677049348651, + "cluster_id": 0, + "id": 1, + "addr": "127.0.0.1:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049344048, + "cluster_id": 0, + "id": 1, + "addr": "0.0.0.0:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049343624, + "cluster_id": 0, + "id": 1, + "addr": "127.0.0.1:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049339036, + "cluster_id": 0, + "id": 1, + "addr": "0.0.0.0:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049338609, + "cluster_id": 0, + "id": 1, + "addr": "127.0.0.1:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049334019, + "cluster_id": 0, + "id": 1, + "addr": "0.0.0.0:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049333592, + "cluster_id": 0, + "id": 1, + "addr": "127.0.0.1:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049329002, + "cluster_id": 0, + "id": 1, + "addr": "0.0.0.0:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049328573, + "cluster_id": 0, + "id": 1, + "addr": "127.0.0.1:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049323986, + "cluster_id": 0, + "id": 1, + "addr": "0.0.0.0:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }] +] +``` + +## /maintenance HTTP 端点 + +集群维护模式是 GreptimeDB 中的一项安全功能,它可以临时禁用自动集群管理操作。此模式在集群升级、计划停机以及任何可能暂时影响集群稳定性的操作期间特别有用。有关更多详细信息,请参阅[集群维护模式](/user-guide/deployments-administration/maintenance/maintenance-mode.md)。 + +## /procedure-manager HTTP 端点 + +该端点用于管理 Procedure Manager 状态。有关更多详细信息,请参阅[防止元数据变更](/user-guide/deployments-administration/maintenance/prevent-metadata-changes.md)。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/metasrv/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/metasrv/overview.md new file mode 100644 index 0000000000..2e3c525baa --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/metasrv/overview.md @@ -0,0 +1,162 @@ +--- +keywords: [Metasrv, 元数据存储, 请求路由, 负载均衡, 高可用性] +description: 介绍 Metasrv 的功能、架构和与前端的交互方式。 +--- + +# 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-1.0/contributor-guide/metasrv/selector.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/metasrv/selector.md new file mode 100644 index 0000000000..13aac3ad9f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/contributor-guide/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/overview.md new file mode 100644 index 0000000000..9f82a72171 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/overview.md @@ -0,0 +1,24 @@ +--- +keywords: [架构, 关键概念, 数据处理, 组件交互, 数据库] +description: 介绍 GreptimeDB 的架构、关键概念和工作原理,包括各组件的交互方式和数据处理流程。 +--- + +# 贡献者指南 + +DeepWiki 对 GreptimeDB 的架构和实现进行了详细且清晰的描述,强烈推荐阅读: + +[https://deepwiki.com/GreptimeTeam/greptimedb](https://deepwiki.com/GreptimeTeam/greptimedb) + +## 架构 + +有关 GreptimeDB 的架构和组件,请参阅用户指南中的 [架构](/user-guide/concepts/architecture.md) 文档。 + +有关每个组件的更多详细信息,请参阅以下指南: + +- [frontend][1] +- [datanode][2] +- [metasrv][3] + +[1]: /contributor-guide/frontend/overview.md +[2]: /contributor-guide/datanode/overview.md +[3]: /contributor-guide/metasrv/overview.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/tests/integration-test.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/tests/integration-test.md new file mode 100644 index 0000000000..63ffa56bc0 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/contributor-guide/tests/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/tests/overview.md new file mode 100644 index 0000000000..81b6defa45 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/tests/overview.md @@ -0,0 +1,9 @@ +--- +keywords: [测试] +description: GreptimeDB 的测试 +--- + +# 测试 + +我们的团队进行了大量测试,以确保 GreptimeDB 的行为。本章将介绍几种用于测试 GreptimeDB 的重要方法,以及如何使用它们。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/tests/sqlness-test.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/tests/sqlness-test.md new file mode 100644 index 0000000000..1258a45c9c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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 bare +``` + +它会自动完成以下步骤:编译 `GreptimeDB`,启动它,抓取测试并将其发送到服务器,然后收集和比较结果。你只需要检查是否有新的 `.output` 文件。如果没有,恭喜你,测试通过了 🥳! + +### 运行特定测试 + +```shell +cargo sqlness bare -t your_test +``` + +如果你指定了第二个参数,则只会执行名称中包含指定字符串的测试案例。Sqlness 还支持基于环境的过滤。过滤器接受正则表达式字符串,并会检查格式为 `env:case` 的案例名称。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/tests/unit-test.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/contributor-guide/tests/unit-test.md new file mode 100644 index 0000000000..79c73775b4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/db-cloud-shared/migrate/_migrate-from-prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/db-cloud-shared/migrate/_migrate-from-prometheus.md new file mode 100644 index 0000000000..bfb0fcd02a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/db-cloud-shared/migrate/_migrate-from-prometheus.md @@ -0,0 +1,31 @@ +GreptimeDB 可以用来存储 [Prometheus](https://prometheus.io/) 的时间序列数据。 +此外,GreptimeDB 通过其 HTTP API 支持 Prometheus 查询语言。 +这可以使你轻松将 Prometheus 的 long-term storage 切换到 GreptimeDB。 + +## 数据模型的区别 + +要了解 Prometheus 和 GreptimeDB 数据模型之间的差异,请参阅 Ingest Data 文档中的[数据模型](/user-guide/ingest-data/for-observability/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) + +如果您需要更详细的迁移方案或示例脚本,请提供具体的表结构和数据量信息。[GreptimeDB 官方社区](https://github.com/orgs/GreptimeTeam/discussions)将为您提供进一步的支持。欢迎加入 [Greptime Slack](http://greptime.com/slack) 社区交流。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/db-cloud-shared/migrate/migrate-from-influxdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/db-cloud-shared/migrate/migrate-from-influxdb.md new file mode 100644 index 0000000000..8cd94650fc --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/db-cloud-shared/migrate/migrate-from-influxdb.md @@ -0,0 +1,259 @@ +本文档将帮助你了解 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 + greptime_timestamp, + host, + AVG(cpu) RANGE '1h' as mean_cpu +FROM + monitor +WHERE + greptime_timestamp > NOW() - '24 hours'::INTERVAL +ALIGN '1h' TO NOW +ORDER BY greptime_timestamp 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: + + + +如果您需要更详细的迁移方案或示例脚本,请提供具体的表结构和数据量信息。[GreptimeDB 官方社区](https://github.com/orgs/GreptimeTeam/discussions)将为您提供进一步的支持。欢迎加入 [Greptime Slack](http://greptime.com/slack) 社区交流。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/autopilot/region-balancer.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/autopilot/region-balancer.md new file mode 100644 index 0000000000..195073e684 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/autopilot/region-balancer.md @@ -0,0 +1,39 @@ +--- +keywords: [Region Balancer, Datanode, 负载均衡, 窗口大小, 负载阈值, 迁移] +description: 介绍 Region Balancer 插件,通过配置窗口大小和负载阈值来均衡 Datanode 上的 Region 写入负载,避免频繁迁移。 +--- + +# Region Balancer + +该插件用于均衡 Datanode 上的 Region 写入负载,通过指定的窗口大小和负载阈值来避免频繁的 Region 迁移。可通过添加以下配置至 Metasrv 开启 Region Rebalancer 功能。 + +```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-1.0/enterprise/console-ui.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/console-ui.md new file mode 100644 index 0000000000..4e010d7d4c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/console-ui.md @@ -0,0 +1,58 @@ +--- +keywords: [企业版, 管理控制台, 仪表板, 集群管理, 数据管理, 监控, UI] +description: GreptimeDB 企业版管理控制台提供集群状态、区域管理、数据管理和监控等功能的可视化界面。 +--- + +# 管理控制台 + +GreptimeDB 企业版管理控制台是标准 GreptimeDB 仪表板的增强版本,为企业用户提供更全面的集群可观测性与运维能力。 + + +## 集群概览 + +**Overview** 页面展示集群整体运行状态和资源使用情况。 + +- **Service Overview**:CPU、内存、存储使用率;数据写入速率;各协议请求速率。 +- **Storage Overview**:数据库数、表数、区域数;Manifest、WAL、Index 文件大小。 +- **Cluster**:节点类型;节点运行状态与资源使用率。 + +![Overview](/enterprise-console-overview.png) + +## 运维操作 + +**Region Management** 提供 Region 级别的运维能力。 + +- **Datanodes 视角**:查看各数据节点及 Region 详情,包括 Region ID、所属表、存储大小、WAL/Manifest/Index 占用、行数。 +- **Tables 视角**:按表查看 Region 分布,支持展开查看 Region 信息。 +- **Region 维护**:支持 Flush 与 Compact。 +- **Region 迁移**:将 Region 从一个节点迁移到另一个节点,支持超时配置和实时迁移状态展示。 + +![Region Management - Datanodes](/enterprise-console-region-datanodes.png) + +![Region Management - Tables](/enterprise-console-region-tables.png) + +## 数据管理 + +**Data Management** 页面提供 SQL/PromQL 查询、数据写入、日志查询、日志管道、链路追踪和 Flow 管理等功能。这些功能与开源版 Dashboard 和 Cloud Dashboard 保持一致,此处不再展开说明。 + +## 监控功能 + +**Monitoring** 页面提供全方位的指标与日志监控。 + +### 指标监控(Metrics) + +提供多个分组的监控指标,包括 Overview、Ingestion、Queries、Resources、Frontend Requests、Frontend to Datanode、Mito Engine、OpenDAL、Metasrv 和 Flownode,覆盖集群运行状态、请求速率、延迟、资源使用等关键数据。 + +![Metrics](/enterprise-console-monitor-metrics.png) + +### 实例日志搜索(Instance Logs) + +支持按角色、实例、日志级别、时间范围和关键词筛选集群日志,结果可导出为 JSON。 + +![Instance Logs](/enterprise-console-instance-logs.png) + +### 慢查询分析(Slow Query) + +展示执行时间较长的 SQL/PromQL 查询,支持查看耗时、语句详情,并可使用 **Explain Query** 分析执行计划。 + +![Slow Query](/enterprise-console-slow-query.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/authentication.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/authentication.md new file mode 100644 index 0000000000..f567cc516b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/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-administration/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-1.0/enterprise/deployments-administration/backup.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/backup.md new file mode 100644 index 0000000000..23ab7c9151 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/backup.md @@ -0,0 +1,20 @@ +--- +keywords: [备份元数据, 备份数据库, GreptimeDB 备份] +description: GreptimeDB 备份指南,包括备份元数据和数据库的步骤。 +--- + +# 备份 + +## 备份元数据 + +GreptimeDB 集群的元数据存储可以存储在 etcd 或者关系数据库中。对于重要的集群,建议使用云厂商提供的关系数据库服务(rds)并开启定期备份功能。 + +请参考[元数据导出与导入工具](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md) 了解更多细节。 + +## 备份数据库 + +由于对象存储一般会存储多个副本,如果 GreptimeDB 的数据存储在对象存储上,则通常无需再额外备份数据库。你也可以考虑开启对象存储的多版本特性,以避免出现误操作导致的数据丢失。 + +你还可以使用 GreptimeDB 的 `COPY DATABASE` 功能来创建备份。 +请参考[数据导出和导入工具](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md)文档了解更多信息。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups.md new file mode 100644 index 0000000000..ee3bfbfe37 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups.md @@ -0,0 +1,99 @@ +--- +keywords: [Kubernetes, deployment, GreptimeDB, datanode groups, CRD, installation, verification] +description: 在 Kubernetes 上部署带有 datanode 组的 GreptimeDB 集群的分步指南,包括先决条件、配置、安装和验证。 +--- + +# 部署具有 Datanode 组的 GreptimeDB 集群 + +在本指南中,你将学习如何在 Kubernetes 上部署具有 datanode 组的 GreptimeDB 集群,该组由多个 datanode 实例组成。 + +## 先决条件 + +- [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 +- [GreptimeDB Operator](https://github.com/GrepTimeTeam/greptimedb-operator) >= v0.3.0 + +## 升级 operator + +安装 GreptimeDB Operator,将镜像版本设置为大于或等于 `v0.3.0`。 +有关升级 operator 的详细说明,请参阅 [GreptimeDB Operator 管理](/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md#升级)指南。 + +## Datanode 组配置 + +在企业版中,你可以配置 **datanode 组**来将读写工作负载分离到不同的组中。 +datanode 接受 `workload_types` 字段来区分其工作负载类型。支持的类型有 **`hybrid`**、**`query`** 和 **`ingest`**: + +* **`hybrid`** 是默认值,作为 `query` 和 `ingest` 的超集,允许 datanode 处理两种工作负载。 +* **`query`** 为读负载优化,datanode 只处理读负载。 +* **`ingest`** 为写负载优化,datanode 只处理写负载。 + +虽然 `hybrid` 很方便,但在同一个 datanode 上同时进行读写操作可能会相互干扰,例如,一个大查询可能占用过多资源,从而影响在线写入。为了获得最佳性能,建议将读写工作负载分离到不同的 datanode 组中。 +在配置 datanode 组时,确保每个组都包含 `name` 字段。以下 `values.yaml` 示例展示了如何定义单独的 datanode 组: + +```yaml +danodata: + enabled: false + +datanodeGroups: + - name: write + replicas: 1 + config: | + workload_types = ["ingest"] + template: + main: + resources: + requests: + cpu: 4 + memory: 8Gi + storage: + fs: + storageClassName: ${storageClassName} + storageSize: 100Gi + - name: read + replicas: 1 + config: | + workload_types = ["query"] + template: + main: + resources: + limits: + cpu: 8 + memory: 16Gi + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: + - "etcd.etcd-cluster.svc.cluster.local:2379" + +frontend: + replicas: 1 +``` + +有关为 Metasrv 配置替代元数据存储后端的指导,请参阅[元数据存储配置](/user-guide/deployments-administration/manage-metadata/configuration.md)文档。 + +你可以使用以下命令应用上述配置: +``` +helm upgrade --install ${release-name} greptime/greptimedb-cluster --namespace ${namespace} -f values.yaml +``` + +## 校验安装 + +检查 Pod 的状态: + +```bash +kubectl get pods -n default +NAME READY STATUS RESTARTS AGE +weny-cluster-datanode-read-0 1/1 Running 0 30s +weny-cluster-datanode-write-0 1/1 Running 0 30s +weny-cluster-frontend-774c76cffc-znvrw 1/1 Running 0 30s +weny-cluster-meta-58977b7897-8k2sf 1/1 Running 0 90s +``` + +## 后续步骤 + +- 为了获得最佳性能,建议[配置 frontend 组](/user-guide/deployments-administration/deploy-on-kubernetes/configure-frontend-groups.md),这确保读写流量的完全分离,实现最大隔离。 + +- 为你的表添加读副本,请参阅[读副本](/enterprise/read-replicas/overview.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/installation.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/installation.md new file mode 100644 index 0000000000..4cd87405fe --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/installation.md @@ -0,0 +1,42 @@ +--- +keywords: [Kubernetes 部署, GreptimeDB 企业版, 安装 GreptimeDB, 启动 GreptimeDB, 私有 docker 仓库, helm chart] +description: 在 Kubernetes 上安装 GreptimeDB 企业版的步骤,包括获取镜像、安装 GreptimeDB Operator 和 etcd 集群、配置 values.yaml 和启动 GreptimeDB。 +--- + +# 部署 GreptimeDB 集群 + +GreptimeDB 企业版以 docker 镜像发布。我们为每位国内的客户提供了一个单独的、托管在阿里云上的私有 docker 仓库,你可以使用 docker pull 命令直接拉取,或在 helm chart 中配置。 + +## 获取 GreptimeDB 企业版镜像 + +你需要在 helm chart 的 `values.yaml` 文件中配置镜像信息以获得专属的 GreptimeDB 企业版,例如: + +```yaml +customImageRegistry: + enabled: true + # -- pull secret 名称,可自定义,需要和 `image.pullSecrets` 保持一致 + secretName: greptimedb-custom-image-pull-secret + registry: + username: + password: + +image: + registry: + repository: + tag: + pullSecrets: + - greptimedb-custom-image-pull-secret +``` + +上述配置中, +`customImageRegistry` 中的 `registry`、`username` 和 `password` 用于创建 k8s 的 pull secret, +`image` 中的 `registry`、`repository` 和 `tag` 用于指定 GreptimeDB 企业版镜像, +因此 `customImageRegistry.secretName` 和 `image.pullSecrets` 需要保持一致以保证拉取镜像时能够找到正确的认证信息。 + +请联系 Greptime 工作人员获取上述配置项的具体值。 +Greptime 工作人员在首次交付给你 GreptimeDB 企业版时,会通过邮件或其他方式告知你 docker 仓库地址和用户名密码。请妥善保存,并切勿分享给外部人员! + +## 安装及启动 + +请参考[部署 GreptimeDB 集群](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md)文档。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/overview.md new file mode 100644 index 0000000000..75c8e8bdff --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/overview.md @@ -0,0 +1,18 @@ +--- +keywords: [Kubernetes 部署, Operator 模式, 自动化管理, 集群部署, 单机实例, 私有云, 公有云] +description: 在 Kubernetes 上部署 GreptimeDB 的概述,包括集群的安装、升级和监控等内容。 +--- + +# 在 Kubernetes 上部署 GreptimeDB + +GreptimeDB 企业版在 Kubernetes 上的部署流程与开源版基本一致,本章节将重点介绍企业版特有的部署配置和功能。 + +## 安装 + +要了解如何通过 Helm Chart 启动 GreptimeDB,请前往[安装 GreptimeDB](./installation.md) 页面。 + +## 升级 + +请前往[升级 GreptimeDB](./upgrade.md) 页面了解如何升级 GreptimeDB。 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/upgrade.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/upgrade.md new file mode 100644 index 0000000000..1bfc3e0bc7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/upgrade.md @@ -0,0 +1,17 @@ +--- +keywords: [升级 GreptimeDB, Metasrv 运维模式] +description: 在 Kubernetes 上升级 GreptimeDB 的步骤,包括直接升级和不使用 GreptimeDB Operator 升级集群的方式。 +--- + +# 升级 + +## 直接升级 + +单独升级 GreptimeDB 企业版的镜像非常简单,只需要在 helm chart 中修改 `tag` 后重启即可。 + +## 不使用 GreptimeDB Operator 升级集群 + +在不使用 GreptimeDB Operator 升级集群时,在操作各组件之前(例如,滚动升级 Datanode 节点),必须手动开启 Metasrv 的运维模式。升级完成后,需等待所有组件状态恢复健康,再关闭 Metasrv 的运维模式。在开启 Metasrv 运维模式后,集群中的 Auto Balancing(如启用)以及 Region Failover(如启用)机制将暂停触发,直至运维模式关闭。 + +请参考[管理运维模式](/user-guide/deployments-administration/maintenance/maintenance-mode.md#管理维护模式)了解如何开启和关闭运维模式。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/disaster-recovery/dr-solution-based-on-active-active-failover.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/disaster-recovery/dr-solution-based-on-active-active-failover.md new file mode 100644 index 0000000000..490c998c41 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-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/deployments-administration/disaster-recovery/overview.md#解决方案比较)" 来比较不同灾难恢复解决方案的 RPO 和 RTO。 +::: + +## 总结 + +在 GreptimeDB 的“双活互备”架构中,你可以选择不同的读写模式组合来实现你的 RPO 目标。至于 RTO,我们依赖外部机制来处理故障转移。一个 +LoadBalancer 是最适合的。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/disaster-recovery/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/disaster-recovery/overview.md new file mode 100644 index 0000000000..a8ba5a20b1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/disaster-recovery/overview.md @@ -0,0 +1,12 @@ +--- +keywords: [灾难恢复, DR 解决方案, 双活互备, 数据库, 恢复方案] +description: 概述 GreptimeDB Enterprise 中的灾难恢复解决方案,特别是基于双活互备的 DR 解决方案,并提供相关链接以获取更多信息。 +--- + +# 灾难恢复 + +作为分布式数据库,GreptimeDB 提供了不同的灾难恢复(DR)解决方案。 + +请参考 GreptimeDB OSS 文档中的[灾难恢复概述](/user-guide/deployments-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-1.0/enterprise/deployments-administration/monitoring/audit-logging.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/audit-logging.md new file mode 100644 index 0000000000..cadd26f082 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/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 +# 存储审计日志文件的目录。默认为 "./greptimedb_data/logs/"。 +dir = "./greptimedb_data/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-1.0/enterprise/deployments-administration/monitoring/check-db-status.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/check-db-status.md new file mode 100644 index 0000000000..5e29296b4a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/check-db-status.md @@ -0,0 +1,8 @@ +--- +keywords: [GreptimeDB 健康检查, GreptimeDB 运行状态, GreptimeDB 部署状态, GreptimeDB 运行指标] +description: 通过 HTTP 接口检查 GreptimeDB 的健康状态、部署状态和运行指标。 +--- + +# 检查 GreptimeDB 状态 + +请参考[开源 GreptimeDB 文档](/user-guide/deployments-administration/monitoring/check-db-status.md)了解如何检查 GreptimeDB 的健康状态。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/key-logs.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/key-logs.md new file mode 100644 index 0000000000..f093e71395 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/key-logs.md @@ -0,0 +1,24 @@ +--- +keywords: [关键日志, 错误日志, 运维日志, GreptimeDB 日志] +description: 通过关键日志了解 GreptimeDB 的运行情况,以及排查错误出现的原因。 +--- + +# 运维关键日志 + +GreptimeDB 在运行过程中,会将一些关键的操作以及预期外的错误信息输出到日志中。 +你可以通过这些日志了解 GreptimeDB 的运行情况,以及排查错误出现的原因。 + +## GreptimeDB 运维日志 + +请参考 GreptimeDB OSS 文档中的[重要日志](/user-guide/deployments-administration/monitoring/key-logs.md)部分。 + +## License 过期 + +对于 GreptimeDB 的企业版,建议监控 license 的到期日志以确保不间断使用企业版功能。 +企业版的 license 过期时,metasrv 会打印如下 warning 日志, +这时需要及时联系 Greptime 获取新的 license + +```bash +License is expired at xxx, please contact your GreptimeDB vendor to renew it +``` + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/key-metrics.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/key-metrics.md new file mode 100644 index 0000000000..fef15070a2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/key-metrics.md @@ -0,0 +1,29 @@ +--- +keywords: [监控关键指标, GreptimeDB 监控, GreptimeDB 关键指标, GreptimeDB 集群监控] +description: 监控 GreptimeDB 集群的关键指标,包括 CPU、内存、磁盘 I/O 和网络带宽的使用情况。 +--- + +# 关键指标监控 + +监控的关键指标包括 CPU、内存、磁盘 I/O 和网络带宽的使用情况。 + +## 告警指标 + +告警系统各公司一般都有自己使用的,配置方法可能各不相同,因此本文档不列举具体的告警配置方式,只列出部分需要关注的指标,可以基于这些指标配置一个是否长时间(超过数分钟)处于不正常数值的告警。你可以根据实际情况设置告警的水位。 + +| 指标 | 含义 | 参考规则 | +| --- | --- | --- | +| `sum(process_resident_memory_bytes{}) by (instance, pod)` | 进程的内存占用 | 占用率持续大于阈值 | +| `sum(rate(process_cpu_seconds_total{}[$__rate_interval]) * 1000) by (instance, pod)` | 进程的 CPU 暂用,CPU 显示的是 millicore | 利用率持续大于阈值 | +| `sum by(instance, pod) (greptime_mito_write_stall_total{instance=~"$datanode"})` | datanode 积压的写入请求数量 | 持续 n 分钟大于 0 | +| `sum(rate(greptime_table_operator_ingest_rows{instance=~"$frontend"}[$__rate_interval]))` | 当前每秒写入的行数 | 持续 n 分钟跌 0(或低于阈值) | +| `greptime_mito_compaction_failure_total` | compaction 失败 | 最近新增大于 0 | +| `greptime_mito_flush_failure_total` | flush 失败 | 最近新增大于 0 | +| `sum by(instance, pod, path, method, code) (rate(greptime_servers_http_requests_elapsed_count{path!~"/health\|/metrics"}[$__rate_interval]))` | HTTP 请求数和返回的响应码 | 响应码 200 的请求数量持续 n 分钟低于阈值或者响应码非 200 的请求数量持续 n 分钟大于正常阈值 | +| `sum by (instance, pod) (rate(greptime_mito_write_rows_total{instance=~"$datanode"}[$__rate_interval]))` | 存储引擎写入行数 | 持续 n 分钟低于正常阈值 | + +Pod 维度还建议配置磁盘告警,当磁盘水位超过某个阈值后进行告警。 +此外,也可以根据运维[关键日志](key-logs.md)中所列举的错误日志中的关键字监控以下事件: + +- Region 续租失败 +- Region failover diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/overview.md new file mode 100644 index 0000000000..289afbb482 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/overview.md @@ -0,0 +1,14 @@ +--- +keywords: [监控, GreptimeDB 监控, 监控指标, 监控配置, 监控日志] +description: GreptimeDB 监控概述,介绍 GreptimeDB 的监控指标、配置和日志等内容。 +--- + +import DocCardList from '@theme/DocCardList'; + +# 监控 + +有效的数据库管理很大程度上依赖于监控。 +你可以使用以下方法监控 GreptimeDB: + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/self-monitor-cluster.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/self-monitor-cluster.md new file mode 100644 index 0000000000..dd5861426c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/monitoring/self-monitor-cluster.md @@ -0,0 +1,116 @@ +--- +keywords: [Kubernetes 部署, 企业集群, 监控] +description: 在 Kubernetes 上为 GreptimeDB 企业集群部署自监控的完整指南,包括 Grafana 仪表板设置和配置选项 +--- + +# 自监控 GreptimeDB 集群 + +在阅读本文档之前,请确保你了解如何[在 Kubernetes 上部署 GreptimeDB 企业集群](/enterprise/deployments-administration/deploy-on-kubernetes/installation.md)。 +本文将介绍在部署 GreptimeDB 集群时如何配置监控。 + +## 快速开始 + +你可以通过在使用 Helm Chart 部署 GreptimeDB 集群时向 `values.yaml` 文件添加配置来启用监控和 [GreptimeDB 控制台](/enterprise/console-ui.md)。 +以下是部署带有监控和 GreptimeDB 控制台的最小 GreptimeDB 集群的完整 `values.yaml` 文件示例: + +```yaml +customImageRegistry: + enabled: true + # -- pull secret 名称,可自定义,需要和 `image.pullSecrets` 保持一致 + secretName: greptimedb-custom-image-pull-secret + # 请咨询工作人员获得 registry、username 和 password + registry: + username: + password: + +image: + registry: + repository: + tag: + pullSecrets: + - greptimedb-custom-image-pull-secret + +initializer: + # 请咨询工作人员获得 registry、repository 和 tag + registry: + repository: greptime/greptimedb-initializer + tag: + +monitoring: + # 启用监控 + enabled: true + +greptimedb-enterprise-dashboard: + # 启用 greptimedb-enterprise-dashboard 部署。 + # 需要首先启用监控(monitoring.enabled: true) + enabled: true + image: + # 请咨询工作人员获得 repository 和 tag + repository: + tag: + +frontend: + replicas: 1 + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + +datanode: + replicas: 1 +``` + +启用 `monitoring` 后,GreptimeDB Operator 会额外启动一个 GreptimeDB Standalone 实例来收集 GreptimeDB 集群的指标和日志。 +为了收集日志数据,GreptimeDB Operator 会在每个 Pod 中启动一个 [Vector](https://vector.dev/) Sidecar 容器。 + +当启用 `greptimedb-enterprise-dashboard` 时,GreptimeDB Operator 会部署企业版控制台,它使用为集群监控配置的 GreptimeDB Standalone 实例作为数据源,并为 GreptimeDB 集群提供管理功能。 + +使用上述 `values.yaml` 文件安装 GreptimeDB 集群: + +```bash +helm upgrade --install mycluster \ + greptime/greptimedb-cluster \ + --values /path/to/values.yaml \ + -n default +``` + +接下来参考下方的[访问 GreptimeDB 企业控制台](#访问-greptimedb-控制台)部分了解如何访问控制台。 + +## 监控配置 + +请参考开源 GreptimeDB 的[监控配置](/user-guide/deployments-administration/monitoring/cluster-monitoring-deployment.md#配置监控数据的收集)文档获取详细的监控配置说明。 + +## GreptimeDB 控制台配置 + +### 启用 GreptimeDB 控制台 + +请在 `values.yaml` 中添加以下配置启用 GreptimeDB 控制台。 +注意该功能需要首先启用监控(`monitoring.enabled: true`): + +```yaml +monitoring: + enabled: true + +greptimedb-enterprise-dashboard: + enabled: true +``` + +### 访问 GreptimeDB 控制台 + +你可以通过将服务端口转发到本地来访问 GreptimeDB 控制台: + +```bash +kubectl -n ${namespace} port-forward svc/${cluster-name}-greptimedb-enterprise-console 18080:19095 +``` + +然后打开 `http://localhost:18080` 访问 GreptimeDB 控制台。 + +有关控制台功能和界面的详细信息,请参考[控制台](/enterprise/console-ui.md)文档。 + +## 清理 PVC + +请参考开源 GreptimeDB 文档的[清理 PVC](/user-guide/deployments-administration/monitoring/cluster-monitoring-deployment.md#清理-pvc)部分。 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/overview.md new file mode 100644 index 0000000000..e8d1136431 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/deployments-administration/overview.md @@ -0,0 +1,26 @@ +--- +keywords: [鉴权认证, 部署, 监控, Kubernetes 部署, GreptimeDB 部署, GreptimeDB 监控] +description: GreptimeDB 企业版的部署指南,包括鉴权认证、Kubernetes 部署和监控等内容。 +--- + +# 部署与管理 + +在阅读本文档之前, +推荐先阅读 GreptimeDB 开源数据库版本的[部署与管理文档](/user-guide/deployments-administration/overview.md), +其文档中涵盖了所有功能企业版同样支持。 + +下面章节描述的是企业版专属功能: + +## 配置与部署 + +- [在 Kubernetes 上部署 GreptimeDB 企业版](./deploy-on-kubernetes/overview.md): 了解如何获取专用的 GreptimeDB 企业版镜像。 +- [LDAP 鉴权](authentication.md): 为 GreptimeDB 企业版提供增强的认证能力。 + +## 监控 + +[监控](./monitoring/overview.md) 章节描述了企业版中所支持的特定指标和日志。 + +## 灾难恢复 + +[灾难恢复](./disaster-recovery/overview.md)提供了确保 GreptimeDB 企业版数据持久性和可用性的策略和最佳实践。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/elasticsearch-compatible/aggregate.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/elasticsearch-compatible/aggregate.md new file mode 100644 index 0000000000..75cf33ec7a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/elasticsearch-compatible/aggregate.md @@ -0,0 +1,27 @@ +--- +keywords: [ES, Elasticsearch, GreptimeDB, QueryDSL] +description: GreptimeDB 企业版所支持的 QueryDSL 语法 +--- + +# 聚合查询 + +## 指标聚合 + +在 GreptimeDB 中,指标聚合用于对数值字段进行统计计算,例如求和、平均值、最大值、最小值等。 + +| Aggregation | 实现情况 | Description | +| ----------- | -------- | ------------------------------ | +| sum | | 聚合用于计算数值字段的总和。 | +| avg | | 聚合用于计算数值字段的平均值。 | +| max | | 聚合用于计算数值字段的最大值。 | +| min | | 聚合用于计算数值字段的最小值。 | +| count | ✅ | 聚合用于计算文档的数量。 | + +## 桶聚合 + +在 GreptimeDB 中,桶聚合用于对文档进行分组,例如按时间、种类等字段进行分桶。 + +| Aggregation | 实现情况 | Description | +| -------------- | -------- | -------------------------------- | +| date_histogram | | 聚合用于对时间字段进行分桶。 | +| terms | | 聚合用于对指定字段的值进行分组。 | diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/elasticsearch-compatible/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/elasticsearch-compatible/overview.md new file mode 100644 index 0000000000..f422e00ee5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/elasticsearch-compatible/overview.md @@ -0,0 +1,54 @@ +--- +keywords: [ES, Elasticsearch, GreptimeDB] +description: GreptimeDB 企业版与 Elasticsearch 的兼容性概述,包括数据模型、查询语法和 API 接口等方面的对比。 +--- + +# 概述 + +GreptimeDB 的 Elasticsearch 兼容层旨在提供与 Elasticsearch 的在一定程度上的兼容性,以便用户能够相对轻松地将现有的 Elasticsearch 应用程序迁移到 GreptimeDB。 + +但是,GreptimeDB 并不完全兼容 Elasticsearch 的所有功能和特性。在某些情况下,用户可能需要对其应用程序进行调整和修改,以便在 GreptimeDB 中实现相同的功能。 + +## 原理 + +本质上 GreptimeDB 是接收 Elasticsearch 的 QueryDSL 语法,并将其转换为 GreptimeDB 的查询语法,并且按照 Elasticsearch API 格式来返回数据。从而实现与 Elasticsearch 的兼容性。 + +## API 支持列表 + +| API | Method | Description | +| ------------------------------ | ------ | ------------ | +| /\{table_name\}/\_search | POST | 执行搜索查询 | +| /\{table_name\}/\_async_search | POST | 执行搜索查询 | +| /\_resolve/index/\{schema_name\} | POST | 索引文档 | +| /\{table_name\}/\_field_caps | GET | 获取字段信息 | + +## 查询支持列表 + +| Query | Description | +| ------------ | ------------ | +| match | 匹配查询 | +| match_phrase | 短语匹配 | +| match_all | 匹配所有 | +| term | 精确匹配 | +| prefix | 前缀匹配 | +| range | 范围查询 | +| exists | 字段存在查询 | +| bool | 复合查询 | +| aggregation | 聚合查询 | + +## 聚合支持列表 + +| Aggregation | 实现情况 | Description | +| -------------- | -------- | ----------- | +| avg | | 平均值 | +| sum | | 求和 | +| min | | 最小值 | +| max | | 最大值 | +| count | ✅ | 计数 | +| date_histogram | ✅ | 日期直方图 | +| histogram | | 直方图 | +| terms | | 词条聚合 | + +## 使用 Kibana 查询 GreptimeDB + +如需了解更多信息,请联系我们。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/elasticsearch-compatible/query.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/elasticsearch-compatible/query.md new file mode 100644 index 0000000000..628b616540 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/elasticsearch-compatible/query.md @@ -0,0 +1,66 @@ +--- +keywords: [ES, Elasticsearch, GreptimeDB, QueryDSL] +description: GreptimeDB 企业版所支持的 QueryDSL 语法 +--- + +# 查询 + +由于 GreptimeDB 和 Elasticsearch 的设计的目的有多不同,有众多的功能无法兼容,我们尽可能地提供了相应的替代方案。在各个具体的接口中,我们会说明 GreptimeDB 的实现方式和 Elasticsearch 的区别。 + +:::tip +所有与 boost 分数相关的功能都不支持。 + +不会自动增加并维护 `_id` 字段。如需使用,需在原始数据中包含该字段。 + +不支持使用 @timestamp 作为时间字段。 + +不允许在同一个请求中同时包含 query 和 aggregation +::: + +## 查询语法 + +### match + +在 GreptimeDB 中,`match` 查询用于匹配文本字段中的一个或多个词。 + +不支持 analyzer,auto_generate_synonyms_phrase_query,fuzziness,max_expansions,prefix_length, +fuzzy_transpositions,fuzzy_rewrite,lenient,operator,minimum_should_match,zero_terms_query。 + +### match_phrase + +在 GreptimeDB 中,`match_phrase` 查询用于匹配文本字段中的一个短语。会根据查询的数据类型来生成不同的查询,当数据类型为文本时,他会转化为 like 查询。 +当数据类型为其他类型时,他会转化为相应的等值查询。 + +不支持 analyzer,auto_generate_synonyms_phrase_query,fuzziness,max_expansions,prefix_length, +fuzzy_transpositions,fuzzy_rewrite,lenient,operator,minimum_should_match,zero_terms_query。 + +### match_all + +在 GreptimeDB 中,`match_all` 查询用于匹配所有文档。 + +### term + +在 GreptimeDB 中,`term` 查询用于匹配文本字段中的一个精确值。主要将查询转化为等值查询。 + +目前不支持 case_insensitive + +### prefix + +在 GreptimeDB 中,`prefix` 查询用于匹配文本字段中的一个前缀。主要将查询转为为一个 like 查询。 +比如你查询以 `yi` 开头的文本,实际会转化为 `LIKE 'yi%'` 的形式。 + +不支持 rewrite,case_insensitive + +### range + +在 GreptimeDB 中,`range` 查询用于匹配文本字段中的一个范围。主要将查询转化为大于等于和小于等于的条件。 + +目前不支持 format,relation,time_zone,boost + +### exists + +在 GreptimeDB 中,`exists` 查询用于匹配文本字段中存在的值。主要将查询转化为是否存在的条件。 + +### bool + +在 GreptimeDB 中,`bool` 查询用于匹配多个查询条件。主要将查询转化为 AND 和 OR 的组合条件。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/overview.md new file mode 100644 index 0000000000..a88cc0c779 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/overview.md @@ -0,0 +1,41 @@ +--- +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 支持开源版中的所有功能, +你可以阅读[用户指南](/user-guide/overview.md)文档以获取开源版的所有功能详情。 +有关开源版和企业版之间的功能对比,请参考官网的[价格页面](https://greptime.cn/pricing)或[联系我们](https://greptime.cn/contactus)。 + +GreptimeDB Enterprise 包括以下高级功能, +详情描述在本章节的文档中: + +- [基于双活互备的 DR 解决方案](./deployments-administration/disaster-recovery/overview.md):通过高级灾难恢复解决方案确保服务不中断和数据保护。 +- [部署 GreptimeDB](./deployments-administration/overview.md):设置认证信息及其他关键配置后,将 GreptimeDB 部署在 Kubernetes 上并监控关键指标。 +- [审计日志](./deployments-administration/monitoring/audit-logging.md):记录数据库用户行为的日志。 +- [自动分区平衡](./autopilot/region-balancer.md):通过分区监控和迁移在 datanode 之间自动平衡负载。 +- [Elasticsearch 查询兼容性](./elasticsearch-compatible/overview.md):在 Kibana 中以 GreptimeDB 作为后端。 +- [Greptime 企业版管理控制台](./console-ui.md):加强版本的管理界面,提供更多的集群管理和监控功能。 +- [读副本](./read-replicas/overview.md):专门运行复杂的查询操作的 datanode,避免影响实时写入。 +- [Trigger](./trigger.md):定时查询和检测预配置的规则,可触发外部 webhook,兼容 Prometheus AlertManager。 +- Flow 的可靠性功能。 + +## 发布说明 + +- [25.05](./release-notes/release-25_05.md) +- [24.11](./release-notes/release-24_11.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replica.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replica.md new file mode 100644 index 0000000000..43eddc80de --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replica.md @@ -0,0 +1,178 @@ +--- +keywords: [企业版, 集群, 读副本, leader region, follower region] +description: GreptimeDB 企业版的读副本功能的概述, 原理, 和"如何". +--- + +# 读副本 + +读副本(Read Replica)是 GreptimeDB 企业集群版中的一项重要功能,旨在提高数据库系统的整体读写性能和可扩展性。在读副本功能中,客户端将数据写入 “Leader” Region。Leader Region 再将数据同步到 “Follower” Region。Follower Region 只提供读功能,是为 Leader Region 的读副本。Leader Region 和 Follower Region 分别部署在不同的 Datanode 节点上,可有效分隔读写请求对于系统资源的互相抢占,带来更平滑的整体读写体验: + +

+ read-replica-overview +

+ +:::tip NOTE +读副本功能仅在企业集群版中存在。 +::: + +## 原理 + +GreptimeDB 企业集群版基于自身架构的特点,可以使数据在副本之间以近乎零成本地同步。另外,读副本也可以无延迟地读取到最新写入的数据。下面简单介绍读副本的数据同步和数据读取的原理。 + +### 数据同步 + +在存算分离的 GreptimeDB 企业集群版中,所有的数据都以一个个 SST 文件存放在对象存储里。那么 Leader Region 和 Follower Region 之间的数据同步,就不需要在两个 Region 之间复制 SST 文件了,而只需要同步 SST 文件的元信息即可。元信息相比 SST 文件小多了,Leader Region 可以很容易地将其同步到 Follower Region 上。一旦元信息同步完成,读副本就“拥有”了一样的 SST 文件,从而读到数据。如下图: + +![read-replica-data-sync](/read-replica-data-sync.png) + +在实际的实现中,SST 文件元信息持久化在一个特殊的 manifest 文件中。manifest 文件和 SST 文件一样,也保存在对象存储中。每个 manifest 文件有一个唯一的版本号。在 Leader Region 和 Follower Region 之间同步 SST 文件元信息实际就是同步这个 manifest 文件的版本号。这个版本号只是一个整形数字,所以同步的成本非常低。Follower Region 在得到 manifest 文件版本号后,就可以去对象存储获取 manifest 文件了,从而就获取了 Leader Region 生成的 SST 文件元信息。 + +manifest 文件版本号是通过 Region 与 Metasrv 之间的心跳进行同步的。Leader Region 在向 Metasrv 的心跳中带上这个版本号。Metasrv 再在回复 Follower Region 的心跳时,将这个版本号返回。如下图: + +![read-replica-heartbeat](/read-replica-heartbeat.png) + +容易看出,如果只有 SST 文件的同步,读副本读到写入数据的延迟是 Leader Region 和 Follower Region 与 Metasrv 之间的心跳间隔之和。假如两个 Region 的心跳间隔都是默认的 3 秒,那么读副本只能读到 3 到 6 秒前写入 SST 文件并 flush 到对象存储的数据。如果客户端对读副本能读到的写入数据的新鲜度要求不高,那么这种数据同步方法就足够了。但如果要求读副本能及时读到最新写入的数据,读副本还需要下面的功能: + +### 数据读取 + +最新写入 GreptimeDB 的数据会保存在 Leader Region 的 memtable 里。所以读副本要想读到最新写入的数据,Follower Region 只要能向 Leader Region 发起请求,获取 memtable 中的数据即可。 + +Follower Region 将 Leader Region 的 memtable 中的数据,和自己通过上面数据同步的方式获得的 SST 文件中的数据相结合,就得到了客户端想要的完整的包含了最新写入的数据: + +

+ read-replica-data-read +

+ +Follower Region 通过我们内部的 GRPC 接口请求 Leader Region。读副本功能会对 Leader Region 造成一定的读负载。但在通常情况下,Leader Region 只需要读取自己 memtable 中的数据,都在内存当中;而且 memtable 大小有限,读的压力不大。 + +## 增加读副本 + +增加读副本很简单,一条 SQL 即可: + +```sql +ADMIN ADD_TABLE_FOLLOWER(, ) +``` + +调用 GreptimeDB 的增加读副本的函数,需要两个参数: + +- table_name:表名; +- follower_datanodes:要放置 Follower Region 的 Datanode Id 列表,用逗号分隔。 + +下面用一个例子说明如何配置读副本。 + +首先启动一个有 3 个 Datanode 节点的 GreptimeDB 企业集群版,然后建表: + +```sql +CREATE TABLE foo ( + ts TIMESTAMP TIME INDEX, + i INT PRIMARY KEY, + s STRING, +) PARTITION ON COLUMNS ('i') ( + i <= 0, + i > 0, +); +``` + +通过 `information_schema`,我们可以看到这张表的 Region 相关信息: + +```sql +SELECT table_name, region_id, peer_id, is_leader FROM information_schema.region_peers WHERE table_name = 'foo'; + ++------------+---------------+---------+-----------+ +| table_name | region_id | peer_id | is_leader | ++------------+---------------+---------+-----------+ +| foo | 4402341478400 | 1 | Yes | +| foo | 4402341478401 | 2 | Yes | ++------------+---------------+---------+-----------+ +``` + +可以看到,这张表有 2 个 Region,分别在 Datanode 1 和 2 上。 + +接下来就可以给这张表创建读副本了: + +```sql +ADMIN ADD_TABLE_FOLLOWER('foo', '0,1,2'); +``` + +读副本创建完,通过 `information_schema`,我们看到这张表已有 Follower Region 了: + +```sql +SELECT table_name, region_id, peer_id, is_leader FROM information_schema.region_peers WHERE table_name = 'foo'; + ++------------+---------------+---------+-----------+ +| table_name | region_id | peer_id | is_leader | ++------------+---------------+---------+-----------+ +| foo | 4402341478400 | 1 | Yes | +| foo | 4402341478400 | 0 | No | +| foo | 4402341478401 | 2 | Yes | +| foo | 4402341478401 | 1 | No | ++------------+---------------+---------+-----------+ +``` + +两个 Follower Region 分别在 Datanode 1 和 2 上。 + +## 使用读副本 + +客户端如何选择是否读 Follower Region 呢?对于 JDBC 连接(MySQL 和 PostgreSQL 协议),可以执行以下 SQL: + +```sql +-- 当前连接的读请求指向 Follower Region +-- 如果没有 Follower Region,会报错给客户端: +SET READ_PREFERENCE='follower' + +-- 当前连接的读请求优先使用 Follower Region +-- 如果没有 Follower Region,则读请求 fallback 到 Leader Region(客户端不报错): +SET READ_PREFERENCE='follower_preferred' + +-- 当前连接的读请求指向 Leader Region: +SET READ_PREFERENCE='leader' +``` + +还是以上面创建的表为例。首先插入一些数据: + +```sql +INSERT INTO foo (ts, i, s) VALUES (1, -1, 's1'), (2, 0, 's2'), (3, 1, 's3'); +``` + +设置从 Follower Region 读取数据: + +```sql +SET READ_PREFERENCE='follower'; +``` + +查数据: + +```sql +SELECT * FROM foo ORDER BY ts; + ++----------------------------+------+------+ +| ts | i | s | ++----------------------------+------+------+ +| 1970-01-01 00:00:00.001000 | -1 | s1 | +| 1970-01-01 00:00:00.002000 | 0 | s2 | +| 1970-01-01 00:00:00.003000 | 1 | s3 | ++----------------------------+------+------+ +``` + +如何确定确实读到了 Follower Region 呢?可以使用 `EXPLAIN ANALYZE`: + +```sql +EXPLAIN ANALYZE SELECT * FROM foo ORDER BY ts; +``` + +可以看到输出的结果中 "`other_ranges`" 大于 0。 + +若使用 `VERBOSE`: + +```sql +EXPLAIN ANALYZE VERBOSE SELECT * FROM foo ORDER BY ts; +``` + +还有类似如下的输出: + +```plaintext +extension_ranges: [LeaderMemtableRange{leader: Peer { id: 1, addr: "192.168.50.189:14101" }, num_rows: 2, time_range: (1::Millisecond, 2::Millisecond) +``` + +这在从 Leader Region 读时是没有的。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replicas/manage-read-replicas.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replicas/manage-read-replicas.md new file mode 100644 index 0000000000..69cdf5b59d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replicas/manage-read-replicas.md @@ -0,0 +1,183 @@ +--- +keywords: [企业版, 集群, 读副本, 管理, region, follower] +description: 在 GreptimeDB 企业版中管理读副本的概览、关键概念与操作指南。 +--- + +# 管理读副本 + +本文介绍如何在 GreptimeDB 企业版中管理读副本,包括在表与 Region 级别添加/移除读副本、使用 `SHOW REGION` 查看副本分布,以及放置约束与性能最佳实践建议。 + +## 为表添加读副本 + +添加读副本只需一条 SQL: + +```sql +ADMIN ADD_TABLE_FOLLOWER() +``` + +每个 Region 的 Follower 节点会基于 Datanode 的工作负载类型进行分配。**为获得最佳性能,强烈建议先[配置 Datanode 分组](/enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups.md),将读与写工作负载分别放置在不同的 Datanode 组中。** + +该函数的参数: + +- `table_name`:需要添加读副本的表名。 + +示例步骤: + +先启动一个包含 3 个 Datanode 的企业集群,然后建表: + +```sql +CREATE TABLE foo ( + ts TIMESTAMP TIME INDEX, + i INT PRIMARY KEY, + s STRING, +) PARTITION ON COLUMNS ('i') ( + i <= 0, + i > 0, +); +``` + +使用 `SHOW REGION` 查看当前 Region 分布: + +```sql +SHOW REGION FROM foo; + ++-------+---------------+------+--------+ +| Table | Region | Peer | Leader | ++-------+---------------+------+--------+ +| foo | 4398046511104 | 0 | Yes | +| foo | 4398046511105 | 1 | Yes | ++-------+---------------+------+--------+ +``` + +上述结果表明在 Datanode `0` 与 `1` 上各有一个写副本 Region。 + +接着添加读副本: + +```sql +ADMIN ADD_TABLE_FOLLOWER('foo'); +``` + +再次查看 Region 分布: + +```sql +SHOW REGION FROM foo; + ++-------+---------------+------------+--------+ +| Table | Region | Peer | Leader | ++-------+---------------+------------+--------+ +| foo | 4398046511104 | 0 | Yes | +| foo | 4398046511104 | 4294967296 | No | +| foo | 4398046511105 | 1 | Yes | +| foo | 4398046511105 | 4294967297 | No | ++-------+---------------+------------+--------+ +``` + +现在可以看到读副本已经分配到 Peer `4294967296` 与 `4294967297` 上。 + +## 从表移除读副本 + +移除读副本同样只需一条 SQL: + +```sql +ADMIN REMOVE_TABLE_FOLLOWER() +``` + +该函数参数: + +- `table_name`:要移除读副本的表名。 + +该命令会从每个 Region 中移除**最近添加的**一个读副本。 + +示例,执行前: + +```sql +SHOW REGION FROM foo; ++-------+---------------+------------+--------+ +| Table | Region | Peer | Leader | ++-------+---------------+------------+--------+ +| foo | 4398046511104 | 0 | Yes | +| foo | 4398046511104 | 4294967296 | No | +| foo | 4398046511104 | 4294967297 | No | +| foo | 4398046511105 | 1 | Yes | +| foo | 4398046511105 | 4294967296 | No | +| foo | 4398046511105 | 4294967297 | No | ++-------+---------------+------------+--------+ +``` + +此时 Region `4398046511104` 与 `4398046511105` 各有两个读副本在 `4294967296`、`4294967297` 节点上。 + +执行: + +```sql +ADMIN REMOVE_TABLE_FOLLOWER('foo'); ++------------------------------------+ +| ADMIN REMOVE_TABLE_FOLLOWER('foo') | ++------------------------------------+ +| 0 | ++------------------------------------+ +``` + +每个 Region 最近添加的读副本被移除: + +- Region `4398046511104`:移除了 `4294967297` 节点上的读副本 +- Region `4398046511105`:移除了 `4294967296` 节点上的读副本 + +结果: + +```sql +SHOW REGION FROM foo; ++-------+---------------+------------+--------+ +| Table | Region | Peer | Leader | ++-------+---------------+------------+--------+ +| foo | 4398046511104 | 0 | Yes | +| foo | 4398046511104 | 4294967296 | No | +| foo | 4398046511105 | 1 | Yes | +| foo | 4398046511105 | 4294967297 | No | ++-------+---------------+------------+--------+ +``` + +## 为 Region 添加读副本 + +```sql +ADMIN ADD_REGION_FOLLOWER(, ) +``` + +参数说明: + +- `region_id`:需要添加读副本的 Region ID。 +- `datanode_id`:要承载该读副本的 Datanode ID。 + +同一 Datanode 上不能同时承载同一 Region 的写副本与读副本;且每个 Datanode 对同一 Region 仅能承载一个读副本。 + +示例: + +```sql +-- 在 Datanode 2 上为 Region 4398046511104 添加一个读副本 +ADMIN ADD_REGION_FOLLOWER(4398046511104, 2); +``` + +若目标 Datanode 已存在该 Region 的读副本,或该 Datanode 已存在该 Region 的写副本,则命令会被拒绝。 + +## 从 Region 移除读副本 + +```sql +ADMIN REMOVE_REGION_FOLLOWER(, ) +``` + +参数说明: + +- `region_id`:需要移除读副本的 Region ID。 +- `datanode_id`:要移除的读副本所在的 Datanode ID。 + +示例: + +```sql +-- 从 Datanode 2 上移除 Region 4398046511104 的读副本 +ADMIN REMOVE_REGION_FOLLOWER(4398046511104, 2); +``` + +## 下一步 + +* [从读副本查询](/enterprise/read-replicas/query-read-replicas.md) + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replicas/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replicas/overview.md new file mode 100644 index 0000000000..d59e5a3426 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replicas/overview.md @@ -0,0 +1,50 @@ +--- +keywords: [企业版, 集群, 读副本, leader region, follower region] +description: GreptimeDB 企业版读副本功能的概述与原理。 +--- + +# 概述 + +*读副本 (Read Replica)* 是 GreptimeDB 企业集群版中的一项重要功能,旨在提升系统的整体读写性能与可扩展性。 + +在读副本机制中,客户端将数据写入写副本 (Leader Region),随后由 Leader Region 将数据同步到 Follower Region。Follower Region 作为 Leader Region 的只读副本。通过[配置 Datanode 组](/enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups.md),可以将 Leader Region 与 Follower Region 分别部署在不同的 Datanode 节点上,读写请求能够有效隔离,避免资源争用,从而获得更平滑的读写体验: + +

+ read-replica-overview +

+ + +## 原理 + +GreptimeDB 企业集群版基于存算分离架构,使副本间的数据同步几乎零成本;同时,读副本也能以极低延迟读取到最新写入的数据。下面分别介绍数据同步与数据读取机制。 + +### 数据同步 + +在 GreptimeDB 中,计算与存储解耦,所有数据以 SST 文件的形式存放在对象存储中。因此,Leader Region 与 Follower Region 之间无需复制 SST 文件本体,只需同步其元信息即可。元信息相比 SST 文件体量小得多,因而同步开销极低。一旦元信息同步完成,读副本便“拥有”相同的 SST 文件,从而可以读取数据: + +![read-replica-data-sync](/read-replica-data-sync.png) + +在实现上,SST 文件的元信息持久化在一个特殊的 manifest 文件中(同样位于对象存储)。每个 manifest 文件都有唯一的版本号。Leader Region 与 Follower Region 之间的同步,本质上就是同步这个版本号——一个简单的整数,开销极小。Follower Region 获得版本号后即可从对象存储拉取对应的 manifest 文件,从而获得 Leader Region 生成的 SST 元信息。 + +manifest 版本号通过 Region 与 Metasrv 之间的心跳进行同步:Leader Region 在发往 Metasrv 的心跳中携带版本号,Metasrv 在回复 Follower Region 的心跳中将其下发: + +![read-replica-heartbeat](/read-replica-heartbeat.png) + +可以看出,若仅依赖 SST 文件层面的同步,读副本读到新写入数据的延迟约为 Leader Region 与 Follower Region 分别到 Metasrv 的心跳间隔之和。以默认 3 秒心跳为例,读副本通常只能读到 3–6 秒前已写入并 flush 至对象存储的数据。对于对数据“新鲜度”要求不高的场景已足够,但若需要近实时读取,还需配合下述机制。 + +### 数据读取 + +最新写入的数据首先保存在 Leader Region 的 memtable 中。为了读到这些最新数据,Follower Region 需要向 Leader Region 请求 memtable 数据,并与自身通过前述同步机制获得的 SST 数据合并,从而向客户端提供包含最新写入的完整结果集: + +

+ read-replica-data-read +

+ +Follower Region 通过内部 gRPC 接口从 Leader Region 获取 memtable 数据。该过程会给 Leader Region 带来一定读负载,但由于 memtable 位于内存且大小受限,通常影响可控。 + +## 下一步 + +* [管理读副本](/enterprise/read-replicas/manage-read-replicas.md) +* [从读副本查询](/enterprise/read-replicas/query-read-replicas.md) + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replicas/query-read-replicas.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replicas/query-read-replicas.md new file mode 100644 index 0000000000..f7391eb52d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/read-replicas/query-read-replicas.md @@ -0,0 +1,95 @@ +--- +keywords: [企业版, 集群, 读副本, 查询, 读优先级] +description: 在 GreptimeDB 企业版中从读副本查询的用法、读优先策略与示例。 +--- + +# 从读副本查询 + +GreptimeDB 允许从**读副本 (Follower Region)** 读取数据,从而降低写副本 (Leader Region) 的负载并提升查询伸缩性。你可以通过 **SQL** 与 **HTTP** 两种方式设置读优先策略。 + +## 读优先策略 + +`READ_PREFERENCE` 支持如下取值: + +- `leader`:始终从写副本读取。 +- `follower`:仅从读副本读取;若不存在读副本,则查询失败。 +- `follower_preferred`:优先从读副本读取;若不可用则回退到写副本。 + +## SQL 协议 + +在 SQL 会话中设置读优先: + +```sql +SET READ_PREFERENCE = 'follower'; +``` + +--- + +## HTTP 协议 + +在 HTTP 请求中通过请求头指定 `X-Greptime-Read-Preference`: + +```bash +curl -X POST \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -H "X-Greptime-Read-Preference: follower" \ + -d "sql=select * from monitoring" \ + http://localhost:4000/v1/sql +``` + +--- + +## 示例:从读副本读取 + +在从读副本读取之前,需要先为表添加读副本。参见[副本管理](/enterprise/read-replicas/manage-read-replicas.md)。 + +向示例表插入数据: + +```sql +INSERT INTO foo (ts, i, s) +VALUES + (1, -1, 's1'), + (2, 0, 's2'), + (3, 1, 's3'); +``` + +设置从读副本读取: + +```sql +SET READ_PREFERENCE = 'follower'; +``` + +查询数据: + +```sql +SELECT * FROM foo ORDER BY ts; + ++----------------------------+------+------+ +| ts | i | s | ++----------------------------+------+------+ +| 1970-01-01 00:00:00.001000 | -1 | s1 | +| 1970-01-01 00:00:00.002000 | 0 | s2 | +| 1970-01-01 00:00:00.003000 | 1 | s3 | ++----------------------------+------+------+ +``` + +--- + +## 验证是否从读副本读取 + +可以使用 `EXPLAIN ANALYZE` 进行验证: + +```sql +EXPLAIN ANALYZE SELECT * FROM foo ORDER BY ts; +``` + +- 当输出中的 `other_ranges` 大于 0 时,表示查询涉及了读副本。 +- 若使用 `VERBOSE` 选项,将看到类似如下的详细信息: + +```plaintext +extension_ranges: [LeaderMemtableRange{leader: Peer { id: 1, addr: "192.168.50.189:14101" }, num_rows: 2, time_range: (1::Millisecond, 2::Millisecond) ... +``` + +如果仅从写副本读取,上述 `extension_ranges` 段不会出现。 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/release-notes/release-24_11.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/release-notes/release-24_11.md new file mode 100644 index 0000000000..d00ea86d01 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/enterprise/release-notes/release-25_05.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/release-notes/release-25_05.md new file mode 100644 index 0000000000..68c74f119c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/release-notes/release-25_05.md @@ -0,0 +1,67 @@ +--- +keywords: [elasticsearch, 读副本, 触发器] +description: GreptimeDB 企业版 25.05 发布说明,新功能 Elasticsearch 兼容层,读副本,触发器等 +--- + +# Release 25.05 + +我们很高兴向大家介绍 GreptimeDB 企业版的 25.05 版本。 + +## 特性亮点 + +### Elasticsearch 兼容层 + +此为 GreptimeDB Enterprise 中的 Elasticsearch 兼容层,这层允许用户将 GreptimeDB +配置为 Kibana 界面的后端,进行日志的搜索、聚合和大盘构建。 + +本次发布支持的查询: + +- match +- match_all +- multi_match +- term +- terms +- prefix +- wildcard +- regexp +- range +- exists +- bool + +### 读副本 + +为了更好地支持分析型查询和其他高代价的查询,本版本中我们设计了专门的查询节点。这 +类节点将专门执行查询,因此在使用时可以将资源尽可能使用而不用担心影响数据的在线写 +入。 + +得益于我们的存算分离架构,增加专门的读节点并不是非常大的架构重构。一种新的 +datanode 角色将承担这种任务。由于数据存储在对象存储上,在创建读节点时不会产生由 +datanode 向新节点的数据拷贝,创建的过程成本很低。用户在发送查询时可以指定查询是 +否要运行在读副本上。 + +### 触发器 + +GreptimeDB 的触发器定期检查用户配置的规则,如果满足条件就将触发下游的 webhook。 +当前发布的是触发器的首个版本,我们设计的目标也是让它可以和 Prometheus +AlertManager 一起工作。注意这不是关系型数据库中的触发器。 + +```sql +CREATE TRIGGER IF NOT EXISTS cpu_monitor + ON (SELECT host AS host_label, cpu, memory FROM machine_monitor WHERE cpu > 1) + EVERY '5 minute'::INTERVAL + LABELS (severity = 'warning') + ANNOTATIONS (summary = 'CPU utilization is too high', link = 'http://...') + NOTIFY( + WEBHOOK alert_manager URL 'http://127.0.0.1:9093' WITH (timeout="1m") + ); +``` + +### Flow Reliability + +Flow 增加了可靠性功能: + +- 任务迁移:在多个 flow 节点之间调度任务,可以保持负载均衡或高可用。 + +## GreptimeDB 开源版特性 + +本版本基于 GreptimeDB 开源版 v0.14。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/trigger.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/trigger.md new file mode 100644 index 0000000000..a4dea01271 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/enterprise/trigger.md @@ -0,0 +1,146 @@ +--- +keywords: [触发器, 告警, GreptimeDB 企业版, SQL, Webhook] +description: GreptimeDB 触发器概述。 +--- + +# Trigger + +Trigger 允许用户基于 SQL 语句定义触发规则,GreptimeDB 根据这些触发规则进行周期性 +计算,当满足条件后对外发出通知。 + +本篇文档的下述内容通过一个示例来展示如何使用 Trigger 监控系统负载并触发告警。 +如果想了解如何撰写 Trigger 的具体语法,请参考[语法](/reference/sql/trigger-syntax.md)文档。 + +# 快速入门示例 + +本节将通过一个端到端示例展示如何使用触发器监控系统负载并触发告警。 + +下图展示了该示例的完整端到端工作流程。 + +![触发器演示架构](/trigger-demo-architecture.png) + +1. Vector 持续采集主机指标并写入 GreptimeDB。 +2. GreptimeDB 中的 Trigger 每分钟评估规则;当条件满足时,会向 Alertmanager 发送 + 通知。 +3. Alertmanager 依据自身配置完成告警分组、抑制及路由,最终通过 Slack 集成将消息 + 发送至指定频道。 + +## 使用 Vector 采集主机指标 + +首先,使用 Vector 采集本机的负载数据,并将数据写入 GreptimeDB 中。Vector 的配置 +示例如下所示: + +```toml +[sources.in] +type = "host_metrics" +scrape_interval_secs = 15 + +[sinks.out] +inputs = ["in"] +type = "greptimedb" +endpoint = "localhost:4001" +``` + +GreptimeDB 会在数据写入的时候自动创建表,其中,`host_load1`表记录了 load1 数据, +load1 是衡量系统活动的关键性能指标。我们可以创建监控规则来跟踪此表中的值。表结构 +如下所示: + +```sql ++-----------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-----------+----------------------+------+------+---------+---------------+ +| ts | TimestampMillisecond | PRI | NO | | TIMESTAMP | +| collector | String | PRI | YES | | TAG | +| host | String | PRI | YES | | TAG | +| val | Float64 | | YES | | FIELD | ++-----------+----------------------+------+------+---------+---------------+ +``` + +## 配置 Alertmanager 与 Slack 集成 + +GreptimeDB Trigger 的 Webhook payload 与 [Prometheus Alertmanager](https://prometheus.io/docs/alerting/latest/alertmanager/) +兼容,因此我们可以复用 Alertmanager 的分组、抑制、静默和路由功能,而无需任何额外 +的胶水代码。 + +你可以参考 [官方文档](https://prometheus.io/docs/alerting/latest/configuration/) +对 Prometheus Alertmanager 进行配置。为在 Slack 消息中呈现一致、易读的内容,可以 +配置以下消息模板。 + +```text +{{ define "slack.text" }} +{{ range .Alerts }} + +Labels: +{{- range .Labels.SortedPairs }} +- {{ .Name }}: {{ .Value }} +{{ end }} + +Annotations: +{{- range .Annotations.SortedPairs }} +- {{ .Name }}: {{ .Value }} +{{ end }} + +{{ end }} +{{ end }} +``` + +使用上述模板生成 slack 消息会遍历所有的告警,并把每个告警的标签和注解展示出来。 + +当配置完成之后,启动 Alertmanager。 + +## 创建 Trigger + +在 GreptimeDB 中创建 Trigger。使用 MySql 客户端连接 GreptimeDB 并执行以下 SQL: + +```sql +CREATE TRIGGER IF NOT EXISTS load1_monitor + ON ( + SELECT collector AS label_collector, + host as label_host, + val + FROM host_load1 WHERE val > 10 and ts >= now() - '1 minutes'::INTERVAL + ) EVERY '1 minute'::INTERVAL + LABELS (severity=warning) + ANNOTATIONS (comment='Your computer is smoking, should take a break.') + NOTIFY( + WEBHOOK alert_manager URL 'http://localhost:9093' WITH (timeout="1m") + ); +``` + +上述 SQL 将创建一个名为 `load1_monitor` 的触发器,每分钟运行一次。它会评估 `host_load1` +表中最近 60 秒的数据;如果任何 load1 值超过 10,则 `NOTIFY` 子句中的 `WEBHOOK` +选项会指定 Trigger 向在本地主机上运行且端口为 9093 的 Alertmanager 发送通知。 + +执行 `SHOW TRIGGERS` 查看已创建的触发器列表。 + +```sql +SHOW TRIGGERS; +``` + +输出结果应如下所示: + +```text ++---------------+ +| Triggers | ++---------------+ +| load1_monitor | ++---------------+ +``` + +## 测试 Trigger + +使用 [stress-ng](https://github.com/ColinIanKing/stress-ng) 模拟 60 秒的高 CPU 负载: + +```bash +stress-ng --cpu 100 --cpu-load 10 --timeout 60 +``` + +load1 值将快速上升,Trigger 通知将被触发,在一分钟之内,指定的 Slack 频道将收到如下 +告警: + +![Slack 告警示意图](/trigger-slack-alert.png) + +## 参考资料 + +- [Trigger 语法](/reference/sql/trigger-syntax.md): 与 `TRIGGER` 相关的 SQL 语句的语法细节。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/faq-and-others/faq.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/faq-and-others/faq.md new file mode 100644 index 0000000000..a2afd91120 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/faq-and-others/faq.md @@ -0,0 +1,418 @@ +--- +keywords: [统一可观测性, metrics, logs, traces, 性能, OpenTelemetry, Prometheus, Grafana, 云原生, SQL, PromQL] +description: 关于 GreptimeDB 的常见问题解答 - 统一可观测性数据库,支持 metrics、logs 和 traces。 +--- + +# 常见问题 + +## 核心能力 + +### 什么是 GreptimeDB? + +GreptimeDB 是一个开源、云原生的统一可观测性数据库,旨在在单一系统中存储和分析 metrics、logs 和 traces。基于 Rust 构建以实现高性能,它提供: +- 高达 50 倍的运营和存储成本降低 +- 在 PB 级数据集上实现亚秒级查询响应 +- 原生 OpenTelemetry 支持 +- SQL、PromQL 和流处理能力 +- 计算存储分离,实现灵活扩展 + +### GreptimeDB 的性能与其他解决方案相比如何? + +GreptimeDB 在可观测性工作负载中提供卓越性能: + +**写入性能**: +- 比 Elasticsearch **快 2-4.7倍**(高达 470% 吞吐量) +- 比 Loki **快 1.5倍**(121k vs 78k rows/s) +- 比 InfluxDB **快 2倍**(250k-360k rows/s) +- **媲美 ClickHouse**(达到 111% 吞吐量) + +**查询性能**: +- 日志查询比 Loki **快 40-80倍** +- 重复查询**快 500倍**(缓存优化) +- 复杂时序查询比 InfluxDB **快 2-11倍** +- 与 ClickHouse 在不同查询模式下性能相当 + +**存储与成本效率**: +- 存储占用比 Elasticsearch **少 87%**(仅需 12.7%) +- 比 ClickHouse **节省 50%** 存储 +- 比 Loki **节省 50%** 存储(3.03GB vs 6.59GB 压缩后) +- 运营成本比传统架构**降低 50倍** + +**资源优化**: +- CPU 使用率**减少 40%** +- 在测试数据库中**内存消耗最低** +- 对象存储(S3/GCS)上性能一致 +- 卓越的高基数数据处理 + +**独特优势**: +- 单一数据库处理 metrics、logs 和 traces +- 原生云原生架构 +- 水平扩展能力(处理 11.5亿+ 行数据) +- 原生全文搜索和索引 + +基准测试报告:[vs InfluxDB](https://greptime.cn/blogs/2024-08-08-report) | [vs Loki](https://greptime.cn/blogs/2025-08-07-beyond-loki-greptimedb-log-scenario-performance-report.html) | [日志基准测试](https://greptime.cn/blogs/2025-03-07-greptimedb-log-benchmark) + +### GreptimeDB 如何处理 metrics、logs 和 traces? + +GreptimeDB 设计为统一可观测性数据库,原生支持三种遥测数据类型: +- **Metrics**:完全兼容 Prometheus,支持 PromQL +- **Logs**:全文索引、Loki 协议支持和高效压缩 +- **Traces**:实验性 OpenTelemetry trace 存储,支持可扩展查询 + +这种统一方法消除了数据孤岛,无需复杂的数据管道即可实现跨信号关联。 + +详细文档: +- [日志概述](/user-guide/logs/overview.md) +- [链路追踪概述](/user-guide/traces/overview.md) +- [OpenTelemetry 兼容性](/user-guide/ingest-data/for-observability/opentelemetry.md) +- [Prometheus 兼容性](/user-guide/ingest-data/for-observability/prometheus.md) +- [Loki 协议兼容性](/user-guide/ingest-data/for-observability/loki.md) +- [Elasticsearch 兼容性](/user-guide/ingest-data/for-observability/elasticsearch.md) +- [Vector 兼容性](/user-guide/ingest-data/for-observability/vector.md) + +### GreptimeDB 的主要应用场景是什么? + +GreptimeDB 擅长于: +- **统一可观测性**:用单一数据库替代复杂的监控堆栈 +- **边缘和云数据管理**:跨环境无缝数据同步 +- **IoT 和汽车**:高效处理大量传感器数据 +- **AI/LLM 监控**:跟踪模型性能和行为 +- **实时分析**:在 PB 级数据集上实现亚秒级查询 + +## 架构与性能 + +### GreptimeDB 能否替代我的 Prometheus 设置? + +是的,GreptimeDB 提供: +- 原生 PromQL 支持,兼容性接近 100% +- Prometheus remote write 协议支持 +- 高效处理高基数 metrics +- 无需降采样的长期存储 +- 比传统 Prometheus+Thanos 堆栈更高的资源效率 + +### GreptimeDB 提供哪些索引能力? + +GreptimeDB 提供丰富的索引选项: +- **倒排索引**:标签列的快速查找 +- **全文索引**:高效日志搜索 +- **跳跃索引**:加速范围查询 +- **向量索引**:支持 AI/ML 工作负载 + +这些索引即使在 PB 级数据集上也能实现亚秒级查询。 + +配置详情请参见[索引管理](/user-guide/manage-data/data-index.md)。 + +### GreptimeDB 如何实现成本效益? + +GreptimeDB 通过以下方式降低成本: +- **列式存储**:卓越的压缩比 +- **计算存储分离**:独立扩展资源 +- **高效基数管理**:处理高基数数据而不发生爆炸 +- **统一平台**:消除对多个专用数据库的需求 + +结果:比传统堆栈降低高达 50 倍的运营和存储成本。 + +### 什么使 GreptimeDB 成为云原生? + +GreptimeDB 专为 Kubernetes 构建: +- **分解架构**:分离计算和存储层 +- **弹性扩展**:根据工作负载添加/删除节点 +- **多云支持**:无缝运行在 AWS、GCP、Azure +- **Kubernetes operators**:简化部署和管理 +- **对象存储后端**:使用 S3、GCS 或 Azure Blob 进行数据持久化 + +Kubernetes 部署详情请参见 [Kubernetes 部署指南](/user-guide/deployments-administration/deploy-on-kubernetes/overview.md)。 + +### GreptimeDB 支持无 schema 数据摄入吗? + +是的,GreptimeDB 在使用以下协议时支持自动 schema 创建: +- gRPC 协议 +- InfluxDB Line Protocol +- OpenTSDB 协议 +- Prometheus Remote Write +- OpenTelemetry 协议 +- Loki 协议(日志数据) +- Elasticsearch 兼容 API(日志数据) + +表和列在首次写入时自动创建,无需手动 schema 管理。 + +## 集成与兼容性 + +### GreptimeDB 如何与现有工具和系统集成? + +**协议支持**: +- **数据写入**:OpenTelemetry、Prometheus Remote Write、InfluxDB Line、Loki、Elasticsearch、gRPC(参见[协议概述](/user-guide/protocols/overview.md)) +- **数据查询**:MySQL、PostgreSQL 协议兼容 +- **查询语言**:SQL、PromQL + +**可视化与监控**: +- **Grafana**:[Grafana 集成](/user-guide/integrations/grafana.md)(含官方插件)+ [MySQL/PostgreSQL 数据源支持](/user-guide/integrations/grafana.md#mysql-数据源) +- **原生 PromQL**:[直接支持](/user-guide/query-data/promql.md) Prometheus 风格查询和仪表板 +- **任何 SQL 工具**:通过 MySQL/PostgreSQL 协议兼容 + +**数据管道集成**: +- **OpenTelemetry**:原生 OTLP 摄入,无转换层,保留所有语义约定 +- **数据收集**:Vector、Fluent Bit、Telegraf、Kafka +- **实时流处理**:直接从 Kafka、Vector 等系统接收数据 + +**SDK 和客户端库**: +- **Go**:[greptimedb-ingester-go](https://github.com/GreptimeTeam/greptimedb-ingester-go) +- **Java**:[greptimedb-ingester-java](https://github.com/GreptimeTeam/greptimedb-ingester-java) +- **Rust**:[greptimedb-ingester-rust](https://github.com/GreptimeTeam/greptimedb-ingester-rust) +- **Erlang**:[greptimedb-ingester-erl](https://github.com/GreptimeTeam/greptimedb-ingester-erl) +- **Python**:通过标准 SQL 驱动程序(MySQL/PostgreSQL 兼容) + +### 如何从其他数据库迁移到 GreptimeDB? + +GreptimeDB 为流行数据库提供迁移指南: +- **从 ClickHouse**:表结构和数据迁移 +- **从 InfluxDB**:Line protocol 和数据迁移 +- **从 Prometheus**:Remote write 和历史数据迁移 +- **从 MySQL/PostgreSQL**:基于 SQL 的迁移 + +详细迁移说明请参见[迁移概述](/user-guide/migrate-to-greptimedb/overview.md)。 + +### GreptimeDB 提供哪些灾备选项? + +GreptimeDB 提供多种灾备策略以满足不同的可用性需求: + +- **单机灾备方案**:使用远程 WAL 和对象存储,可实现 RPO=0 和分钟级 RTO,适合小规模场景 +- **Region 故障转移**:个别区域的自动故障转移,停机时间最短 +- **双机热备**(企业版):节点间同步请求复制,提供高可用性 +- **跨区域单集群**:跨越三个区域,实现零 RPO 和区域级容错 +- **备份与恢复**:定期数据备份,可根据备份频率配置 RPO + +根据您的可用性需求、部署规模和成本考虑选择合适的解决方案。详细指导请参见[灾难恢复概述](/user-guide/deployments-administration/disaster-recovery/overview.md)。 + +## 数据管理与处理 + +### GreptimeDB 如何处理数据生命周期? + +**保留策略**: +- 数据库级和表级 TTL 设置 +- 无需手动清理的自动数据过期 +- 通过 [TTL 文档](/reference/sql/create.md#表选项)配置 + +**数据导出**: +- 用于 S3、本地文件的 [`COPY TO` 命令](/reference/sql/copy.md#连接-s3) +- 通过任何兼容客户端的标准 SQL 查询 +- 备份和灾难恢复的导出功能:[备份与恢复数据](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md) + +### GreptimeDB 如何处理高基数和实时处理? + +**高基数管理**: +- 高级索引策略防止基数爆炸 +- 具有智能压缩的列式存储 +- 带数据修剪的分布式查询执行 +- 高效处理数百万唯一时间序列 + +了解更多索引信息:[索引管理](/user-guide/manage-data/data-index.md) + +**实时处理**: +- **[Flow Engine](/user-guide/flow-computation/overview.md)**:实时流数据处理系统,对流式数据进行连续增量计算,自动更新结果表 +- **[Pipeline](/user-guide/logs/use-custom-pipelines.md)**:实时数据解析转换机制,通过可配置处理器对各种入库数据进行字段提取和数据类型转换 +- **输出表**:持久化处理结果用于分析 + +### GreptimeDB 的可扩展性特征是什么? + +**扩展限制**: +- 表或列数量无严格限制 +- 数百个表的性能影响最小 +- 性能随主键设计而非表数量扩展 +- 列式存储确保高效的部分读取 + +**分区与分布**: +- region 内基于时间的自动组织 +- 通过 PARTITION 子句进行手动分布式分片(参见[表分片指南](/user-guide/deployments-administration/manage-data/table-sharding.md)) +- 计划未来版本的自动 region 拆分 +- **无需配置的动态分区**(企业版功能) + +**核心扩展性功能**: +- **多层缓存**:写入缓存(磁盘支持)和读取缓存(LRU 策略)优化性能 +- **对象存储后端**:通过 S3/GCS/Azure Blob 实现几乎无限存储 +- **异步 WAL**:高效的预写日志,支持可选的按表控制 +- **分布式查询执行**:多节点协调处理大型数据集 +- **手动压缩**:通过[管理命令](/reference/sql/admin.md)提供 + +**企业级扩展功能**: +- 高级分区和自动重新平衡 +- 增强的多租户和隔离功能 +- 企业级监控和管理工具 + +架构详情请参见[存储架构博客](https://greptime.cn/blogs/2024-12-24-observability)。 + +### GreptimeDB 的设计权衡是什么? + +GreptimeDB 针对可观测性工作负载进行了优化,具有以下设计限制: +- **无 ACID 事务**:优先考虑高吞吐量写入而非事务一致性 +- **有限删除操作**:为追加重的可观测性数据设计 +- **时序数据专注**:针对 IoT、metrics、logs 和 traces 而非通用 OLTP 进行优化 +- **简化连接**:针对时序查询而非复杂关系操作进行优化 + +## 部署与运维 + +### GreptimeDB 部署和运维指南 + +**部署选项**: + +*集群部署(生产环境)*: +- 最少 3 个节点实现高可用性 +- 服务架构:metasrv、frontend、datanode(可同节点或分离部署) +- 存储后端:S3、GCS、Azure Blob(生产)或本地存储(测试) +- 元数据存储:MySQL/PostgreSQL 后端支持 metasrv +- 参见[容量规划指南](/user-guide/deployments-administration/capacity-plan.md) + +*边缘与单机部署*: +- Android ARM64、Raspberry Pi 等受限环境 +- 单节点模式适用于开发测试和 IoT 场景 +- 高效资源使用,支持边缘计算 + +**数据分布策略**: +- **当前**:通过 PARTITION 子句手动分区(参见[表分片指南](/user-guide/deployments-administration/manage-data/table-sharding.md)),region 内自动时间组织,支持手动 region 迁移进行负载均衡(参见[Region 迁移指南](/user-guide/deployments-administration/manage-data/region-migration.md)) +- 自动 region 故障转移容灾(参见[Region 故障转移](/user-guide/deployments-administration/manage-data/region-failover.md)) +- **路线图**:自动 region 拆分、动态负载均衡 + +**监控与运维**: + +GreptimeDB 提供全面的监控能力,包括指标收集、健康检查和可观测性集成。详细的监控设置和故障排除指南请参见[监控概述](/user-guide/deployments-administration/monitoring/overview.md)。 + +部署和管理详情:[部署与管理概述](/user-guide/deployments-administration/overview.md) + +## 开源版 vs 企业版 vs 云版本 + +### GreptimeDB 各版本的区别是什么? + +**开源版本**: +- 高性能写入和查询能力 +- 集群部署和基础读写分离 +- 多协议支持(OpenTelemetry、Prometheus、InfluxDB 等) +- 基础访问控制和加密 +- 基础性能诊断 +- 社区支持 + +**企业版本**(包含所有开源版功能,另增加): +- 基于成本的查询优化器,提升性能 +- 高级读写分离和双活灾备(参见[双机热备灾备方案](/enterprise/deployments-administration/disaster-recovery/dr-solution-based-on-active-active-failover.md)) +- 自动扩展、索引和负载均衡 +- 分层缓存和企业级管理控制台 +- 企业授权(RBAC/LDAP 集成) +- 增强的安全和审计功能 +- 一对一技术支持和 7x24 服务响应 +- 专业定制服务 + +**GreptimeCloud**(全托管,包含所有企业版功能,另增加): +- Serverless 自动扩展,按用量付费 +- 全托管部署,无缝升级 +- 独立资源池和网络隔离 +- 可配置读写容量和无限存储 +- 具有 Prometheus 工作台的高级仪表板 +- SLA 保证和自动灾难恢复 + +详细对比请参见[价格与功能](https://greptime.cn/pricing#differences)。 + +### 有哪些安全功能可用? + +**开源版本**: +- 基本用户名/密码身份验证 +- 连接的 TLS/SSL 支持 + +**企业版/云版本**: +- 基于角色的访问控制(RBAC) +- 团队管理和 API 密钥 +- 静态数据加密 +- 合规审计日志 + +## 技术细节 + +### GreptimeDB 如何扩展 Apache DataFusion? + +GreptimeDB 基于 DataFusion 构建: +- **查询语言**:原生 PromQL 与 SQL 并存 +- **分布式执行**:多节点查询协调 +- **自定义函数**:时序特定的 UDF/UDAF +- **优化**:针对可观测性工作负载的规则 +- **计数器处理**:在 `rate()` 和 `delta()` 函数中自动重置检测 + +自定义函数开发:[函数文档](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-write-aggregate-function.md) + +### GreptimeDB 和 InfluxDB 的区别是什么? + +主要区别: +- **开源策略**:GreptimeDB 的整个分布式系统完全开源 +- **架构**:针对可观测性工作负载优化的基于 region 的设计 +- **查询语言**:SQL + PromQL vs InfluxQL + SQL +- **统一模型**:在一个系统中原生支持 metrics、logs 和 traces +- **存储**:具有专用优化的可插拔引擎 +- **云原生**:为 Kubernetes 构建,具有分解的计算/存储(参见 [Kubernetes 部署指南](/user-guide/deployments-administration/deploy-on-kubernetes/overview.md)) + +详细比较请参见 [GreptimeDB vs InfluxDB](https://greptime.cn/compare/influxdb)。更多产品比较(如 vs. ClickHouse、Loki 等)可在官网的资源菜单中找到。 + +### GreptimeDB 的存储引擎如何工作? + +**LSM-Tree 架构**: +- 基于日志结构合并树(LSMT)设计 +- WAL 可以使用本地磁盘或分布式服务(如 Kafka)通过 Log Store API +- SST 文件刷写到对象存储(S3/GCS)或本地磁盘 +- 面向云原生环境设计,以对象存储为主要后端 +- 使用 TWCS(时间窗口压缩策略)优化时序工作负载 + +**性能考量**: +- **时间戳**:日期时间格式(yyyy-MM-dd HH:mm:ss)无性能影响 +- **压缩**:仅测量数据目录;WAL 循环重用 +- **Append Only 表**:建议使用,对写入和查询性能更友好,尤其适合日志场景 +- **Flow Engine**:目前基于 SQL;PromQL 支持正在评估中 + +### 特定用例的最佳实践是什么? + +**网络监控**(如数千个网卡): +- 使用 Flow 表进行连续聚合 +- 通过 Flow Engine 手动降采样进行数据缩减 +- 输出到常规表进行长期存储 + +**日志分析**: +- 使用 Append Only 表获得更好的写入和查询性能 +- 在频繁查询的字段上创建索引([索引管理](/user-guide/manage-data/data-index.md)) +- 存储效率:ClickHouse 的 50%,Elasticsearch 的 12.7% + +**表设计与性能**: +- 表建模指导:[设计表](/user-guide/deployments-administration/performance-tuning/design-table.md) +- 性能优化:[性能调优提示](/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md) + + +## 入门指南 + +### 如何开始使用 GreptimeDB? + +**📚 学习资源**: + +*文档与指南*: +- [安装指南](/getting-started/installation/overview.md) - 快速开始部署 +- [容量规划](/user-guide/deployments-administration/capacity-plan.md) - 生产环境规划 +- [配置指南](/user-guide/deployments-administration/configuration.md) - 详细配置说明 + +*性能基准*: +- [TSBS 基准测试](https://github.com/GreptimeTeam/greptimedb/tree/main/docs/benchmarks/tsbs) +- [性能对比分析](/user-guide/concepts/features-that-you-concern.md#greptimedb-对比其他存储或时序数据库的性能如何) +- [vs InfluxDB](https://greptime.cn/blogs/2024-08-08-report) +- [vs Loki](https://greptime.cn/blogs/2025-08-07-beyond-loki-greptimedb-log-scenario-performance-report.html) +- [日志基准测试](https://greptime.cn/blogs/2025-03-07-greptimedb-log-benchmark) + +**🚀 快速上手路径**: + +1. **云端体验**:[GreptimeCloud 免费版](https://greptime.cn/product/cloud) - 无需安装即可试用 +2. **本地部署**:按照[安装指南](/getting-started/installation/overview.md)自托管部署 +3. **集成现有系统**:GreptimeDB 支持与 Prometheus、Vector、Kafka、Telegraf、EMQX、Metabase 等众多系统的广泛集成。完整列表请参见[集成概述](/user-guide/integrations/overview.md),或从以下开始: + - [OpenTelemetry 集成](/user-guide/ingest-data/for-observability/opentelemetry.md) + - [Prometheus 迁移](/user-guide/ingest-data/for-observability/prometheus.md) + - Grafana 仪表板配置 + +**🤝 社区与贡献**: + +*参与社区*: +- [Slack 频道](https://greptime.com/slack) - 与用户和开发者交流 +- [GitHub Discussions](https://github.com/GreptimeTeam/greptimedb/discussions) - 技术讨论 + +*贡献代码*: +- [贡献指南](https://github.com/GreptimeTeam/greptimedb/blob/main/CONTRIBUTING.md) - 开发环境搭建 +- [适合新手的 Issue](https://github.com/GreptimeTeam/greptimedb/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+first+issue%22) - 第一次贡献 +- [文档改进](https://github.com/GreptimeTeam/docs) - 帮助完善中英文文档 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/faq-and-others/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/faq-and-others/overview.md new file mode 100644 index 0000000000..de87c1cb13 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/faq-and-others/overview.md @@ -0,0 +1,9 @@ +--- +keywords: [常见问题] +description: 关于 GreptimeDB 的常见问题解答。 +--- + +# 常见问题及其他 + +在本节中,我们将介绍[常见问题](./faq.md)和其他一些信息。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/greptimedb-cluster.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/greptimedb-cluster.md new file mode 100644 index 0000000000..e86d9cc805 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-administration/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 +``` + +默认情况下,数据将被存储在 `./greptimedb-cluster-docker-compose`。如果你想清理数据,也可删除该目录。 + +## 下一步 + +学习如何使用 GreptimeDB:[快速开始](../quick-start.md#连接到-greptimedb)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/greptimedb-dashboard.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/greptimedb-dashboard.md new file mode 100644 index 0000000000..d9674647b8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/greptimedb-dashboard.md @@ -0,0 +1,17 @@ +--- +keywords: [控制台, 数据可视化, 查询语言, SQL 查询, PromQL 查询] +description: 介绍 GreptimeDB 控制台的功能和使用方法,包括数据可视化和多种查询语言的支持。 +--- + +# GreptimeDB 控制台 + +数据可视化在时间序列数据分析时发挥着关键作用。为了帮助用户充分利用 GreptimeDB 的各种功能,GreptimeDB 提供了一个简单的[控制台](https://github.com/GreptimeTeam/dashboard)。 + +自 GreptimeDB v0.2.0 版本以来,控制台已经默认嵌入到 GreptimeDB 的 binary 文件中。在启动 [GreptimeDB 单机版](greptimedb-standalone.md)或[分布式集群](greptimedb-cluster.md)后,可以通过 URL `http://localhost:4000/dashboard` 访问控制台。控制台支持多种查询语言,包括 [SQL 查询](/user-guide/query-data/sql.md)和 [PromQL 查询](/user-guide/query-data/promql.md)。 + +我们提供不同种类的图表,可以根据不同的场景进行选择。当用户有足够的数据时,图表的内容将更加丰富。 + +![line](/dashboard-line.png) +![scatter](/dashboard-scatter.png) + +我们将持续开发和迭代这个开源项目,并计划将时间序列数据应用于监测、分析和其他相关领域的扩展。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/greptimedb-standalone.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/greptimedb-standalone.md new file mode 100644 index 0000000000..5ffc12cc28 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/greptimedb-standalone.md @@ -0,0 +1,136 @@ +--- +keywords: [单机模式, 二进制安装, Docker, Windows, 配置文档] +description: 介绍如何在单机模式下安装和运行 GreptimeDB,包括使用二进制文件、Docker 和 Windows 的安装方法。 +--- + +# GreptimeDB 单机模式 + +## 安装 + +我们先通过最简单的配置来开始。有关 GreptimeDB 中可用的所有配置选项的详细列表,请参考[配置文档](/user-guide/deployments-administration/configuration.md)。 + +## 在 Kubernetes 中部署 GreptimeDB 单机版 + +对于生产环境,我们建议在 Kubernetes 中部署 GreptimeDB 单机版。请参考 [在 Kubernetes 上部署](/user-guide/deployments-administration/deploy-on-kubernetes/overview.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_data:/greptimedb_data" \ + --name greptime --rm \ + greptime-registry.cn-hangzhou.cr.aliyuncs.com/greptime/greptimedb:VAR::greptimedbVersion standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-bind-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_data/` 目录中。 + +如果你想要使用另一个版本的 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_data:/greptimedb_data" \ + --name greptime --rm \ + greptime-registry.cn-hangzhou.cr.aliyuncs.com/greptime/greptimedb:VAR::greptimedbVersion standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-bind-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-bind-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_data:/greptimedb_data" \ + --name greptime --rm \ + greptime-registry.cn-hangzhou.cr.aliyuncs.com/greptime/greptimedb:VAR::greptimedbVersion standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-bind-addr 0.0.0.0:4001 \ + --mysql-addr 0.0.0.0:4002 \ + --postgres-addr 0.0.0.0:4003 +``` + + + + + +你也可以参考[配置 GreptimeDB](/user-guide/deployments-administration/configuration.md)文档在配置文件中修改绑定的地址。 + +## 下一步 + +学习如何使用 GreptimeDB:[快速开始](../quick-start.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/overview.md new file mode 100644 index 0000000000..75362b5ce7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/installation/overview.md @@ -0,0 +1,31 @@ +--- +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-1.0/getting-started/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/overview.md new file mode 100644 index 0000000000..2100f4b86c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/overview.md @@ -0,0 +1,11 @@ +--- +keywords: [快速开始, 安装] +description: 快速开始使用 GreptimeDB +--- + +# 立即开始 + +立即开始使用 GreptimeDB! + +- [安装](./installation/overview.md):安装 GreptimeDB 单机模式或分布式集群。 +- [快速开始](./quick-start.md):使用你熟悉的协议或语言快速上手 GreptimeDB。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/quick-start.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/quick-start.md new file mode 100644 index 0000000000..7087af6d81 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/getting-started/quick-start.md @@ -0,0 +1,526 @@ +--- +keywords: [快速开始, 数据库连接, 创建表, 写入数据, 查询数据, 数据可视化] +description: 介绍如何快速开始使用 GreptimeDB,包括连接数据库、创建表、写入数据、查询数据等核心功能。 +--- + +# 快速开始 + +在继续阅读之前,请确保你已经[安装了 GreptimeDB](./installation/overview.md)。 + +本指南通过引导你创建一个 metric 表和一个 log 表来介绍 GreptimeDB 的核心功能。 + +你将学习(10-15 分钟) +* 在本地启动并连接到 GreptimeDB +* 创建 metrics 和 logs 表并插入示例数据 +* 查询和聚合数据 +* 计算 5 秒窗口内的 p95 和 ERROR 计数并对齐它们 +* 关联 metrics 和 logs 来发现异常主机和时间点 +* 结合 SQL 和 PromQL 查询数据 + +## 连接到 GreptimeDB + +GreptimeDB 支持[多种协议](/user-guide/protocols/overview.md)与数据库进行交互。 +在本快速入门文档中,我们使用 SQL 作为实例。 + +如果你的 GreptimeDB 实例运行在 `127.0.0.1` 中, +并且使用 MySQL 客户端默认端口 `4002` 或 PostgreSQL 客户端默认端口 `4003`, +你可以使用以下命令连接到数据库。 + +GreptimeDB 默认不开启[鉴权认证](/user-guide/deployments-administration/authentication/overview.md)。 +在本章节中你可以在连接数据库时不提供用户名密码。 + +```shell +mysql -h 127.0.0.1 -P 4002 +``` + +或者 + +```shell +psql -h 127.0.0.1 -p 4003 -d public +``` + +你也可以通过浏览器访问 DB 内置的 Dashboard 地址 `http://127.0.0.1:4000/dashbaord` 运行本文档中的 SQL。 + +## 创建表 + +假设你有一个名为 `grpc_latencies` 的事件(Events)表,用于存储的 gRPC 调用接口以及它的处理时间。表 schema 如下: + +```sql +-- Metrics: gRPC 调用延迟(毫秒) +CREATE TABLE grpc_latencies ( + ts TIMESTAMP TIME INDEX, + host STRING INVERTED INDEX, + method_name STRING, + latency DOUBLE, + PRIMARY KEY (host, method_name) +); +``` + +- `ts`:收集指标时的时间戳,时间索引列。 +- `host`:主机名,设置了[倒排索引](/user-guide/manage-data/data-index.md#倒排索引)。 +- `method_name`:RPC 请求方法的名称,tag 列。 +- `latency`:RPC 请求的响应时间。 + +此外,还有一个名为 `app_logs` 的表用于存储日志: + +```sql +-- Logs: 应用程序日志 +CREATE TABLE app_logs ( + ts TIMESTAMP TIME INDEX, + host STRING INVERTED INDEX, + api_path STRING, + log_level STRING, + log_msg STRING FULLTEXT INDEX WITH('case_sensitive' = 'false'), + PRIMARY KEY (host, log_level) +) with('append_mode'='true'); +``` + +- `ts`:日志条目的时间戳,时间索引列。 +- `host`:主机名,设置了倒排索引。 +- `api_path`:API 路径。 +- `log_level`:日志级别,tag 列。 +- `log_msg`:日志消息内容,设置了[全文索引](/user-guide/manage-data/data-index.md#全文索引)。 + +通过将 `append_mode` 设置为 true 来启用 [Append Only](/user-guide/deployments-administration/performance-tuning/design-table.md#何时使用-append-only-表)模式,这通常对性能有帮助。同时也支持其他表选项,如数据保留期等。 + +::::tip +我们在下面使用 SQL 来导入数据,因此需要手动创建表。但 GreptimeDB 本身是 [schemaless](/user-guide/ingest-data/overview.md#自动生成表结构) 的,在使用其他写入方法时可以自动生成 schema。 +:::: + +## 写入数据 + +让我们插入一些模拟数据来模拟收集的指标和错误日志。 + +假设有两个服务器 `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_msg) 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(0.95) WITHIN GROUP (ORDER BY latency) 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) +``` + + +### 通过关键词搜索日志 + +通过关键词 `timeout` 过滤日志消息: +```sql +SELECT + * +FROM + app_logs +WHERE + lower(log_msg) @@ 'timeout' + AND ts > '2024-07-11 20:00:00' +ORDER BY + ts; +``` + +```sql ++---------------------+-------+------------------+-----------+--------------------+ +| ts | host | api_path | log_level | log_msg | ++---------------------+-------+------------------+-----------+--------------------+ +| 2024-07-11 20:00:10 | host1 | /api/v1/billings | ERROR | Connection timeout | +| 2024-07-11 20:00:10 | host1 | /api/v1/resource | ERROR | Connection timeout | +| 2024-07-11 20:00:14 | host1 | /api/v1/billings | ERROR | Timeout | +| 2024-07-11 20:00:14 | host1 | /api/v1/resource | ERROR | Timeout | ++---------------------+-------+------------------+-----------+--------------------+ +``` + +`@@` 操作符用于[短语搜索](/user-guide/logs/fulltext-search.md)。 + +### Range query + +你可以使用 [range query](/reference/sql/range.md#range-query)来实时监控延迟。例如,按 5 秒窗口计算请求的 p95 延迟: + +```sql +SELECT + ts, + host, + approx_percentile_cont(0.95) WITHIN GROUP (ORDER BY latency) + RANGE '5s' AS p95_latency +FROM + grpc_latencies +ALIGN '5s' FILL PREV +ORDER BY + host,ts; +``` + +```sql ++---------------------+-------+-------------+ +| ts | host | p95_latency | ++---------------------+-------+-------------+ +| 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 | +| 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 | ++---------------------+-------+-------------+ +8 rows in set (0.06 sec) +``` + +Range query 是一个非常强大的功能,用于基于时间窗口查询和聚合数据,请阅读[手册](/reference/sql/range.md#range-query)以了解更多。 + +### 指标和日志的关联查询 + +通过组合两个表的数据,你可以快速地确定故障时间和相应的日志。以下 SQL 查询使用 `JOIN` 操作关联指标和日志: + +```sql +-- 将指标和日志对齐到 5 秒时间桶,然后关联 +WITH + -- 指标: 每个主机在 5 秒时间桶内的 p95 延迟 + metrics AS ( + SELECT + ts, + host, + approx_percentile_cont(0.95) WITHIN GROUP (ORDER BY latency) RANGE '5s' AS p95_latency + FROM grpc_latencies + ALIGN '5s' FILL PREV + ), + -- 日志: 相同 5 秒时间桶内每个主机的 ERROR 计数 + logs AS ( + SELECT + ts, + host, + count(log_msg) RANGE '5s' AS num_errors + FROM app_logs + WHERE log_level = 'ERROR' + ALIGN '5s' + ) +SELECT + m.ts, + m.p95_latency, + COALESCE(l.num_errors, 0) AS num_errors, + m.host +FROM metrics m +LEFT JOIN logs l + ON m.host = l.host AND m.ts = l.ts +ORDER BY m.ts, m.host; +``` + + +```sql ++---------------------+-------------+------------+-------+ +| ts | p95_latency | num_errors | host | ++---------------------+-------------+------------+-------+ +| 2024-07-11 20:00:05 | 104.5 | 0 | host1 | +| 2024-07-11 20:00:05 | 114 | 0 | host2 | +| 2024-07-11 20:00:10 | 4200 | 10 | host1 | +| 2024-07-11 20:00:10 | 111 | 0 | host2 | +| 2024-07-11 20:00:15 | 3500 | 4 | host1 | +| 2024-07-11 20:00:15 | 115 | 0 | host2 | +| 2024-07-11 20:00:20 | 2500 | 0 | host1 | +| 2024-07-11 20:00:20 | 95 | 0 | host2 | ++---------------------+-------------+------------+-------+ +8 rows in set (0.02 sec) +``` + +我们可以看到当 gRPC 响应时间增大的时间窗口内,错误日志也显著增多,并且确定问题在 `host1`。 + +### 通过 PromQL 查询数据 + +GreptimeDB 支持 [Prometheus 查询语言及其 API](/user-guide/query-data/promql.md),允许你使用 PromQL 查询指标。例如,你可以使用以下查询获取每个主机在过去 1 分钟内的 p95 响应时间: + +```promql +quantile_over_time(0.95, grpc_latencies{host!=""}[1m]) +``` + +要测试这个查询,使用以下 curl 命令: +```bash +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + --data-urlencode 'query=quantile_over_time(0.95, grpc_latencies{host!=""}[1m])' \ + --data-urlencode 'start=2024-07-11 20:00:00Z' \ + --data-urlencode 'end=2024-07-11 20:00:20Z' \ + --data-urlencode 'step=1m' \ + 'http://localhost:4000/v1/prometheus/api/v1/query_range' +``` + +这里我们设置 `step` 为 1 分钟。 + +输出: +```json +{ + "status": "success", + "data": { + "resultType": "matrix", + "result": [ + { + "metric": { + "__name__": "grpc_latencies", + "host": "host1", + "method_name": "GetUser" + }, + "values": [ + [ + 1720728000.0, + "103" + ] + ] + }, + { + "metric": { + "__name__": "grpc_latencies", + "host": "host2", + "method_name": "GetUser" + }, + "values": [ + [ + 1720728000.0, + "113" + ] + ] + } + ] + } +} +``` + +更强大的是,你可以使用 SQL 来执行 PromQL 并混合使用两者,例如: +```sql +TQL EVAL ('2024-07-11 20:00:00Z', '2024-07-11 20:00:20Z','1m') + quantile_over_time(0.95, grpc_latencies{host!=""}[1m]); +``` + +这个 SQL 查询将输出: +```sql ++---------------------+---------------------------------------------------------+-------+-------------+ +| ts | prom_quantile_over_time(ts_range,latency,Float64(0.95)) | host | method_name | ++---------------------+---------------------------------------------------------+-------+-------------+ +| 2024-07-11 20:00:00 | 113 | host2 | GetUser | +| 2024-07-11 20:00:00 | 103 | host1 | GetUser | ++---------------------+---------------------------------------------------------+-------+-------------+ +``` + +重写上面的关联示例: +```sql +WITH + metrics AS ( + TQL EVAL ('2024-07-11 20:00:00Z', '2024-07-11 20:00:20Z', '5s') + quantile_over_time(0.95, grpc_latencies{host!=""}[5s]) + ), + logs AS ( + SELECT + ts, + host, + COUNT(log_msg) RANGE '5s' AS num_errors + FROM app_logs + WHERE log_level = 'ERROR' + ALIGN '5s' + ) +SELECT + m.*, + COALESCE(l.num_errors, 0) AS num_errors +FROM metrics AS m +LEFT JOIN logs AS l + ON m.host = l.host + AND m.ts = l.ts +ORDER BY + m.ts, + m.host; +``` + +```sql ++---------------------+---------------------------------------------------------+-------+-------------+------------+ +| ts | prom_quantile_over_time(ts_range,latency,Float64(0.95)) | host | method_name | num_errors | ++---------------------+---------------------------------------------------------+-------+-------------+------------+ +| 2024-07-11 20:00:05 | 103 | host1 | GetUser | 0 | +| 2024-07-11 20:00:05 | 113 | host2 | GetUser | 0 | +| 2024-07-11 20:00:10 | 140.89999999999998 | host1 | GetUser | 10 | +| 2024-07-11 20:00:10 | 113.8 | host2 | GetUser | 0 | +| 2024-07-11 20:00:15 | 3400 | host1 | GetUser | 4 | +| 2024-07-11 20:00:15 | 114 | host2 | GetUser | 0 | +| 2024-07-11 20:00:20 | 3375 | host1 | GetUser | 0 | +| 2024-07-11 20:00:20 | 115 | host2 | GetUser | 0 | ++---------------------+---------------------------------------------------------+-------+-------------+------------+ +``` + +通过使用 [TQL](/reference/sql/tql.md) 命令,你可以结合 SQL 和 PromQL 的强大功能,使关联分析和复杂查询不再困难。 + + + +## 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.17/greptimecloud/getting-started/create-service.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/create-service.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/create-service.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/create-service.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/go.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/go.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/go.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/go.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/influxdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/influxdb.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/influxdb.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/influxdb.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/java.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/java.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/java.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/java.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/mysql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/mysql.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/mysql.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/mysql.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/node.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/node.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/node.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/node.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/overview.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/overview.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/prometheus.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/prometheus.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/prometheus.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/python.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/python.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/python.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/python.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/vector.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/vector.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/vector.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/vector.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/visualize-data.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/visualize-data.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/getting-started/visualize-data.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/getting-started/visualize-data.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/alloy.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/alloy.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/alloy.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/alloy.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/dbeaver.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/dbeaver.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/dbeaver.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/dbeaver.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/fluent-bit.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/fluent-bit.md similarity index 99% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/fluent-bit.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/fluent-bit.md index 700bdcae25..696f4fa77a 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/fluent-bit.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/fluent-bit.md @@ -27,7 +27,7 @@ Fluent Bit 可以配置为使用 HTTP 协议将日志发送到 GreptimeCloud。 http_Passwd ``` -在此示例中,使用 `http` 输出插件将日志发送到 GreptimeCloud。有关更多信息和额外选项,请参阅 [Logs HTTP API](https://docs.greptime.cn/reference/pipeline/write-log-api/#http-api) 指南。 +在此示例中,使用 `http` 输出插件将日志发送到 GreptimeCloud。有关更多信息和额外选项,请参阅 [Logs HTTP API](https://docs.greptime.cn/reference/pipeline/write-log-api.md#http-api) 指南。 ## Prometheus Remote Write diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/grafana.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/grafana.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/grafana.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/grafana.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/influxdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/influxdb.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/influxdb.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/influxdb.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/kafka.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/kafka.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/kafka.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/kafka.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/metabase.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/metabase.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/metabase.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/metabase.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/mindsdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/mindsdb.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/mindsdb.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/mindsdb.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/mysql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/mysql.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/mysql.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/mysql.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/otlp.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/otlp.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/otlp.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/otlp.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/postgresql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/postgresql.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/postgresql.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/postgresql.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/prometheus.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/prometheus.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/prometheus.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/sdk-libraries/go.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/sdk-libraries/go.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/sdk-libraries/go.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/sdk-libraries/go.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/sdk-libraries/java.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/sdk-libraries/java.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/sdk-libraries/java.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/sdk-libraries/java.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/streamlit.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/streamlit.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/streamlit.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/streamlit.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/superset.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/superset.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/superset.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/superset.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/vector.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/vector.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/integrations/vector.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/integrations/vector.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/overview.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/overview.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/billing.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/billing.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/billing.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/billing.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/dedicated.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/dedicated.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/dedicated.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/dedicated.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/hobby.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/hobby.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/hobby.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/hobby.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/overview.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/overview.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/request-capacity-unit.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/request-capacity-unit.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/request-capacity-unit.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/request-capacity-unit.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/serverless.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/serverless.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/serverless.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/serverless.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/shared-storage-capacity.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/shared-storage-capacity.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.17/greptimecloud/usage-&-billing/shared-storage-capacity.md rename to i18n/zh/docusaurus-plugin-content-docs/version-1.0/greptimecloud/usage-&-billing/shared-storage-capacity.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/index.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/index.md new file mode 100644 index 0000000000..ba1c8cf3b2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/index.md @@ -0,0 +1,42 @@ +--- +keywords: [可观测性数据库,开源可观测性数据库,时序数据库, 开源时序数据库, 可观测数据,时序数据, 可观测性工具, 云原生数据库, 数据可观测性, 可观测性平台, 边缘数据库, 物联网边缘计算, 边缘云计算, 日志管理, 日志聚合, 高基数, SQL查询示例, OpenTelemetry 收集器, GreptimeDB] +description: 介绍了 GreptimeDB,一个开源的统一可观测性数据库,用于存储指标、日志和事件,包含入门指南、用户指南、贡献者指南等链接,帮助用户快速上手和深入了解。 +--- + +# 简介 + +

+ GreptimeDB Logo +

+ +**GreptimeDB** 是一个开源、云原生、统一的可观测性数据库,用于存储指标、日志和链路追踪数据。您可以从边缘到云端获得实时洞察——无论规模大小。 + +GreptimeDB 经由 [GreptimeCloud](https://greptime.cn/product/cloud) 提供云服务。 +GreptimeCloud 是一个完全托管的可观测性数据库服务,具有无服务器(Serverless)的可扩展性、与丰富的 IoT 和可观测软件生态系统的无缝集成。 + +我们的核心开发人员多年深耕于建立可观测(监控)数据平台。基于他们的丰富经验,GreptimeDB 应运而生,并为用户提供: + + +- **All-in-One 的可观测性数据库**:通过统一数据库实时处理指标、日志和链路追踪,原生支持 [SQL](/user-guide/query-data/sql.md)、[PromQL](/user-guide/query-data/promql.md) 和 [流式处理](/user-guide/flow-computation/overview.md)。用高性能单一解决方案取代复杂的传统数据堆栈。 +- **高性能引擎**:采用 Rust 语言打造,具备卓越的性能和可靠性。丰富的[索引选择](/user-guide/manage-data/data-index.md)(倒排、全文、调数和向量索引)加速查询,实现 PB 级数据的亚秒级响应,并能处理数十万并发请求。 +- **显著的成本降低**:凭借计算与存储分离的[架构](/user-guide/concepts/architecture.md),运营和存储成本降低 50 倍。可灵活扩展至各类云存储系统(如 S3、Azure Blob Storage),配合全托管云服务 [GreptimeCloud](https://greptime.cn/product/cloud) ,极大简化运维管理。 +- **无限扩展性**:专为 [Kubernetes](/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md) 和云环境而设计,采用业界领先的计算与存储分离架构,实现无限制的跨云扩展。高效应对高基数爆炸问题。 +- **开发者友好**:支持标准 SQL、PromQL 接口、内置 Web 仪表盘、REST API,并兼容 MySQL/PostgreSQL 协议。广泛适配主流数据 [接入协议](/user-guide/protocols/overview.md),轻松迁移与集成。 +- **灵活的部署选项**:可部署于任意环境,从 ARM 边缘设备到云端,提供统一 API 和高效带宽的数据同步。通过相同的 API 无缝查询边缘和云端数据。 + +在开始上手之前,请阅读以下文档,其包含了设置说明、基本概念、架构设计和教程: + +- [立即开始][1]: 为刚接触 GreptimeDB 的用户提供指引,包括如何安装与数据库操作。 +- [用户指南][2]: 应用程序开发人员可以使用 GreptimeDB 或建立自定义集成。 +- [贡献者指南][3]: 有兴趣了解更多技术细节并想成为 GreptimeDB 的贡献者的开发者请阅读此文档。 +- [最新 RoadMap][4]: 了解 GreptimeDB 当前研发进展和路线图 + + +[1]: ./getting-started/overview.md +[2]: ./user-guide/overview.md +[3]: ./contributor-guide/overview.md +[4]: https://greptime.cn/blogs/2025-01-24-greptimedb-roadmap2025 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/about-greptimedb-engines.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/about-greptimedb-engines.md new file mode 100644 index 0000000000..b8b98d7505 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/about-greptimedb-engines.md @@ -0,0 +1,50 @@ +--- +keywords: [greptimedb 引擎, Mito 引擎, Metric 引擎, File 引擎, 表引擎] +description: GreptimeDB 中所有表引擎的概述。 +--- + +# GreptimeDB 表引擎 + +## 概述 + +GreptimeDB 提供多种专业的表引擎(Table Engine),每种引擎都针对特定工作负载和使用场景进行了优化设计。本文档全面介绍了这些引擎,并提供了何时使用每种引擎的指导。 + +### Mito 引擎 + +Mito 是 GreptimeDB 的默认`存储引擎`,负责高效存储和管理数据库数据。基于 [LSMT][1](日志结构合并树)架构构建,Mito 已针对时间序列数据工作负载进行了广泛优化。 + +该引擎的架构包括预写日志(WAL)以确保持久性、Memtable 在内存中高效组织数据以及基于时间窗口压缩策略(TWCS)的高效压缩策略。这种设计使 Mito 能够处理高吞吐量的写入操作,同时保持出色的查询性能。 + +Mito 无缝集成了各种对象存储解决方案,包括 S3、GCS 和 Azure Blob Storage,无需额外插件即可提供原生支持。它在对象存储之上实现了分层缓存系统,优化了任何规模时间序列数据的存储成本和访问速度。 + +[1]: https://en.wikipedia.org/wiki/Log-structured_merge-tree + +### Metric 引擎 + +顾名思义,Metric 引擎旨在高效处理指标数据。它专门处理可观测性负载中典型的海量小表的场景。 + +Metric 引擎的关键创新在于使用合成宽物理表来存储来自众多小表的数据。这种方法能够跨表高效重用列和元数据,显著减少存储开销,同时提高列式压缩效率。在 Metric 引擎下,表成为轻量级逻辑结构,非常适合云原生可观测场景,这些场景中通常存在数千个小型指标表。 + +Metric 引擎构建在 Mito 引擎之上,这意味着其数据实际上存储在 Mito 引擎中。这种架构利用了 Mito 强大的存储能力,同时为指标数据管理添加了专门的优化。 + +### File 引擎 + +File 引擎是 GreptimeDB 中专为处理基于文件的数据源而设计的专用存储引擎。它允许 GreptimeDB 直接查询和处理存储在外部文件中的数据,无需数据导入或转换。 + +该引擎支持数据分析工作流中常用的各种文件格式,实现与现有数据管道的无缝集成。通过将外部文件视为虚拟表,File 引擎提供了对基于文件的数据的 SQL 查询能力,同时保持了 GreptimeDB 查询引擎的性能优化。 + +当数据已经以文件格式存在时,File 引擎特别有用,允许用户分析这些数据,同时分析存储在其他 GreptimeDB 引擎中的时间序列数据。这一功能使 GreptimeDB 成为更加多功能的统一分析平台,能够处理多样化的数据源。 + +## 引擎选择指南 + +### 何时使用各种引擎 + +- **Mito 引擎**:作为默认存储引擎,Mito 适用于大多数通用时间序列工作负载。当你需要平衡写入吞吐量、查询性能和存储效率时,它是一个极佳的选择。对于需要持久存储并具有良好全面性能特性的应用程序,请使用 Mito。 + +- **Metric 引擎**:当处理涉及数千个具有相似列结构的小表的可观测性和指标监控场景时,选择 Metric 引擎。该引擎在云原生监控环境中表现出色,可以减少存储开销并提高查询性能,特别适合指标数据为主的场景。 + +- **File 引擎**:当你需要查询已存在于外部文件中的数据而无需将其导入数据库时,选择 File 引擎。这对于数据探索、一次性分析任务或与现有基于文件的数据管道集成时非常理想。 + +### 在 SQL 中指定引擎类型 + +在 GreptimeDB 中创建表时,您可以通过 CREATE TABLE 语句中的 `ENGINE` 子句指定要使用的引擎。有关语法和选项的更详细信息,请参阅 [CREATE TABLE](/reference/sql/create.md#create-table) 文档。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/about-greptimedb-version.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/about-greptimedb-version.md new file mode 100644 index 0000000000..182fcc688d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/reference/command-lines/datanode.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/datanode.md new file mode 100644 index 0000000000..d212142404 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/datanode.md @@ -0,0 +1,86 @@ +--- +keywords: [GreptimeDB datanode, 命令行界面, datanode 配置, datanode 启动, datanode 选项, datanode 示例] +description: GreptimeDB datanode 命令行界面完整指南,包括配置选项、启动命令以及部署 datanode 实例的实用示例。 +--- + +# Datanode + +`greptime datanode` 命令提供了用于管理和基准测试 datanode 实例的子命令。 + +## start + +启动 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-bind-addr ` | gRPC 服务绑定地址址 | +| `--rpc-server-addr ` | 该地址用于来自主机外部的连接和通信。如果留空或未设置,服务器将自动使用主机上第一个网络接口的 IP 地址,其端口号与 `rpc_bind_addr` 中指定的相同; | +| `--wal-dir ` | WAL 目录 | + +所有的 `addr` 类选项都是 `ip:port` 形式的字符串。 + +### 示例 + +#### 使用配置启动服务 + +使用自定义配置启动 Datanode 实例: + +```sh +greptime datanode start -c config/datanode.example.toml +``` + +使用命令行参数启动 Datanode,指定 gRPC 服务地址、MySQL 服务地址、Metasrv 地址和该 Datanode 的 ID: + +```sh +greptime datanode start --rpc-bind-addr=0.0.0.0:4001 --mysql-addr=0.0.0.0:4002 --metasrv-addrs=0.0.0.0:3002 --node-id=1 +``` + +`datanode.example.toml` 配置文件来自 `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` 仓库的 `config` 目录。你可以在那里找到更多示例配置文件。`-c` 选项指定配置文件,更多信息请参考 [Configuration](/user-guide/deployments-administration/configuration.md)。 + +## objbench + +`objbench` 子命令是一个用于测量对象存储上特定文件读写性能的基准测试工具。这对于诊断性能问题和测试存储层性能非常有用。 + +### 选项 + +| 选项 | 描述 | +| ------------------------------ | ---------------------------------------------------------------------------------------------------- | +| `--config ` | datanode 配置文件路径(TOML 格式) | +| `--source ` | 对象存储中的源 SST 文件路径(例如 `data/greptime/public/1024/1024_0000000000/metadata/.parquet`)| +| `-v`/`--verbose` | 启用详细输出 | +| `--pprof-file ` | pprof 火焰图的输出文件路径(启用性能分析)。生成 SVG 格式的火焰图文件 | + +### 示例 + +#### 基础基准测试 + +测量特定文件的读写性能: + +```sh +greptime datanode objbench --config ./datanode.toml --source data/greptime/public/1024/1024_0000000000/metadata/8fb41bc7-a106-4b9e-879b-392da799f958.parquet +``` + +#### 带性能分析的基准测试 + +测量性能并生成用于性能分析的火焰图: + +```sh +greptime datanode objbench --config ./datanode.toml --source data/greptime/public/1024/1024_0000000000/metadata/8fb41bc7-a106-4b9e-879b-392da799f958.parquet --pprof-file=./flamegraph.svg +``` + +这将生成一个 SVG 格式的火焰图,可以在 Web 浏览器中打开进行性能分析。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/flownode.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/flownode.md new file mode 100644 index 0000000000..6755d18044 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/flownode.md @@ -0,0 +1,43 @@ +--- +keywords: [GreptimeDB flownode, 命令行界面, flownode 配置, flownode 启动, flownode 选项, flownode 示例] +description: GreptimeDB flownode 命令行界面完整指南,包括配置选项、启动命令以及部署 flownode 实例的实用示例。 +--- + +# Flownode + +## 子命令选项 + +你可以通过以下命令列出所有选项: + +``` +greptime flownode start --help +``` +| Option | Description | +| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `-c`/`--config-file` | Flownode 的配置文件 | +| `--env-prefix ` | 配置的环境变量前缀,默认为`GREPTIMEDB_FLOWNODE` | +| `--metasrv-addrs ...` | etasrv 服务器列表,用逗号或者空格隔开 | +| `--node-id ` | 节点 ID | +| `--rpc-bind-addr ` | gRPC 服务绑定地址 | +| `--rpc-server-addr ` | 该地址用于来自主机外部的连接和通信。如果留空或未设置,服务器将自动使用主机上第一个网络接口的 IP 地址,其端口号与 `rpc_bind_addr` 中指定的相同; | + +所有的 `addr` 类选项都是 `ip:port` 形式的字符串。 + +## Examples + +### 使用配置启动服务 + +使用自定义配置启动 Flownode 实例: + +```sh +greptime flownode start -c config/flownode.example.toml +``` + + +使用命令行参数启动 Flownode,指定 gRPC 服务地址、Metasrv 地址: + +```sh +greptime flownode start --node-id=0 --rpc-bind-addr=127.0.0.1:6800 --metasrv-addrs=127.0.0.1:3002 +``` + +`flownode.example.toml` 配置文件来自 `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` 仓库的 `config` 目录。你可以在那里找到更多示例配置文件。`-c` 选项指定配置文件,更多信息请参考 [Configuration](/user-guide/deployments-administration/configuration.md)。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/frontend.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/frontend.md new file mode 100644 index 0000000000..8717ec87b7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/frontend.md @@ -0,0 +1,51 @@ +--- +keywords: [GreptimeDB frontend, 命令行界面, frontend 配置, frontend 启动, frontend 选项, frontend 示例] +description: GreptimeDB frontend 命令行界面完整指南,包括配置选项、启动命令以及部署 frontend 实例的实用示例。 +--- + +# Frontend + +## 子命令选项 + +你可以通过以下命令列出所有选项: + +``` +greptime frontend start --help +``` + +| Option | Description | +| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-c`/`--config-file` | Frontend 的配置文件 | +| `--disable-dashboard` | 禁用 dashboard http 服务,默认是 `false` | +| `--env-prefix ` | 配置的环境变量前缀,默认为`GREPTIMEDB_FRONTEND` | +| `--rpc-bind-addr ` | gRPC 服务绑定地址 | +| `--rpc-server-addr ` | 该地址用于来自主机外部的连接和通信。如果留空或未设置,服务器将自动使用主机上第一个网络接口的 IP 地址,其端口号与 `rpc_bind_addr` 中指定的相同; | +| `--http-timeout ` | HTTP 请求超时时间(秒) | +| `--influxdb-enable` | 是否启用 InfluxDB 协议 | +| `--metasrv-addrs ` | Metasrv 服务器列表,用逗号或者空格隔开 | +| `--mysql-addr ` | MySQL 服务器地址 | +| `--postgres-addr ` | Postgres 服务器地址 | +| `--tls-cert-path ` | TLS 公钥文件路径 | +| `--tls-key-path ` | TLS 私钥文件路径 | +| `--tls-mode ` | TLS 模式 | +| `--user-provider ` | 您可以参考 [authentication](/user-guide/deployments-administration/authentication/overview.md) | + +所有的 `addr` 类选项都是 `ip:port` 形式的字符串。 + +## Examples + +### 使用配置启动服务 + +使用自定义配置启动 Frontend 实例: + +```sh +greptime frontend start -c config/frontend.example.toml +``` + +使用命令行参数启动 Frontend,指定 Metasrv 地址: + +```sh +greptime frontend start --metasrv-addrs=0.0.0.0:3002 +``` + +`frontend.example.toml` 配置文件来自 `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` 仓库的 `config` 目录。你可以在那里找到更多示例配置文件。`-c` 选项指定配置文件,更多信息请参考 [Configuration](/user-guide/deployments-administration/configuration.md)。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/metasrv.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/metasrv.md new file mode 100644 index 0000000000..f7e7aa5623 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/metasrv.md @@ -0,0 +1,41 @@ +--- +keywords: [GreptimeDB metasrv, 命令行界面, metasrv 配置, metasrv 启动, metasrv 选项, metasrv 示例] +description: GreptimeDB metasrv 命令行界面完整指南,包括配置选项、启动命令以及部署和管理 metasrv 实例的实用示例。 +--- + +# Metasrv + +## 子命令选项 + +你可以通过以下命令列出所有选项: + +``` +greptime metasrv start --help +``` + +| Option | Description | +| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-c`/`--config-file` | Metasrv 的配置文件 | +| `--enable-region-failover` | 是否启用 Region 自动容灾,默认是 `false`。开启条件请参考:[Region 自动容灾](/user-guide/deployments-administration/manage-data/region-failover.md) | +| `--env-prefix ` | 配置的环境变量前缀,默认为`GREPTIMEDB_METASRV` | +| `--rpc-bind-addr ` | gRPC 服务绑定地址 | +| `--rpc-server-addr ` | 该地址用于来自主机外部的连接和通信。如果留空或未设置,服务器将自动使用主机上第一个网络接口的 IP 地址,其端口号与 `rpc_bind_addr` 中指定的相同; | +| `--http-addr ` | HTTP 服务器地址 | +| `--http-timeout ` | HTTP 请求超时时间(秒) | +| `--selector ` | 您可以参考 [selector-type](/contributor-guide/metasrv/selector.md#selector-type) | +| `--store-addrs ` | 逗号或空格分隔的键值存储服务器(默认是 etcd)地址,用于存储元数据 | +| `--use-memory-store` | 用内存存储而不是其他持久化的存储后端,仅用于测试目的的 | + +所有的 `addr` 类选项都是 `ip:port` 形式的字符串。 + +## 示例 + +### 使用配置启动服务 + +使用自定义配置启动 Metasrv 实例: + +```sh +greptime metasrv start -c config/metasrv.example.toml +``` + +`metasrv.example.toml` 配置文件来自 `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` 仓库的 `config` 目录。你可以在那里找到更多示例配置文件。`-c` 选项指定配置文件,更多信息请参考 [Configuration](/user-guide/deployments-administration/configuration.md)。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/overview.md new file mode 100644 index 0000000000..c1952b4d45 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/overview.md @@ -0,0 +1,67 @@ +--- +keywords: [命令行工具, 安装 Greptime, 启动服务, 配置示例, 升级版本] +description: 介绍 Greptime 命令行工具的安装、使用方法,包括全局选项、各子命令选项、配置示例、升级 GreptimeDB 版本等内容。 +--- + +# 概述 + +`greptime` 命令行工具可以启动、停止、或传递配置项给 GreptimeDB。 + +## 安装命令行工具 + +Greptime 命令行工具与 GreptimeDB 二进制文件捆绑在一起。 + +如果你按照[快速安装 GreptimeDB](/getting-started/installation/overview.md)文档中所述使用二进制文件启动的 GreptimeDB,可以在 GreptimeDB 的当前目录中执行 `./greptime` 命令。 +为了方便起见,如果你希望使用 `greptime` 而不是 `./greptime` 来运行命令, +可以将命令行工具的二进制文件移动到系统的 `bin` 目录,或者将二进制文件的路径添加到 `PATH` 环境变量中。 + +如果你是在 Kubernetes 中部署的 GreptimeDB,可以通过 frontend pod 访问 greptime 命令行工具。使用以下命令进入 pod: + +```sh +kubectl exec -it -n -- /bin/bash +``` + +进入 pod 后,可以运行 `greptime help` 查看所有可用命令。 + +## 选项 + +`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 +``` + +### 全局选项 + +| Option | Description | +| ------------------------- | ----------------------------------------- | +| `-h`/`--help` | 打印帮助信息 | +| `-V`/`--version` | 打印版本信息 | +| `--log-dir ` | 日志目录,默认是 `./greptimedb_data/logs` | +| `--log-level ` | 日志级别,默认是 `info` | + +### 子命令 +- [Metasrv](/reference/command-lines/metasrv.md) +- [Datanode](/reference/command-lines/datanode.md) +- [Flownode](/reference/command-lines/flownode.md) +- [Frontend](/reference/command-lines/frontend.md) +- [Standalone](/reference/command-lines/standalone.md) + +### 升级 GreptimeDB 版本 + +请参考具体的[升级步骤](/user-guide/deployments-administration/upgrade.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/standalone.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/standalone.md new file mode 100644 index 0000000000..47168c5f5d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/standalone.md @@ -0,0 +1,38 @@ +--- +keywords: [GreptimeDB standalone, 命令行界面, standalone 配置, standalone 启动, standalone 选项, standalone 示例] +description: GreptimeDB standalone 命令行界面完整指南,包括配置选项、启动命令以及部署 standalone 实例的实用示例。 +--- + +# Standalone + +## 子命令选项 + +你可以通过以下命令列出所有选项: + + +``` +greptime standalone start --help +``` +| Option | Description | +| --------------------------------- | ------------------------------------------------- | +| `-c`/`--config-file` | Standalone 的配置文件 | +| `--env-prefix ` | 配置的环境变量前缀,默认为`GREPTIMEDB_STANDALONE` | +| `--http-addr ` | HTTP 服务器地址 | +| `--influxdb-enable` | 是否启用 InfluxDB 协议 | +| `--mysql-addr ` | MySQL 服务器地址 | +| `--postgres-addr ` | Postgres 服务器地址 | +| `--rpc-bind-addr ` | gRPC 服务绑定地址 | + +所有的 `addr` 类选项都是 `ip:port` 形式的字符串。 + +## 示例 + +### 使用配置启动服务 + +使用自定义配置启动 Standalone 实例: + +```sh +greptime --log-dir=greptimedb_data/logs --log-level=info standalone start -c config/standalone.example.toml +``` + +`standalone.example.toml` 配置文件来自 `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` 仓库的 `config` 目录。你可以在那里找到更多示例配置文件。`-c` 选项指定配置文件,更多信息请参考 [Configuration](/user-guide/deployments-administration/configuration.md)。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/data.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/data.md new file mode 100644 index 0000000000..e02bda114f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/data.md @@ -0,0 +1,72 @@ +--- +keywords: [备份, 恢复, 导出工具, 导入工具, 数据库备份, 数据恢复, 命令行工具, 数据导出, 数据导入] +description: 介绍 GreptimeDB 的数据导出和导入工具,用于数据库备份和恢复,包括命令语法、选项。 +--- + +# 数据导出和导入 + +数据导出和导入工具提供了备份和恢复 GreptimeDB 数据库的功能。这些工具可以处理表结构和数据,允许进行完整的备份或选择性的备份和恢复操作。 + +## 导出工具 + +### 命令语法 +```bash +greptime cli data 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`) | +| `--proxy` | 否 | - | 代理服务器地址,如设置该参数,将覆盖系统代理。如果未设置 `--proxy` 和 `--no-proxy`,则默认使用系统代理 | +| `--no-proxy` | 否 | - | 禁用代理服务器,如设置该参数,将完全不使用代理 | +| `--s3` | 否 | - | 是否导出数据到 Amazon S3 | +| `--ddl-local-dir` | 否 | - | 当同时设置了 `ddl_local_dir` 和远程存储(如 S3/OSS)时,SQL 文件将导出至本地目录,而数据将导出到远程存储。注意:`ddl_local_dir` 只导出 SQL 文件至**本地文件系统**,适用于导出客户端无法直接访问远程存储的情况。如果未设置 `ddl_local_dir`,则 SQL 和数据都将导出至远程存储 | +| `--s3-bucket` | 是\* | - | 当设置了 `--s3` 时,必须指定 S3 的 bucket 名称 | +| `--s3-root` | 是\* | - | 当设置了 `--s3` 时,必须指定导出在 bucket 中的根路径 | +| `--s3-endpoint` | 否\* | - | 当设置了 `--s3` 时,需指定 S3 的 endpoint | +| `--s3-access-key` | 是\* | - | 当设置了 `--s3` 时,需指定 S3 的 Access Key | +| `--s3-secret-key` | 是\* | - | 当设置了 `--s3` 时,需指定 S3 的 Secret Key | +| `--s3-region` | 是\* | - | 当设置了 `--s3` 时,需指定 S3 的区域(Region) | +| `--oss` | 否 | - | 是否导出数据到阿里云 OSS | +| `--oss-bucket` | 是\* | - | 当设置了 `--oss` 时,需指定 OSS 的 bucket 名称 | +| `--oss-endpoint` | 否\* | - | 当设置了 `--oss` 时,需指定 OSS 的 endpoint | +| `--oss-access-key-id` | 是\* | - | 当设置了 `--oss` 时,需指定 OSS 的 Access Key ID | +| `--oss-access-key-secret` | 是\* | - | 当设置了 `--oss` 时,需指定 OSS 的 Access Key Secret | + +### 导出目标 +- `schema`: 仅导出表结构(`SHOW CREATE TABLE`) +- `data`: 仅导出表数据(`COPY DATABASE TO`) +- `all`: 导出表结构和数据(默认) + +## 导入工具 + +### 命令语法 +```bash +greptime cli data 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`: 导入表结构和数据(默认) \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/metadata-interaction.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/metadata-interaction.md new file mode 100644 index 0000000000..9e2a14ccfb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/metadata-interaction.md @@ -0,0 +1,255 @@ +--- +keywords: [GreptimeDB CLI, 元数据交互, 键值操作, 表元数据, 存储后端] +description: 使用 CLI 与 GreptimeDB 元数据交互的指南,包括键值操作、表元数据检索和删除。 +--- + +# 元数据交互 + +`greptime cli meta` 命令可以用于与 GreptimeDB 集群的元数据进行交互。 + + +## 公共选项 + +| 选项 | 描述 | 默认值 | 值 | +| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------------------- | +| `--store-addrs ...` | 元数据存储服务地址。可以是 etcd、postgres 或 mysql。
对于 postgres 存储,格式为:`"password=password dbname=postgres user=postgres host=localhost port=5432"`。
对于 etcd 存储,格式为:`"127.0.0.1:2379"`。
对于 mysql 存储,格式为:`"mysql://user:password@ip:port/dbname"` | - | - | +| `--max-txn-ops ` | 单个事务中操作的最大数量。仅在使用 [etcd-store] 时使用 | 128 | - | +| `--backend ` | 元数据存储后端类型 | etcd-store | etcd-store, memory-store, postgres-store, mysql-store | +| `--store-key-prefix ` | 元数据存储前缀缀 | - | - | +| `--meta-table-name ` | 元数据存储的表名。元数据存储后端为 [postgres-store] 或 [mysql-store] 时使用 | greptime_metakv | - | + + + +## 获取键值对 + +### 命令语法 + +```bash +greptime cli meta get key [OPTIONS] [KEY] +``` + +### 选项 + +| 选项 | 描述 | 默认值 | +| ----------------- | ----------------------------------------------------------------------- | ------ | +| `--prefix` | 是否执行前缀查询。如果为 true,则返回所有键值对,其中键以给定的前缀开头 | false | +| `--limit ` | 返回的最大键值对数量。如果为 0,则返回所有键值对 | 0 | + +## 获取表元数据 + +### 命令语法 + +```bash +greptime cli meta get table [OPTIONS] +``` + +### 选项 + +| 选项 | 描述 | 默认值 | +| ------------------------------- | ---------------------- | -------- | +| `--table-id ` | 通过表 ID 获取表元数据 | - | +| `--table-name ` | 通过表名获取表元数据 | - | +| `--schema-name ` | 所属数据库的名称 | public | +| `--catalog-name ` | 所属 catalog 的名称 | greptime | +| `--pretty` | 美化输出 | - | + + +## 删除键值对 + +### 命令语法 + +```bash +greptime cli meta del key [OPTIONS] [KEY] +``` + +### 选项 + + +| Option | 描述 | 默认值 | +| ---------- | -------------------------- | ------ | +| `--prefix` | 删除具有给定前缀的键值对。 | false | + + +## 删除表元数据 + +### 命令语法 + +```bash +greptime cli meta del table [OPTIONS] +``` + +#### 选项 + +| Option | 描述 | 默认值 | +| ------------------------------- | ---------------------- | -------- | +| `--table-id ` | 通过表 ID 获取表元数据 | - | +| `--table-name ` | 通过表名获取表元数据 | - | +| `--schema-name ` | 表所属数据库的名称 | public | +| `--catalog-name ` | 表所属 catalog 的名称 | greptime | + + +## 示例 + +### 获取单个键值对 + +```bash +greptime cli meta get key --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + __table_name/greptime/public/metric_table_2 +``` + +输出: + +```json +__table_name/greptime/public/metric_table_2 +{"table_id":1059} +``` + +### 获取所有具有给定前缀的键值对 + +输出: +```bash +greptime cli meta get key --prefix \ + --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + __table_name/greptime/public +``` + +```json +__table_name/greptime/public/greptime_physical_table +{"table_id":1057} +__table_name/greptime/public/metric_table_1 +{"table_id":1058} +__table_name/greptime/public/metric_table_2 +{"table_id":1059} +``` + +### 通过表 ID 获取表元数据 + +```bash +greptime cli meta get table --table-id=1059 \ + --store-addrs=$ENDPOINT \ + --backend=postgres-store +``` + +输出: + +```json +__table_info/1059 +{ + "table_info": { + "ident": { + "table_id": 1059, + "version": 0 + }, + "name": "metric_table_2", + "desc": null, + "catalog_name": "greptime", + "schema_name": "public", + "meta": { + "schema": { + "column_schemas": [ + { + "name": "app", + "data_type": { + "String": null + }, + "is_nullable": true, + "is_time_index": false, + "default_constraint": null, + "metadata": {} + }, + ... + ], + "timestamp_index": 2, + "version": 0 + }, + "primary_key_indices": [ + 0, + ... + ], + "value_indices": [ + 3 + ], + "engine": "metric", + "next_column_id": 8, + "region_numbers": [ + 0, + ... + ], + "options": { + "write_buffer_size": null, + "ttl": null, + "skip_wal": false, + "extra_options": { + "on_physical_table": "greptime_physical_table" + } + }, + "created_on": "2025-06-17T14:53:14.639207075Z", + "partition_key_indices": [] + }, + "table_type": "Base" + }, + "version": 0 +} +__table_route/1059 +{ + "type": "logical", + "physical_table_id": 1057, + "region_ids": [ + 4548370366464, + 4548370366465, + ... + ] +} +``` + +### 通过表名获取表元数据 + +```bash +greptime cli meta get table --table-name=metric_table_2 \ + --schema-name=public \ + --store-addrs=$ENDPOINT \ + --backend=postgres-store +``` + +输出: 与上述命令的输出相同。 + +## 删除不存在的键值对 + +```bash +greptime cli meta del key --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + non_existent_key +``` + +输出(返回删除的键值对数量): +```bash +0 +``` + +## 删除键值对 + +```bash +greptime cli meta del key --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + __table_name/greptime/public/metric_table_3 +``` + +输出(返回删除的键值对数量): +```bash +1 +``` + +## 删除表元数据 + +```bash +greptime cli meta del table --table-id=1059 \ + --store-addrs=$ENDPOINT \ + --backend=postgres-store +``` + +输出: +```bash +Table(1059) deleted +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/metadata.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/metadata.md new file mode 100644 index 0000000000..f50c814a04 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/metadata.md @@ -0,0 +1,240 @@ +--- +keywords: [备份, 恢复, 导出工具, 导入工具, 数据库元信息备份, 数据恢复, 命令行工具, GreptimeDB CLI, 灾难恢复] +description: 介绍 GreptimeDB 的元信息导出和导入工具,用于数据库元信息的备份和恢复,包括命令语法、选项。 +--- + +# 元数据导出和导入 + +元数据导出和导入工具提供了备份和恢复 GreptimeDB 元信息的功能。这些工具允许进行元信息备份和恢复操作。 + +## 导出工具 + +### 命令语法 + +```bash +greptime cli meta snapshot save [OPTIONS] +``` + +### 选项 + +#### 存储后端选项 + +| 选项 | 是否必需 | 默认值 | 描述 | +| ------------------ | -------- | ----------------- | ------------------------------------------------------------------------------------------------------ | +| --store-addrs | 是 | - | 要连接的元数据存储服务地址(仅支持 etcd、MySQL、PostgreSQL),格式与 Metasrv 配置中的 store-addrs 一致 | +| --backend | 是 | - | 元数据存储后端类型,支持 `etcd-store`、`postgres-store`、`mysql-store` | +| --store-key-prefix | 否 | "" | 元数据存储前缀,参考 Metasrv 配置 | +| --meta-table-name | 否 | greptime_metakv | 当后端为 `postgres-store` 或 `mysql-store` 时,元数据存储的表名 | +| --max-txn-ops | 否 | 128 | 最大事务操作数 | + +#### 文件选项 + +| 选项 | 是否必需 | 默认值 | 描述 | +| ----------- | -------- | ----------------- | -------------------------------------------------- | +| --file-name | 否 | metadata_snapshot | 元数据导出的文件名,会自动添加 `.metadata.fb` 后缀 | +| --dir | 否 | "" | 存储导出数据的目录 | + +#### 对象存储选项 + +要使用对象存储来存储导出的元数据,请启用以下任一提供商并配置其连接参数: + +##### S3 + +| 选项 | 是否必需 | 默认值 | 描述 | +| ------------------------------ | -------- | ------ | ------------------------------------------- | +| --enable-s3 | 否 | false | 是否使用 S3 作为导出数据的存储介质 | +| --s3-bucket | 否 | - | S3 桶名 | +| --s3-root | 否 | - | S3 桶中的根路径 | +| --s3-access-key-id | 否 | - | S3 访问密钥 ID | +| --s3-secret-access-key | 否 | - | S3 访问密钥 | +| --s3-region | 否 | - | S3 区域名称 | +| --s3-endpoint | 否 | - | S3 端点 URL(可选,默认根据桶区域确定) | +| --s3-enable-virtual-host-style | 否 | false | 为 S3 API 请求启用虚拟主机样式 | + +##### OSS(阿里云) + +| 选项 | 是否必需 | 默认值 | 描述 | +| ----------------------- | -------- | ------ | ---------------------------------- | +| --enable-oss | 否 | false | 是否使用 OSS 作为导出数据的存储介质 | +| --oss-bucket | 否 | - | OSS 桶名 | +| --oss-root | 否 | - | OSS 桶中的根路径 | +| --oss-access-key-id | 否 | - | OSS 访问密钥 ID | +| --oss-access-key-secret | 否 | - | OSS 访问密钥 | +| --oss-endpoint | 否 | - | OSS 端点 URL | + +##### GCS(谷歌云存储) + +| 选项 | 是否必需 | 默认值 | 描述 | +| --------------------- | -------- | ------ | ---------------------------------- | +| --enable-gcs | 否 | false | 是否使用 GCS 作为导出数据的存储介质 | +| --gcs-bucket | 否 | - | GCS 桶名 | +| --gcs-root | 否 | - | GCS 桶中的根路径 | +| --gcs-scope | 否 | - | GCS 服务范围 | +| --gcs-credential-path | 否 | - | GCS 凭证文件路径 | +| --gcs-credential | 否 | - | GCS 凭证内容 | +| --gcs-endpoint | 否 | - | GCS 端点 URL | + +##### Azure Blob 存储 + +| 选项 | 是否必需 | 默认值 | 描述 | +| --------------------- | -------- | ------ | ---------------------------------------- | +| --enable-azblob | 否 | false | 是否使用 Azure Blob 作为导出数据的存储介质 | +| --azblob-container | 否 | - | Azure Blob 容器名称 | +| --azblob-root | 否 | - | 容器中的根路径 | +| --azblob-account-name | 否 | - | Azure Blob 账户名称 | +| --azblob-account-key | 否 | - | Azure Blob 账户密钥 | +| --azblob-endpoint | 否 | - | Azure Blob 端点 URL | +| --azblob-sas-token | 否 | - | Azure Blob SAS 令牌 | + +## 导入工具 + +### 命令语法 + +```bash +greptime cli meta snapshot restore [OPTIONS] +``` + +### 选项 + +#### 存储后端选项 + +| 选项 | 是否必需 | 默认值 | 描述 | +| ------------------ | -------- | --------------- | ------------------------------------------------------------------------------------------------------ | +| --store-addrs | 是 | - | 要连接的元数据存储服务地址(仅支持 etcd、MySQL、PostgreSQL),格式与 Metasrv 配置中的 store-addrs 一致 | +| --backend | 是 | - | 元数据存储后端类型,支持 `etcd-store`、`postgres-store`、`mysql-store` | +| --store-key-prefix | 否 | "" | 元数据存储的 key 前缀,参考 Metasrv 配置 | +| --meta-table-name | 否 | greptime_metakv | 当后端为 `postgres-store` 或 `mysql-store` 时,元数据存储的表名 | +| --max-txn-ops | 否 | 128 | 最大事务操作数 | + +#### 文件选项 + +| 选项 | 是否必需 | 默认值 | 描述 | +| ----------- | -------- | ----------------------------- | -------------------------------------------------------------------------------------- | +| --file-name | 否 | metadata_snapshot.metadata.fb | 元数据导出的文件名 | +| --dir | 否 | "." | 存储导出数据的目录 | +| --force | 否 | false | 是否强制导入,当目标后端检测包含旧数据时,默认无法导入数据,若想强制导入则可开启此标志 | + +#### 对象存储选项 + +要使用对象存储来导入元数据,请启用以下任一提供商并配置其连接参数: + +##### S3 + +| 选项 | 是否必需 | 默认值 | 描述 | +| ------------------------------ | -------- | ------ | ------------------------------------------- | +| --enable-s3 | 否 | false | 是否使用 S3 作为导出数据的存储介质 | +| --s3-bucket | 否 | - | S3 桶名 | +| --s3-root | 否 | - | S3 桶中的根路径 | +| --s3-access-key-id | 否 | - | S3 访问密钥 ID | +| --s3-secret-access-key | 否 | - | S3 访问密钥 | +| --s3-region | 否 | - | S3 区域名称 | +| --s3-endpoint | 否 | - | S3 端点 URL(可选,默认根据桶区域确定) | +| --s3-enable-virtual-host-style | 否 | false | 为 S3 API 请求启用虚拟主机样式 | + +##### OSS(阿里云) + +| 选项 | 是否必需 | 默认值 | 描述 | +| ----------------------- | -------- | ------ | ---------------------------------- | +| --enable-oss | 否 | false | 是否使用 OSS 作为导出数据的存储介质 | +| --oss-bucket | 否 | - | OSS 桶名 | +| --oss-root | 否 | - | OSS 桶中的根路径 | +| --oss-access-key-id | 否 | - | OSS 访问密钥 ID | +| --oss-access-key-secret | 否 | - | OSS 访问密钥 | +| --oss-endpoint | 否 | - | OSS 端点 URL | + +##### GCS(谷歌云存储) + +| 选项 | 是否必需 | 默认值 | 描述 | +| --------------------- | -------- | ------ | ---------------------------------- | +| --enable-gcs | 否 | false | 是否使用 GCS 作为导出数据的存储介质 | +| --gcs-bucket | 否 | - | GCS 桶名 | +| --gcs-root | 否 | - | GCS 桶中的根路径 | +| --gcs-scope | 否 | - | GCS 服务范围 | +| --gcs-credential-path | 否 | - | GCS 凭证文件路径 | +| --gcs-credential | 否 | - | GCS 凭证内容 | +| --gcs-endpoint | 否 | - | GCS 端点 URL | + +##### Azure Blob 存储 + +| 选项 | 是否必需 | 默认值 | 描述 | +| --------------------- | -------- | ------ | ---------------------------------------- | +| --enable-azblob | 否 | false | 是否使用 Azure Blob 作为导出数据的存储介质 | +| --azblob-container | 否 | - | Azure Blob 容器名称 | +| --azblob-root | 否 | - | 容器中的根路径 | +| --azblob-account-name | 否 | - | Azure Blob 账户名称 | +| --azblob-account-key | 否 | - | Azure Blob 账户密钥 | +| --azblob-endpoint | 否 | - | Azure Blob 端点 URL | +| --azblob-sas-token | 否 | - | Azure Blob SAS 令牌 | + +## 信息工具 + +信息工具允许您查看元数据快照的内容而无需恢复它。 + +### 命令语法 + +```bash +greptime cli meta snapshot info [OPTIONS] +``` + +### 选项 + +#### 文件选项 + +| 选项 | 是否必需 | 默认值 | 描述 | +| ------------- | -------- | ----------------- | ---------------------- | +| --file-name | 否 | metadata_snapshot | 要查看的元数据快照文件名 | +| --dir | 否 | "." | 快照文件存储的目录 | +| --inspect-key | 否 | "*" | 过滤元数据键的查询模式 | +| --limit | 否 | - | 显示的最大条目数 | + +#### 对象存储选项 + +要检查存储在对象存储中的快照,请启用以下任一提供商并配置其连接参数: + +##### S3 + +| 选项 | 是否必需 | 默认值 | 描述 | +| ------------------------------ | -------- | ------ | --------------------------------------- | +| --enable-s3 | 否 | false | 是否使用 S3 作为快照的存储介质 | +| --s3-bucket | 否 | - | S3 桶名 | +| --s3-root | 否 | - | S3 桶中的根路径 | +| --s3-access-key-id | 否 | - | S3 访问密钥 ID | +| --s3-secret-access-key | 否 | - | S3 访问密钥 | +| --s3-region | 否 | - | S3 区域名称 | +| --s3-endpoint | 否 | - | S3 端点 URL(可选,默认根据桶区域确定) | +| --s3-enable-virtual-host-style | 否 | false | 为 S3 API 请求启用虚拟主机样式 | + +##### OSS(阿里云) + +| 选项 | 是否必需 | 默认值 | 描述 | +| ----------------------- | -------- | ------ | ------------------------------ | +| --enable-oss | 否 | false | 是否使用 OSS 作为快照的存储介质 | +| --oss-bucket | 否 | - | OSS 桶名 | +| --oss-root | 否 | - | OSS 桶中的根路径 | +| --oss-access-key-id | 否 | - | OSS 访问密钥 ID | +| --oss-access-key-secret | 否 | - | OSS 访问密钥 | +| --oss-endpoint | 否 | - | OSS 端点 URL | + +##### GCS(谷歌云存储) + +| 选项 | 是否必需 | 默认值 | 描述 | +| --------------------- | -------- | ------ | ------------------------------ | +| --enable-gcs | 否 | false | 是否使用 GCS 作为快照的存储介质 | +| --gcs-bucket | 否 | - | GCS 桶名 | +| --gcs-root | 否 | - | GCS 桶中的根路径 | +| --gcs-scope | 否 | - | GCS 服务范围 | +| --gcs-credential-path | 否 | - | GCS 凭证文件路径 | +| --gcs-credential | 否 | - | GCS 凭证内容 | +| --gcs-endpoint | 否 | - | GCS 端点 URL | + +##### Azure Blob 存储 + +| 选项 | 是否必需 | 默认值 | 描述 | +| --------------------- | -------- | ------ | ------------------------------------ | +| --enable-azblob | 否 | false | 是否使用 Azure Blob 作为快照的存储介质 | +| --azblob-container | 否 | - | Azure Blob 容器名称 | +| --azblob-root | 否 | - | 容器中的根路径 | +| --azblob-account-name | 否 | - | Azure Blob 账户名称 | +| --azblob-account-key | 否 | - | Azure Blob 账户密钥 | +| --azblob-endpoint | 否 | - | Azure Blob 端点 URL | +| --azblob-sas-token | 否 | - | Azure Blob SAS 令牌 | diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/repair-logical-tables.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/repair-logical-tables.md new file mode 100644 index 0000000000..1621bd48f7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/command-lines/utilities/repair-logical-tables.md @@ -0,0 +1,55 @@ +--- +keywords: [GreptimeDB CLI, 逻辑表修复, 元数据修复, 表元数据, 存储后端] +description: 使用 CLI 修复 GreptimeDB 集群逻辑表的指南,包括元数据一致性修复。 +--- + +# 逻辑表修复 + +`greptime cli meta repair-logical-tables` 命令可以用于修复 GreptimeDB 集群的逻辑表。在某些情况下,逻辑表元数据可能与存储在元数据存储中的元数据不一致。此命令可用于修复逻辑表元数据。 + +:::tip +该工具需要连接到元数据存储和 Datanode。确保集群正在运行且工具可与 Datanode 通信。 +::: + +## 命令语法 + +```bash +greptime cli meta repair-logical-tables [OPTIONS] +``` + +## 选项 + +| 选项 | 描述 | 默认值 | 值 | +| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------------------- | +| `--store-addrs ...` | 元数据存储服务地址。可以是 etcd、postgres 或 mysql。
对于 postgres 存储,格式为:`"password=password dbname=postgres user=postgres host=localhost port=5432"`。
对于 etcd 存储,格式为:`"127.0.0.1:2379"`。
对于 mysql 存储,格式为:`"mysql://user:password@ip:port/dbname"` | - | - | +| `--max-txn-ops ` | 单个事务中操作的最大数量。仅在使用 [etcd-store] 时使用 | 128 | - | +| `--backend ` | 元数据存储后端类型 | etcd-store | etcd-store, memory-store, postgres-store, mysql-store | +| `--store-key-prefix ` | 元数据存储前缀 | - | - | +| `--meta-table-name ` | 元数据存储的表名。元数据存储后端为 [postgres-store] 或 [mysql-store] 时使用 | greptime_metakv | - | +| `--table-names ` | 要修复的表名,用逗号分隔 | - | +| `--table-ids ` | 要修复的表 ID,用逗号分隔 | - | +| `--schema-name ` | 要修复的表所属数据库的名称 | public | +| `--catalog-name ` | 要修复的表所属 catalog 的名称 | greptime | +| `--fail-fast` | 如果任何修复操作失败,是否立即失败 | - | +| `--client-timeout-secs ` | 客户端操作 Datanode 的超时时间 | 30 | +| `--client-connect-timeout-secs ` | 客户端连接 Datanode 的超时时间 | 3 | + + +## 示例 + +### 通过表名修复逻辑表 + +```bash +greptime cli repair-logical-tables --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + --table-names=metric_table_1,metric_table_2 \ + --schema-name=public \ + --catalog-name=greptime +``` + +输出: +```bash +2025-06-20T08:31:43.904497Z INFO cli::metadata::repair: All alter table requests sent successfully for table: greptime.public.metric_table_1 +2025-06-20T08:31:43.904499Z INFO cli::metadata::repair: All alter table requests sent successfully for table: greptime.public.metric_table_2 +2025-06-20T08:31:43.904539Z INFO cli::metadata::repair: Repair logical tables result: 2 tables repaired, 0 tables skipped +``` \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/glossary.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/glossary.md new file mode 100644 index 0000000000..e9f0bf5a93 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/glossary.md @@ -0,0 +1,240 @@ +--- +keywords: [云原生, 可观测, 开源, 时序数据库, 车联网, 物联网, 日志, 指标, 事件, Rust] +description: 本文档提供与云原生开源时序数据库 GreptimeDB 相关的核心术语与概念的清晰定义和解析,涵盖指标、日志及事件处理领域。通过探索术语库,深入了解支撑 GreptimeDB 的创新功能与技术架构。 +--- + +# Glossary(术语表) + +欢迎访问 GreptimeDB 技术术语库!本资源系统阐释了云原生开源时序数据库 GreptimeDB 的核心概念与关键技术术语,涵盖指标、日志及事件处理领域。通过本术语库,您将深入理解支撑 GreptimeDB 的创新架构与技术实现。 + +> 注:该排名顺序按照英文词汇首字母正序排列。 + +--- + +## A + +### Anomaly Detection (异常检测) +识别数据点、事件或观测值显著偏离常态的过程。在时序数据场景中,异常检测可辅助发现可能表征关键事件的非常规模式。 + +### Append Only Table (Append Only 表) +GreptimeDB 中针对写入密集型工作负载优化的表类型,数据仅插入而不更新或删除。这种设计显著提升写入和查询性能,特别适用于日志分析和时序数据场景。 + +--- + +## C + +### Cardinality (基数) +衡量数据库元素唯一性的指标,如数据列中唯一值的数量。高基数场景(尤其在时序数据中)将显著提升存储复杂度与资源需求。 + +### Cloud-Native Design (云原生架构) +基于云计算框架构建弹性可扩展应用的架构方法论。GreptimeDB 的云原生设计支持从边缘计算节点到云端分布式集群的无缝扩展。 + +### Columnar Storage (列式存储) +按列而非行组织数据表的存储格式。该格式显著提升分析型查询效率,是 GreptimeDB 实现高性价比的重要技术基础。 + +--- + +## D + +### Decoupled Compute and Storage Architecture (存算分离架构) +将计算资源与存储资源解耦管理的架构设计。该架构支持独立扩展与资源优化,实现工作负载管理的灵活性与高性能。 + +--- + +## E + +### Edge Database (边缘数据库) +部署在网络边缘侧(临近数据源或终端用户)的数据库系统,通过降低数据传输延迟实现实时数据处理。 + +### Edge Deployment (边缘部署) +在临近数据源或终端用户的边缘节点部署服务的实践方案。GreptimeDB 支持边缘部署模式,可在资源受限环境下实现实时数据处理。 + +### Event Management (事件管理) +对指标、日志、追踪等事件数据进行采集、组织与分析的系统化实践,是保障实时系统稳定运行的核心环节。 + +--- + +## D + +### Datanode (数据节点) +GreptimeDB 分布式架构中负责数据存储和处理的核心组件。Datanode 处理数据摄入、存储管理、本地数据查询执行,并维护包含实际表数据的 region。可在集群中部署多个 datanode 以提供水平可扩展性、容错能力和分布式数据处理能力。 + +--- + +## F + +### Field (字段) +GreptimeDB 数据模型中包含实际测量数据或日志内容的列类型。Field 存储数值、文本内容或其他数据指标,代表时序数据中的核心信息,与 Tag 和 Time Index 列相补构成完整的数据模型。 + +### Flow Engine (流处理引擎) +GreptimeDB 的实时流数据处理系统,支持对流式数据进行连续增量计算。Flow Engine 类似智能物化视图,当源表有新数据到达时自动更新结果表。以可配置间隔(默认一秒)处理数据,计算开销极小,特别适用于 ETL 流程、降采样、实时分析和持续聚合等场景。 + +### Frontend (前端节点) +GreptimeDB 分布式架构中的查询处理层,作为客户端连接的入口点。Frontend 节点处理 SQL 解析、查询规划、分布式查询协调和结果聚合。它们将查询路由到适当的 datanode,管理客户端会话,并为各种数据库接口(包括 MySQL、PostgreSQL 和 GreptimeDB 原生协议)提供协议兼容性。 + +--- + +## G + +### GreptimeCloud +GreptimeDB 的全托管云服务,提供 serverless 自动扩展的数据库即服务(DBaaS)能力。GreptimeCloud 通过自动扩展、按量付费、企业级安全和无缝云边协同部署等特性消除运维开销,非常适合寻求无忧可观测性数据库解决方案的组织。 + +--- + +## I + +### IoT Cloud (物联网云平台) +专为物联网应用设计的云计算平台,提供海量设备数据存储、处理与连接管理能力。 + +### IoT Database (物联网数据库) +针对物联网传感器高频时序数据优化的数据库系统。GreptimeDB 可高效处理物联网设备产生的大规模时序数据,提供弹性扩展能力。 + +### IoT Observability (物联网可观测性) +通过指标、日志与事件数据对物联网设备及系统进行监控、分析与洞察的能力,确保物联网生态的可靠运行。 + +### Interoperability (协议互操作性) +异构系统间无缝协作的能力。GreptimeDB 原生支持 SQL、InfluxDB、OpenTelemetry、Prometheus、Elasticsearch、Loki 等协议与 API,实现开箱即用的系统集成。 + +--- + +## L + +### Log Aggregation (日志聚合) +对一组日志执行计算以生成单个摘要统计数据,以供分析和故障排除,例如 SUM,COUNT 等。 + +### Log Management (日志管理) +涵盖日志采集、存储、分析与可视化的全生命周期管理方案,是保障系统性能与安全的重要基础。 + +--- + +## M + +### Memory Leak (内存泄漏) +程序未能正确释放闲置内存导致的软件缺陷,长期运行可能引发系统性能下降或崩溃。 + +### Metric Engine (指标引擎) +GreptimeDB 中专门设计用于高效处理指标数据的存储引擎,特别适用于可观测性工作负载中常见的数千个小表场景。Metric Engine 使用合成的宽物理表来存储来自众多逻辑表的数据,实现高效的列和元数据重用,降低存储开销并增强列式压缩效果。基于 Mito Engine 构建,提供强大的存储能力。 + +### Mito Engine (Mito 引擎) +GreptimeDB 的默认存储引擎,基于日志结构合并树(LSM-Tree)架构,针对时序工作负载进行优化。Mito 具备预写日志(WAL)、内存表和时间窗口压缩策略(TWCS),能够处理高吞吐量写入同时保持出色的查询性能。原生集成对象存储解决方案(S3、GCS、Azure Blob)并实现分层缓存以优化存储成本和访问速度。 + +--- + +## L + +### LSM-Tree (日志结构合并树) +GreptimeDB 存储引擎采用的数据结构,通过先将数据写入日志再定期合并为有序结构来优化写入性能。该设计特别适合高写入吞吐量的时序工作负载。 + +--- + +## M + +### Metasrv (元数据服务) +GreptimeDB 分布式架构中的元数据管理服务,维护集群状态、表结构和 region 分布信息。Metasrv 协调集群操作,管理表的创建和修改,处理 region 分配和迁移,确保集群范围内的元数据一致性。它作为集群管理的中央控制平面,是所有元数据操作的权威数据源。 + +--- + +## O + +### Observability (可观测性) +通过系统外部输出推断内部状态的能力。GreptimeDB 作为可观测性基础设施,可通过指标、日志与事件数据实现系统性能监控与深度洞察。 + +### OpenTelemetry +面向云原生应用的开源可观测性框架,提供遥测数据(追踪、指标、日志)的采集、处理与导出工具链。GreptimeDB 深度集成 OpenTelemetry 以强化数据可观测性。 + +--- + +## P + +### Pipeline (数据管道) +GreptimeDB 中用于实时处理传入数据的强大解析和转换机制。Pipeline 由可配置的处理器组成,用于预处理原始数据;分发器用于将数据路由到不同管道;以及转换规则用于数据类型转换和表结构定义。支持多种输入格式和数据源(包括日志、Prometheus 指标和其他可观测性数据),提供广泛的处理能力,包括时间戳解析、正则匹配、字段提取和数据类型转换,实现可观测性数据的结构化存储和高效查询。 + + + +### PromQL (Prometheus 查询语言) +专为 Prometheus 设计的时序数据查询语言。GreptimeDB 支持 PromQL 且兼容性接近 100%,支持用户执行复杂的时序数据分析操作并使用现有的 Prometheus 仪表盘和告警规则。 + +--- + +## R + +### Read Replica (读副本) +GreptimeDB 企业版中的功能,通过创建额外的只读数据实例来提升查询性能和可扩展性。读副本将读取工作负载分布到多个实例上,减少主数据库的负载同时提供更快的查询响应。该功能支持数据访问点的地理分布,提升读取操作的高可用性,并在企业环境中实现读密集型工作负载的高效扩展。 + +### Region (区域) +GreptimeDB 架构中数据分布的基本单元。Region 包含表数据的子集,可分布在集群的不同节点上。每个 Region 管理自己的存储、索引和查询处理,实现水平扩展和容错能力。 + +### Rust +以前沿内存安全特性著称的系统级编程语言。GreptimeDB 采用 Rust 语言构建,为其高性能与高可靠性提供底层保障。 + +--- + +## S + +### Scalability (弹性扩展) +通过垂直扩展(提升单节点性能)或水平扩展(增加集群节点)应对数据量与查询负载增长的能力。GreptimeDB 的弹性扩展特性确保系统在业务增长时持续保持高性能。 + +### SQL +关系型数据库的标准查询语言。GreptimeDB 支持使用 SQL 对指标、日志及事件数据进行高效查询。 + +### Stream Processing (流式处理) +对到达的数据流进行连续实时处理的技术。在 GreptimeDB 中,流式处理通过 Flow Engine 实现,对流式时序数据执行增量计算。支持对 metrics、logs 和 events 进行即时过滤、计算和聚合,以最小延迟提供可操作的洞察。 + +--- + +## T + +### Tag (标签) +GreptimeDB 数据模型中用于唯一标识时序数据的列类型。具有相同 Tag 值的行属于同一个时间序列,使 Tag 成为组织和查询可观测性数据的关键。Tag 通常用于存储元数据,如主机名、服务名或设备 ID,并在表架构中指定为 PRIMARY KEY 列。 + +### Time Index (时间索引) +GreptimeDB 表中的特殊时间戳列,作为时序数据的主要时间维度。每个 GreptimeDB 表都需要一个 Time Index 列来按时间顺序组织数据,实现基于时间的查询,支持高效的时序操作,如降采样和时间窗口聚合。 + +### Time Series Database (时序数据库) +专为时间戳索引数据设计的数据库类型。GreptimeDB 作为云原生时序数据库,深度优化了对指标、日志及事件的分析查询性能。 + +--- + +## T + +### Trigger (触发器) +GreptimeDB 企业版中的监控和告警功能,支持对时序数据条件进行自动化评估。Trigger 在指定间隔内持续监控表中的数据,执行基于 SQL 的规则来检查预定义的阈值或条件,并在满足条件时通过 webhook 发送通知。该功能与 Alertmanager 等告警系统集成,支持自定义标签和注释,特别适用于实时系统监控、性能告警和自动化事件响应。 + +--- + +## U + +### Unified Analysis (统一分析) +在单一平台集成多源异构数据分析的能力。GreptimeDB 通过兼容 SQL 与 PromQL 实现跨数据类型(指标/日志/事件)的统一查询分析。 + +### Unified Observability (统一可观测性) +将 metrics、logs 和 traces 整合到单一系统中的数据库架构方法,消除数据孤岛并降低运维复杂性。GreptimeDB 通过将所有遥测数据类型视为带有时间戳的宽事件来实现统一可观测性,实现跨信号关联、简化数据管道和成本高效的可观测性基础设施。 + +--- + +## W + +### WAL (预写日志) +GreptimeDB 用于确保数据持久性和一致性的日志机制。WAL 在数据变更应用到主存储之前记录所有变更,在系统故障时实现数据恢复。GreptimeDB 支持灵活的 WAL 选项,包括本地磁盘存储或 Kafka 等分布式服务。 + +### Wide Events (宽事件) +可观测性 2.0 中的基础概念,将 metrics、logs 和 traces 融合为单一综合事件的上下文丰富、高维度遥测数据。宽事件捕获每次服务交互的广泛上下文信息,包括高基数字段(用户 ID、会话 ID)、业务逻辑数据、基础设施详情和请求元数据。GreptimeDB 原生支持将宽事件作为带时间戳的可观测性数据,支持复杂的多维度查询并解决系统行为分析中的 "unknown unknowns" 问题。 + +--- + +## V + +### Vector Processing (向量化处理) +GreptimeDB 查询引擎采用的高性能数据处理技术,通过批量操作数据向量(数组)来提升查询性能。支持 SIMD 指令加速,显著提升大规模时序数据的分析速度。 + +### Vehicle Data Collection (车载数据采集) +对车辆传感器读数、GPS 定位信息等数据进行采集的标准化流程,是现代车联网生态的核心组成部分。 + +### Vehicle-Cloud Integrated TSDB (车云协同时序数据库) +专为车联网设计的时序数据库系统,支持车载终端与云端系统的协同工作,实现车联网数据的高效存储与实时分析。 + +--- + +*注:本术语表将持续更新,以反映 GreptimeDB 生态的最新功能演进与技术概念扩展。* + +--- diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/gtctl.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/gtctl.md new file mode 100644 index 0000000000..5ba0e28623 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/gtctl.md @@ -0,0 +1,246 @@ +--- +keywords: [gtctl, 安装, Homebrew, 源代码构建, 自动补全, 快速入门, 部署, Kubernetes, 裸机模式] +description: 介绍 gtctl 工具的安装、使用方法,包括一键安装、通过 Homebrew 安装、从源代码构建、启用自动补全、快速入门、部署等内容。 +--- + +# gtctl + +[gtctl][1],g-t-control,是一个用于管理 GreptimeDB 集群的命令行工具。gtctl 是集成了 GreptimeDB 集群的多种操作的多合一 binary。 + +## 安装 + +### 一键安装 + +使用以下命令下载二进制文件: + +```bash +curl -fsSL https://raw.githubusercontent.com/greptimeteam/gtctl/develop/hack/install.sh | sh +``` + +下载完成后,gtctl 将位于当前目录中。 + +你还可以从 AWS 中国区 S3 存储桶安装 gtctl: + +```bash +curl -fsSL https://downloads.greptime.cn/releases/scripts/gtctl/install.sh | sh -s -- -s aws +``` + +### 通过 Homebrew 安装 + +在 macOS 上,可以通过 Homebrew 安装 gtctl: + +```bash +brew tap greptimeteam/greptime +brew install gtctl +``` + +### 从源代码构建 + +如果已经安装了 [Go][2],可以在该项目下运行 `make` 命令来构建 gtctl: + +```bash +make gtctl +``` + +构建完成后,gtctl 将生成在 `./bin/` 目录下。如果想要安装 gtctl,可以运行 `install` 命令: + +```bash +# 构建的 gtctl 将安装在 /usr/local/bin 目录下 +make install + +# 构建的 gtctl 将安装在自定义路径下 +make install INSTALL_DIR= +``` + +## 启用 gtctl 自动补全(可选) + +gtctl 支持多种不同的 shell 自动补全。 + +### Bash + +在 Bash 中,可以使用命令 `gtctl completion bash` 生成 gtctl 的自动补全脚本。将补全脚本引入到你的 shell 中可以启用 gtctl 的自动补全功能。 + +```bash +echo 'source <(gtctl completion bash)' >> ~/.bashrc +``` + +### Zsh + +在 Zsh 中,可以使用命令 `gtctl completion zsh` 生成 gtctl 的自动补全脚本。将补全脚本引入到你的 shell 中可以启用 gtctl 的自动补全功能。 + +```bash +mkdir -p $ZSH/completions && gtctl completion zsh > $ZSH/completions/_gtctl +``` + +### Fish + +在 Fish 中,可以使用命令 `gtctl completion fish` 生成 gtctl 的自动补全脚本。将补全脚本引入到你的 shell 中可以启用 gtctl 的自动补全功能。 + +```bash +gtctl completion fish | source +``` + +## 快速入门 + +体验 GreptimeDB 集群的**最快**方法是使用 playground: + +```bash +gtctl playground +``` + +`playground` 命令将在你的环境中以**裸机**模式部署最小的 GreptimeDB 集群。 + +## 部署 + +gtctl 支持两种部署模式:Kubernetes 和裸机模式(Bare-Metal)。 + +### Kubernetes + +#### 先决条件 + +* 需要 Kubernetes 版本 1.18 或更高。 + + 你可以使用 [kind][3] 创建自己的 Kubernetes 集群: + + ```bash + kind create cluster + ``` + +#### 创建 + +创建自己的 GreptimeDB 集群和 etcd 集群: + +```bash +gtctl cluster create mycluster -n default +``` + +如果你想使用存储在中国区的 artifacts(charts 和镜像),你可以启用 `--use-greptime-cn-artifacts`: + +```bash +gtctl cluster create mycluster -n default --use-greptime-cn-artifacts +``` + +创建完成后,整个 GreptimeDB 集群将在 default 命名空间中启动: + +```bash +# 获取集群。 +gtctl cluster get mycluster -n default + +# 列出所有集群。 +gtctl cluster list +``` + +所有在 [charts][4] 中提供的用于 cluster、etcd 和 operator 的值都是可配置的,你可以使用 `--set` 进行配置。gtctl 还提供了一些常用的配置选项,你可以使用 `gtctl cluster create --help` 来查看它们。 + +```bash +# 将 cluster datanode 副本数配置为 5 +gtctl cluster create mycluster --set cluster.datanode.replicas=5 + +# 两种配置 etcd 存储大小为 15Gi 的方式 +gtctl cluster create mycluster --set etcd.storage.volumeSize=15Gi +gtctl cluster create mycluster --etcd-storage-size 15Gi +``` + +#### 预运行 + +在集群创建过程中,gtctl 提供了 `--dry-run` 选项。如果用户使用 `--dry-run` 执行命令,gtctl 将输出清单的内容而不应用它们: + +```bash +gtctl cluster create mycluster -n default --dry-run +``` + +#### 连接 + +你可以使用 kubectl 的 `port-forward` 命令将前端请求转发到本地: + +```bash +kubectl port-forward svc/mycluster-frontend 4002:4002 > connections.out & +``` + +使用 gtctl 的 `connect` 命令或你的 `mysql` 客户端连接到集群: + +```bash +gtctl cluster connect mycluster -p mysql + +mysql -h 127.0.0.1 -P 4002 +``` + +#### 扩缩容(实验性) + +你可以使用以下命令来扩展(或缩小)集群的规模: + +```bash +# 将 datanode 扩展到 3 个副本。 +gtctl cluster scale -n -c datanode --replicas 3 + +# 将 frontend 扩展到 5 个副本。 +gtctl cluster scale -n -c frontend --replicas 5 +``` + +#### 删除 + +如果你想删除集群,可以执行以下操作: + +```bash +# 删除集群。 +gtctl cluster delete mycluster -n default + +# 删除集群,包括 etcd 集群。 +gtctl cluster delete mycluster -n default --tear-down-etcd +``` + +### 裸机模式(Bare-Metal) + +#### 创建 + +你可以使用以下简单命令在裸机环境中部署 GreptimeDB 集群: + +```bash +gtctl cluster create mycluster --bare-metal +``` + +它会在 `${HOME}/.gtctl` 中创建所有必要的元信息。 + +如果你想进行更多的配置,可以使用 yaml 格式的配置文件: + +```bash +gtctl cluster create mycluster --bare-metal --config +``` + +你可以参考 [`examples/bare-metal`][5] 中提供的示例配置文件 `cluster.yaml` 和 `cluster-with-local-artifacts.yaml`。 + +#### 删除 + +由于裸机模式下的集群在前台运行,任何 `SIGINT` 和 `SIGTERM` 信号都会删除集群。例如,在键盘上按下 `Ctrl+C` 后集群将被删除。 + +删除操作还会删除位于 `${HOME}/.gtctl` 中的一个集群的元信息。如果启用了 `--retain-logs`(默认启用),集群的日志将保留。 + +## 开发 + +Makefile 提供了许多有用的工具,你可以简单地运行 `make help` 来获取更多信息: + +* 编译项目 + + ```bash + make + ``` + + 然后 gtctl 会生成在 `./bin/` 目录下。 + +* 运行单元测试 + + ```bash + make test + ``` + +* 运行端到端测试 + + ```bash + make e2e + ``` + +[1]: +[2]: +[3]: +[4]: +[5]: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/http-endpoints.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/http-endpoints.md new file mode 100644 index 0000000000..27c6629061 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/http-endpoints.md @@ -0,0 +1,236 @@ +--- +keywords: [HTTP API, 管理 API, 健康检查, 状态, 指标, 配置, 仪表盘, 日志级别, 性能分析] +description: 介绍 GreptimeDB 中各种 HTTP 路径及其用法的完整列表。 +--- + +# HTTP API 端点列表 + +以下是 GreptimeDB 中各种 HTTP 路径及其用法的完整列表: + +## 管理 API + +未版本化的端点(不在 `/v1` 下)。用于健康检查、状态、指标等管理用途。 + +### 健康检查 + +- **路径**: `/health` +- **方法**: `GET`, `POST` +- **描述**: 提供一个健康检查端点以验证服务器是否正在运行。 +- **用法**: 访问此端点以检查服务器的健康状态。 + +请参考[检查 GreptimeDB 健康状态文档](/enterprise/deployments-administration/monitoring/check-db-status.md#查看-greptimedb-是否正常运行)获取示例。 + +### 状态 + +- **路径**: `/status` +- **方法**: `GET` +- **描述**: 检索服务器的当前状态。 +- **用法**: 使用此端点获取服务器状态信息。 + +请参考[检查 GreptimeDB 状态文档](/enterprise/deployments-administration/monitoring/check-db-status.md#查看-greptimedb-的部署状态)获取示例。 + +### 指标 + +- **路径**: `/metrics` +- **方法**: `GET` +- **描述**: 暴露 Prometheus 指标以进行监控。 +- **用法**: Prometheus 可以抓取此端点以收集指标数据。 + +示例如下: + +```bash +curl -X GET http://127.0.0.1:4000/metrics + +# HELP greptime_app_version app version +# TYPE greptime_app_version gauge +greptime_app_version{app="greptime-edge",short_version="main-b4bd34c5",version="0.12.0"} 1 +# HELP greptime_catalog_catalog_count catalog catalog count +# TYPE greptime_catalog_catalog_count gauge +greptime_catalog_catalog_count 1 +# HELP greptime_catalog_schema_count catalog schema count +# TYPE greptime_catalog_schema_count gauge +greptime_catalog_schema_count 3 +# HELP greptime_flow_run_interval_ms flow run interval in ms +# TYPE greptime_flow_run_interval_ms gauge +greptime_flow_run_interval_ms 1000 +# HELP greptime_meta_create_catalog meta create catalog +# TYPE greptime_meta_create_catalog histogram +greptime_meta_create_catalog_bucket{le="0.005"} 1 +greptime_meta_create_catalog_bucket{le="0.01"} 1 +greptime_meta_create_catalog_bucket{le="0.025"} 1 +greptime_meta_create_catalog_bucket{le="0.05"} 1 +greptime_meta_create_catalog_bucket{le="0.1"} 1 +... +``` + +### 配置 + +- **路径**: `/config` +- **方法**: `GET` +- **描述**: 检索服务器的配置选项。 +- **用法**: 访问此端点以获取配置详细信息。 + +示例如下: + +```shell +curl http://localhost:4000/config +``` + +输出包含 GreptimeDB 服务器的配置信息。 + +```toml +enable_telemetry = true +user_provider = "static_user_provider:file:user" +init_regions_in_background = false +init_regions_parallelism = 16 + +[http] +addr = "127.0.0.1:4000" +timeout = "30s" +body_limit = "64MiB" +is_strict_mode = false + +# ... +``` + +### 仪表盘 + +- **路径**: `/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/ingest` + - `/v1/pipelines/{pipeline_name}` + - `/v1/pipelines/dryrun` +- **方法**: + - `POST` 写入日志和添加 Pipeline。 + - `DELETE` 用于删除 Pipeline。 +- **描述**: 提供日志写入和 Pipeline 管理的端点。 +- **用法**: + - 通过 `/logs` 端点写入日志。 + - 使用 `/pipelines` 端点管理日志 Pipeline。 + +有关日志写入和 Pipeline 管理的更多信息,请参阅[日志概述](/user-guide/logs/overview.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/pipeline/built-in-pipelines.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/pipeline/built-in-pipelines.md new file mode 100644 index 0000000000..6ebf48b298 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/pipeline/built-in-pipelines.md @@ -0,0 +1,183 @@ +--- +keywords: [内置 pipeline, greptime_identity, JSON 日志, 日志处理, 时间索引, pipeline, GreptimeDB] +description: 了解 GreptimeDB 的内置 pipeline,包括用于处理 JSON 日志的 greptime_identity pipeline,具有自动 schema 创建、类型转换和时间索引配置功能。 +--- + +# 内置 Pipeline + +GreptimeDB 提供了常见日志格式的内置 Pipeline,允许你直接使用而无需创建新的 Pipeline。 + +请注意,内置 Pipeline 的名称以 "greptime_" 为前缀,不可编辑。 + +## `greptime_identity` + +`greptime_identity` Pipeline 适用于写入 JSON 日志,并自动为 JSON 日志中的每个字段创建列。嵌套的 JSON 对象将自动展开为使用点符号的单独列。 + +- 嵌套对象会被自动展开(例如,`{"a": {"b": 1}}` 变成列 `a.b`) +- 数组会被转换为 JSON 字符串 +- 如果相同字段包含不同类型的数据,则会返回错误 +- 值为 `null` 的字段将被忽略 +- 如果没有手动指定,一个作为时间索引的额外列 `greptime_timestamp` 将被添加到表中,以指示日志写入的时间 + +### 类型转换规则 + +- `string` -> `string` +- `number` -> `int64` 或 `float64` +- `boolean` -> `bool` +- `null` -> 忽略 +- `array` -> `string`(JSON 字符串格式) +- `object` -> 自动展开为单独的列(参见[展开 JSON 对象](#展开-json-对象)) + +例如,如果我们有以下 JSON 数据: + +```json +[ + {"name": "Alice", "age": 20, "is_student": true, "score": 90.5,"object": {"a":1,"b":2}}, + {"age": 21, "is_student": false, "score": 85.5, "company": "A" ,"whatever": null}, + {"name": "Charlie", "age": 22, "is_student": true, "score": 95.5,"array":[1,2,3]} +] +``` + +我们将合并每个批次的行结构以获得最终 schema。注意,嵌套对象会自动展开为单独的列(例如 `object.a`、`object.b`),数组会转换为 JSON 字符串。表 schema 如下所示: + +```sql +mysql> desc pipeline_logs; ++--------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+---------------------+------+------+---------+---------------+ +| age | Int64 | | YES | | FIELD | +| is_student | Boolean | | YES | | FIELD | +| name | String | | YES | | FIELD | +| object.a | Int64 | | YES | | FIELD | +| object.b | Int64 | | YES | | FIELD | +| score | Float64 | | YES | | FIELD | +| company | String | | YES | | FIELD | +| array | String | | YES | | FIELD | +| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | ++--------------------+---------------------+------+------+---------+---------------+ +9 rows in set (0.00 sec) +``` + +数据将存储在表中,如下所示: + +```sql +mysql> select * from pipeline_logs; ++------+------------+---------+----------+----------+-------+---------+-----------+----------------------------+ +| age | is_student | name | object.a | object.b | score | company | array | greptime_timestamp | ++------+------------+---------+----------+----------+-------+---------+-----------+----------------------------+ +| 22 | 1 | Charlie | NULL | NULL | 95.5 | NULL | [1,2,3] | 2024-10-18 09:35:48.333020 | +| 21 | 0 | NULL | NULL | NULL | 85.5 | A | NULL | 2024-10-18 09:35:48.333020 | +| 20 | 1 | Alice | 1 | 2 | 90.5 | NULL | NULL | 2024-10-18 09:35:48.333020 | ++------+------------+---------+----------+----------+-------+---------+-----------+----------------------------+ +3 rows in set (0.01 sec) +``` + +### 自定义时间索引列 + +每个 GreptimeDB 表中都必须有时间索引列。`greptime_identity` pipeline 不需要额外的 YAML 配置,如果你希望使用写入数据中自带的时间列(而不是日志数据到达服务端的时间戳)作为表的时间索引列,则需要通过参数进行指定。 + +假设这是一份待写入的日志数据: +```JSON +[ + {"action": "login", "ts": 1742814853} +] +``` + +设置如下的 URL 参数来指定自定义时间索引列: +```shell +curl -X "POST" "http://localhost:4000/v1/ingest?db=public&table=pipeline_logs&pipeline_name=greptime_identity&custom_time_index=ts;epoch;s" \ + -H "Content-Type: application/json" \ + -H "Authorization: Basic {{authentication}}" \ + -d $'[{"action": "login", "ts": 1742814853}]' +``` + +取决于数据的格式,`custom_time_index` 参数接受两种格式的配置值: +- Unix 时间戳: `<字段名>;epoch;<精度>` + - 该字段需要是整数或者字符串 + - 精度为这四种选项之一: `s`, `ms`, `us`, or `ns`. +- 时间戳字符串: `<字段名>;datestr;<字符串解析格式>` + - 例如输入的时间字段值为 `2025-03-24 19:31:37+08:00`,则对应的字符串解析格式为 `%Y-%m-%d %H:%M:%S%:z` + +通过上述配置,结果表就能正确使用输入字段作为时间索引列 +```sql +DESC pipeline_logs; +``` +```sql ++--------+-----------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------+-----------------+------+------+---------+---------------+ +| ts | TimestampSecond | PRI | NO | | TIMESTAMP | +| action | String | | YES | | FIELD | ++--------+-----------------+------+------+---------+---------------+ +2 rows in set (0.02 sec) +``` + +假设时间变量名称为 `input_ts`,以下是一些使用 `custom_time_index` 的示例: +- 1742814853: `custom_time_index=input_ts;epoch;s` +- 1752749137000: `custom_time_index=input_ts;epoch;ms` +- "2025-07-17T10:00:00+0800": `custom_time_index=input_ts;datestr;%Y-%m-%dT%H:%M:%S%z` +- "2025-06-27T15:02:23.082253908Z": `custom_time_index=input_ts;datestr;%Y-%m-%dT%H:%M:%S%.9f%#z` + + +### 展开 JSON 对象 + +`greptime_identity` pipeline **自动展开**嵌套的 JSON 对象为单层结构。此行为始终启用,使用点符号(例如 `a.b.c`)为每个嵌套字段创建单独的列。 + +#### 控制展开深度 + +你可以使用 `x-greptime-pipeline-params` header 中的 `max_nested_levels` 参数来控制对象展开的深度。默认值为 10 层。 + +以下是一个示例请求: + +```shell +curl -X "POST" "http://localhost:4000/v1/ingest?db=&table=&pipeline_name=greptime_identity&version=" \ + -H "Content-Type: application/x-ndjson" \ + -H "Authorization: Basic {{authentication}}" \ + -H "x-greptime-pipeline-params: max_nested_levels=5" \ + -d "$" +``` + +当达到最大嵌套级别时,任何剩余的嵌套结构都会被转换为 JSON 字符串并存储在单个列中。例如,当 `max_nested_levels=3` 时: + +```JSON +{ + "a": { + "b": { + "c": { + "d": [1, 2, 3] + } + } + }, + "e": [ + "foo", + "bar" + ], + "f": { + "g": { + "h": 123, + "i": "hello", + "j": { + "k": true + } + } + } +} +``` + +将被展开为: + +```json +{ + "a.b.c": "{\"d\":[1,2,3]}", + "e": "[\"foo\",\"bar\"]", + "f.g.h": 123, + "f.g.i": "hello", + "f.g.j": "{\"k\":true}" +} +``` + +注意: +- 任何级别的数组都会被转换为 JSON 字符串(例如,`"e"` 变成 `"[\"foo\",\"bar\"]"`) +- 当达到嵌套级别限制时(此例中为第 3 层),剩余的嵌套对象会被转换为 JSON 字符串(例如 `"a.b.c"` 和 `"f.g.j"`) +- 深度限制内的常规标量值以其原生类型存储(例如 `"f.g.h"` 为整数,`"f.g.i"` 为字符串) + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/pipeline/pipeline-config.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/pipeline/pipeline-config.md new file mode 100644 index 0000000000..ef9f942bb8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/pipeline/pipeline-config.md @@ -0,0 +1,1175 @@ +--- +keywords: [Pipeline 配置, Processor, Transform, 解析日志, 转换日志, YAML 配置, 数据处理, 时间字段解析, 字段拆分] +description: 介绍 GreptimeDB 中 Pipeline 的配置,包括 Processor 和 Transform 的使用方法,以及各种 Processor 的详细配置示例。 +--- + +# Pipeline 配置 + +Pipeline 是 GreptimeDB 中对 log 数据进行解析和转换的一种机制,由一个唯一的名称和一组配置规则组成,这些规则定义了如何对日志数据进行格式化、拆分和转换。目前我们支持 JSON(`application/json` 或者 `application/x-ndjson`,推荐后者)和纯文本(`text/plain`)格式的日志数据作为输入。 + +这些配置以 YAML 格式提供,使得 Pipeline 能够在日志写入过程中,根据设定的规则对数据进行处理,并将处理后的数据存储到数据库中,便于后续的结构化查询。 + +## 输入格式 + +一般情况下,Pipeline 接收一组键值对形式的 map 作为 Pipeline 的输入。如下三种格式均可作为 Pipeline 的输入: + +### JSON 格式 + +当请求的 Content-Type 为 `application/json` 时,请求的数据格式为标准的 JSON 格式。 + +```json +[ + {"message": "hello world", "time": "2024-07-12T16:18:53.048"}, + {"message": "hello greptime", "time": "2024-07-12T16:18:53.048"} +] +``` + +### NDJSON 格式 + +当请求的 Content-Type 为 `application/x-ndjson` 时,每行数据会被视为一条独立的标准 JSON 对象。 + +```json +{"message": "hello world", "time": "2024-07-12T16:18:53.048"} +{"message": "hello greptime", "time": "2024-07-12T16:18:53.048"} +``` + +### 纯文本格式 + +当请求的 Content-Type 为 `text/plain` 时,每行数据会被视为一条独立的对象。并且会将整行数据视为一个字符串,存储在一个只包含 `message` 字段的 map 对象中 + +``` +hello world 2024-07-12T16:18:53.048 +hello greptime 2024-07-12T16:18:53.048 +``` + +上述的纯文本格式数据会被转换为如下的等价形式: + +```json +{"message": "hello world 2024-07-12T16:18:53.048"} +{"message": "hello greptime 2024-07-12T16:18:53.048"} +``` + +也就是说,当输入内容为纯文本格式时,需要在编写 `Processor` 和 `Transform` 的过程中,使用 `message` 来指代每行数据的内容。 + +## 整体结构 + +Pipeline 由四部分组成:Processors、Dispatcher、Transform 和 Table suffix。 +Processors 对数据进行预处理。 +Dispatcher 可以将 pipeline 执行上下文转发到不同的后续 pipeline 上。 +Transform 决定最终保存在数据库中的数据类型和表结构。 +Table suffix 支持将数据保存到不同的表中。 + +- Version 用于指定 pipeline 配置的格式。虽然它是可选的,但是我们强烈建议使用 version 2 来编写新配置。更多详情请参考这个[章节](#版本-2-中的-transform)。 +- Processor 用于对 log 数据进行预处理,例如解析时间字段,替换字段等。 +- Dispatcher(可选) 用于将执行上下文转发到另一个 pipeline,同一个输入批次的数据可以基于特定的值被不同的 pipeline 进行处理。 +- Transform(可选) 用于对数据进行格式转换,例如将字符串类型转换为数字类型,并且指定数据库表中列的索引信息。 +- Table suffix(可选) 用于将数据存储到不同的表中,以便后续使用。 + +一个包含 Processor 和 Transform 的简单配置示例如下: + +```yaml +version: 2 +processors: + - urlencoding: + fields: + - string_field_a + - string_field_b + method: decode + ignore_missing: true +dispatcher: + field: type + rules: + - value: http + table_suffix: http + pipeline: http + - value: db + table_suffix: db +transform: + - fields: + - string_field_a + - string_field_b + type: string + # 写入的数据必须包含 timestamp 字段 + - fields: + - reqTimeSec, req_time_sec + # epoch 是特殊字段类型,必须指定精度 + type: epoch, ms + index: timestamp +table_suffix: _${string_field_a} +``` + +从 `v0.15` 开始, GreptimeDB 引入了一个新的文件格式版本。 +其主要的差别在于 Transform 的处理逻辑。 +请参考[下述章节](#版本-2-中的-transform)查看更多细节。 + +## Processor + +Processor 用于对 log 数据进行预处理,其配置位于 YAML 文件中的 `processors` 字段下。 +Pipeline 会按照多个 Processor 的顺序依次加工数据,每个 Processor 都依赖于上一个 Processor 处理的结果。 +Processor 由一个 name 和多个配置组成,不同类型的 Processor 配置有不同的字段。 + +我们目前内置了以下几种 Processor: + +- `date`: 解析格式化的时间字符串字段,例如 `2024-07-12T16:18:53.048`。 +- `epoch`: 解析数字时间戳字段,例如 `1720772378893`。 +- `decolorize`: 移除日志数据中的 ANSI 颜色代码。 +- `dissect`: 对 log 数据字段进行拆分。 +- `gsub`: 对 log 数据字段进行替换。 +- `join`: 对 log 中的 array 类型字段进行合并。 +- `letter`: 对 log 数据字段进行字母转换。 +- `regex`: 对 log 数据字段进行正则匹配。 +- `urlencoding`: 对 log 数据字段进行 URL 编解码。 +- `csv`: 对 log 数据字段进行 CSV 解析。 +- `json_path`: 从 JSON 数据中提取字段。(**已废弃**,请使用 `vrl` ) +- `json_parse`: 将一个字段解析成 JSON 对象。 +- `simple_extract`: 使用简单的 key 从 JSON 数据中提取字段。 +- `digest`: 提取日志消息模板。 +- `select`: 从 pipeline 执行上下文中保留或移除字段。 +- `vrl`: 使用 pipeline 上下文执行 [vrl](https://vector.dev/docs/reference/vrl/) 脚本。 +- `filter`: 过滤不需要写入的行数据。 + +### Processor 的输入和输出 + +大多数 Processor 接收一个 `field` 或者 `fields` 参数(一个串行处理的 `field` 列表)作为输入数据。 +Processor 会产出一个或者多个输出数据。 +对于那些只产出一个输出数据的 processor,输出的数据会替换上下文中原始 key 所关联的数据。 + +下述的示例中,在 `letter` processor 之后,一个大写版本的字符串会被保存在 `message` 字段中。 +```yaml +processors: + - letter: + fields: + - message + method: upper +``` + +我们可以将输出数据保存到另一个字段中,使得原有的字段不变。 +下述的示例中,我们依然使用 `message` 字段作为 `letter` processor 的输入,但是将输出保存到一个名为 `upper_message` 的新字段中。 +```yaml +processors: + - letter: + fields: + - key: message + rename_to: upper_message + method: upper +``` + +这个重命名的语法有一种便捷的书写方式:通过 `,` 将两个字段分割即可。 +以下是一个示例: +```yaml +processors: + - letter: + fields: + - message, upper_message + method: upper +``` + +重命名主要有两个场景: +1. 保持原字段不变,使得它可以被多个 processor 使用,或者作为原始记录被保存到数据库中。 +2. 统一命名。例如为了一致性,将驼峰命名法的变量重命名为蛇形命名法。 + +### `date` + +`date` Processor 用于解析时间字段。示例配置如下: + +```yaml +processors: + - date: + fields: + - time + formats: + - '%Y-%m-%d %H:%M:%S%.3f' + ignore_missing: true + timezone: 'Asia/Shanghai' +``` + +如上所示,`date` Processor 的配置包含以下字段: + +- `fields`: 需要解析的时间字段名列表。 +- `formats`: 时间格式化字符串,支持多个时间格式化字符串。按照提供的顺序尝试解析,直到解析成功。你可以在[这里](https://docs.rs/chrono/latest/chrono/format/strftime/index.html)找到格式化的语法说明。 +- `ignore_missing`: 忽略字段不存在的情况。默认为 `false`。如果字段不存在,并且此配置为 false,则会抛出异常。 +- `timezone`:时区。使用[tz_database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) 中的时区标识符来指定时区。默认为 `UTC`。 + +### `epoch` + +`epoch` Processor 用于解析时间戳字段,示例配置如下: + +```yaml +processors: + - epoch: + fields: + - reqTimeSec + resolution: millisecond + ignore_missing: true +``` + +如上所示,`epoch` Processor 的配置包含以下字段: + +- `fields`: 需要解析的时间戳字段名列表。 +- `resolution`: 时间戳精度,支持 `s`, `sec` , `second` , `ms`, `millisecond`, `milli`, `us`, `microsecond`, `micro`, `ns`, `nanosecond`, `nano`。默认为 `ms`。 +- `ignore_missing`: 忽略字段不存在的情况。默认为 `false`。如果字段不存在,并且此配置为 false,则会抛出异常。 + +### `decolorize` + +`decolorize` Processor 用于移除日志数据中的 ANSI 颜色代码。示例配置如下: + +```yaml +processors: + - decolorize: + fields: + - message +``` + +如上所示,`decolorize` Processor 的配置包含以下字段: + +- `fields`: 需要移除颜色代码的字段名列表。 + +### `dissect` + +`dissect` Processor 用于对 log 数据字段进行拆分,示例配置如下: + +```yaml +processors: + - dissect: + fields: + - message + patterns: + - '%{key1} %{key2}' + ignore_missing: true + append_separator: '-' +``` + +如上所示,`dissect` Processor 的配置包含以下字段: + +- `fields`: 需要拆分的字段名列表。不支持字段重命名。 +- `patterns`: 拆分的 dissect 模式。 +- `ignore_missing`: 忽略字段不存在的情况。默认为 `false`。如果字段不存在,并且此配置为 false,则会抛出异常。 +- `append_separator`: 对于多个追加到一起的字段,指定连接符。默认是一个空字符串。 + +#### Dissect 模式 + +和 Logstash 的 Dissect 模式类似,Dissect 模式由 `%{key}` 组成,其中 `%{key}` 为一个字段名。例如: + +``` +"%{key1} %{key2} %{+key3} %{+key4/2} %{key5->} %{?key6}" +``` + +#### Dissect 修饰符 + +Dissect 模式支持以下修饰符: + +| 修饰符 | 说明 | 示例 | +| ----------- | ---------------------------------------- | --------------------- | +| `+` | 将两个或多个字段追加到一起 | `%{+key} %{+key}` | +| `+` 和 `/n` | 按照指定的顺序将两个或多个字段追加到一起 | `%{+key/2} %{+key/1}` | +| `->` | 忽略右侧的任何重复字符 | `%{key1->} %{key2->}` | +| `?` | 忽略匹配的值 | `%{?key}` | + +#### `dissect` 示例 + +例如,对于以下 log 数据: + +``` +"key1 key2 key3 key4 key5 key6" +``` + +使用以下 Dissect 模式: + +``` +"%{key1} %{key2} %{+key3} %{+key3/2} %{key5->} %{?key6}" +``` + +将得到以下结果: + +``` +{ + "key1": "key1", + "key2": "key2", + "key3": "key3 key4", + "key5": "key5" +} +``` + +### `gsub` + +`gsub` Processor 用于对 log 数据字段进行替换,示例配置如下: + +```yaml +processors: + - gsub: + fields: + - message + pattern: 'old' + replacement: 'new' + ignore_missing: true +``` + +如上所示,`gsub` Processor 的配置包含以下字段: + +- `fields`: 需要替换的字段名列表。 +- `pattern`: 需要替换的字符串。支持正则表达式。 +- `replacement`: 替换后的字符串。 +- `ignore_missing`: 忽略字段不存在的情况。默认为 `false`。如果字段不存在,并且此配置为 false,则会抛出异常。 + +### `join` + +`join` Processor 用于对 log 中的 Array 类型字段进行合并,示例配置如下: + +```yaml +processors: + - join: + fields: + - message + separator: ',' + ignore_missing: true +``` + +如上所示,`join` Processor 的配置包含以下字段: + +- `fields`: 需要合并的字段名列表。注意,这里每行字段的值需要是 Array 类型,每行字段会单独合并自己数组内的值,所有行的字段不会合并到一起。 +- `separator`: 合并后的分隔符。 +- `ignore_missing`: 忽略字段不存在的情况。默认为 `false`。如果字段不存在,并且此配置为 false,则会抛出异常。 + +#### `join` 示例 + +例如,对于以下 log 数据: + +```json +{ + "message": ["a", "b", "c"] +} +``` + +使用以下配置: + +```yaml +processors: + - join: + fields: + - message + separator: ',' +``` + +将得到以下结果: + +```json +{ + "message": "a,b,c" +} +``` + +### `letter` + +`letter` Processor 用于对 log 数据字段进行字母转换,示例配置如下: + +```yaml +processors: + - letter: + fields: + - message + method: upper + ignore_missing: true +``` + +如上所示,`letter` Processor 的配置包含以下字段: + +- `fields`: 需要转换的字段名列表。 +- `method`: 转换方法,支持 `upper`, `lower` ,`capital`。默认为 `lower`。注意 `capital` 只会将第一个字母转换为大写。 +- `ignore_missing`: 忽略字段不存在的情况。默认为 `false`。如果字段不存在,并且此配置为 false,则会抛出异常。 + +### `regex` + +`regex` Processor 用于对 log 数据字段进行正则匹配,示例配置如下: + +```yaml +processors: + - regex: + fields: + - message + patterns: + - ':(?[0-9])' + ignore_missing: true +``` + +如上所示,`regex` Processor 的配置包含以下字段: + +- `fields`: 需要匹配的字段名列表。如果重命名了字段,重命名后的字段名将与 `pattern` 中的命名捕获组名进行拼接。 +- `pattern`: 要进行匹配的正则表达式,需要使用命名捕获组才可以从对应字段中取出对应数据。 +- `ignore_missing`: 忽略字段不存在的情况。默认为 `false`。如果字段不存在,并且此配置为 false,则会抛出异常。 + +#### regex 命名捕获组的规则 + +`regex` Processor 支持使用 `(?...)` 的语法来命名捕获组,最终将数据处理为这种形式: + +```json +{ + "_": "" +} +``` + +例如 `regex` Processor 中 field 填写的字段名为 `message`,对应的内容为 `"[ERROR] error message"`, +你可以将 pattern 设置为 `\[(?[A-Z]+)\] (?.+)`, +最终数据会被处理为: +```json +{ + "message_level": "ERROR", + "message_content": "error message" +} +``` + +### `urlencoding` + +`urlencoding` Processor 用于对 log 数据字段进行 URL 编码,示例配置如下: + +```yaml +processors: + - urlencoding: + fields: + - string_field_a + - string_field_b + method: decode + ignore_missing: true +``` + +如上所示,`urlencoding` Processor 的配置包含以下字段: + +- `fields`: 需要编码的字段名列表。 +- `method`: 编码方法,支持 `encode`, `decode`。默认为 `encode`。 +- `ignore_missing`: 忽略字段不存在的情况。默认为 `false`。如果字段不存在,并且此配置为 false,则会抛出异常。 + +### `csv` + +`csv` Processor 用于对 log 数据中没有携带 header 的 CSV 类型字段解析,示例配置如下: + +```yaml +processors: + - csv: + fields: + - message + separator: ',' + quote: '"' + trim: true + ignore_missing: true +``` + +如上所示,`csv` Processor 的配置包含以下字段: + +- `fields`: 需要解析的字段名列表。 +- `separator`: 分隔符。 +- `quote`: 引号。 +- `trim`: 是否去除空格。默认为 `false`。 +- `ignore_missing`: 忽略字段不存在的情况。默认为 `false`。如果字段不存在,并且此配置为 false,则会抛出异常。 + +### `json_path`(废弃) + +:::danger 废弃特性 +增加 vrl processor 后,`json_path` 处理器的使用场景已经大大减少。 +如果你需要从 JSON 数据中提取字段,建议使用 `vrl` 处理器来实现更灵活的处理。 +我们计划在未来的版本中废弃 `json_path` 处理器。 +::: + +`json_path` 处理器用于从 JSON 数据中提取字段。以下是一个配置示例: + +```yaml +processors: + - json_path: + fields: + - complex_object + json_path: "$.shop.orders[?(@.active)].id" + ignore_missing: true + result_index: 1 +``` + +在上述示例中,`json_path` processor 的配置包括以下字段: + +- `fields`:要提取的字段名称列表。 +- `json_path`:要提取的 JSON 路径。 +- `ignore_missing`:忽略字段缺失的情况。默认为 `false`。如果字段缺失且此配置设置为 `false`,将抛出异常。 +- `result_index`:指定提取数组中要用作结果值的下标。默认情况下,包含所有值。Processor 提取的结果值是包含 path 中所有值的数组。如果指定了索引,将使用提取数组中对应的下标的值作为最终结果。 + +#### JSON 路径语法 + +JSON 路径语法基于 [jsonpath-rust](https://github.com/besok/jsonpath-rust) 库。 + +在此阶段,我们仅推荐使用一些简单的字段提取操作,以便将嵌套字段提取到顶层。 + +#### `json_path` 示例 + +例如,给定以下日志数据: + +```json +{ + "product_object": { + "hello": "world" + }, + "product_array": [ + "hello", + "world" + ], + "complex_object": { + "shop": { + "orders": [ + { + "id": 1, + "active": true + }, + { + "id": 2 + }, + { + "id": 3 + }, + { + "id": 4, + "active": true + } + ] + } + } +} +``` + +使用以下配置: + +```yaml +processors: + - json_path: + fields: + - product_object, object_target + json_path: "$.hello" + result_index: 0 + - json_path: + fields: + - product_array, array_target + json_path: "$.[1]" + result_index: 0 + - json_path: + fields: + - complex_object, complex_target_1 + json_path: "$.shop.orders[?(@.active)].id" + - json_path: + fields: + - complex_target_1, complex_target_2 + json_path: "$.[1]" + result_index: 0 + - json_path: + fields: + - complex_object, complex_target_3 + json_path: "$.shop.orders[?(@.active)].id" + result_index: 1 +transform: + - fields: + - object_target + - array_target + type: string + - fields: + - complex_target_3 + - complex_target_2 + type: uint32 + - fields: + - complex_target_1 + type: json +``` + +结果将是: + +```json +{ + "object_target": "world", + "array_target": "world", + "complex_target_3": 4, + "complex_target_2": 4, + "complex_target_1": [1, 4] +} +``` + +### `json_parse` + +`json_parse`,如其名字所示,将一个字符串解析成一个 JSON 对象。以下是一份示例配置: + +```yaml +processors: + - json_parse: + fields: + - complex_object, target_field + ignore_missing: true +``` + +在上述示例中,`json_parse` 处理器的配置包含以下字段: + +- `fields`:对于每个字段,第一个 key 表示输入字符串中的 key,第二个 key 表示输出的 key 名称。如果不填写第二个 key,则默认使用第一个 key 名作为输出名,也就是替换第一个 key 中的值。上面的示例表示解析 `complex_object` 并将输出放入 `target_field` 中。 +- `ignore_missing`:忽略字段不存在的情况。默认为 `false`。如果字段不存在且此配置为 `false`,将抛出异常。 + +#### `json_parse` example + +例如,给定以下日志数据: + +```json +{ + "product_object": "{\"hello\":\"world\"}", +} +``` + +使用以下配置: + +```yaml +processors: + - json_parse: + fields: + - product_object +``` + +结果将是: + +```json +{ + "product_object": { + "hello": "world" + } +} +``` + +### `simple_extract` + +虽然 `json_path` 处理器能够使用复杂表达式从 JSON 对象中提取字段,但它相对较慢且成本较高。`simple_extract` 处理器提供了一种简单的方法,仅使用键名来提取字段。以下是示例配置: + +```yaml +processors: + - simple_extract: + fields: + - complex_object, target_field + key: "shop.name" + ignore_missing: true +``` + +在上述示例中,`simple_extract` 处理器的配置包含以下字段: + +- `fields`:对于每个字段,第一个键表示上下文中的输入 JSON 对象,第二个键表示输出键名。上面的示例表示从 `complex_object` 中提取数据并将输出放入 `target_field` 中。 +- `key`:提取键,使用 `x.x` 格式,每个 `.` 表示一个新的嵌套层。 +- `ignore_missing`:忽略字段不存在的情况。默认为 `false`。如果字段不存在且此配置为 `false`,将抛出异常。 + +#### `simple_extract` 示例 + +例如,给定以下日志数据: + +```json +{ + "product_object": { + "hello": "world" + }, + "product_array": [ + "hello", + "world" + ], + "complex_object": { + "shop": { + "name": "some_shop_name" + } + } +} +``` + +使用以下配置: + +```yaml +processors: + - simple_extract: + fields: + - complex_object, shop_name + key: "shop.name" +transform: + - fields: + - shop_name + type: string +``` + +结果将是: + +```json +{ + "shop_name": "some_shop_name" +} +``` + +### `digest` + +`digest` 处理器用于从日志内容中提取日志模板,它通过识别并移除可变内容(如数字、UUID、IP 地址、引号中的内容和括号中的文本等)来实现。提取出的模板可用于日志的分类和分析。配置示例如下: + +```yaml +processors: + - digest: + fields: + - message + presets: + - numbers + - uuid + - ip + - quoted + - bracketed + regex: + - "foobar" + ignore_missing: true +``` + +在上述示例中,`digest` 处理器的配置包含以下字段: + +- `fields`:要进行摘要处理的字段名列表。处理后的结果将存储在带有 `_digest` 后缀的新字段中。 +- `presets`:要移除的预设模式列表。支持以下模式: + - `numbers`:匹配数字序列 + - `uuid`:匹配 UUID 字符串,如 `123e4567-e89b-12d3-a456-426614174000` + - `ip`:匹配 IPv4/IPv6 地址(可选带端口号) + - `quoted`:匹配单引号/双引号内的文本(包括各种 Unicode 引号) + - `bracketed`:匹配各种类型括号内的文本(包括各种 Unicode 括号) +- `regex`:要移除的自定义正则表达式列表 +- `ignore_missing`:是否忽略字段不存在的情况。默认为 `false`。如果字段不存在且此配置为 `false`,将抛出异常。 + +#### `digest` 示例 + +例如,给定以下日志数据: + +```json +{ + "message": "User 'john.doe' from [192.168.1.1] accessed resource 12345 with UUID 123e4567-e89b-12d3-a456-426614174000" +} +``` + +使用以下配置: + +```yaml +processors: + - digest: + fields: + - message + presets: + - numbers + - uuid + - ip + - quoted + - bracketed +``` + +结果将是: + +```json +{ + "message": "User 'john.doe' from [192.168.1.1] accessed resource 12345 with UUID 123e4567-e89b-12d3-a456-426614174000", + "message_digest": "User from accessed resource with UUID " +} +``` + +提取的模板可用于对相似的日志消息进行分组或分析日志模式,即使可变内容不同。例如,以下所有日志消息都会生成相同的模板: + +- `User 'alice' from [10.0.0.1] accessed resource 54321 with UUID 987fbc97-4bed-5078-9141-2791ba07c9f3` +- `User 'bob' from [2001:0db8::1] accessed resource 98765 with UUID 550e8400-e29b-41d4-a716-446655440000` + +### `select` + +`select` 处理器用于从 pipeline 执行上下文中保留或者移除字段。 + +从 `v0.15` 开始,我们引入了[`自动 transform`](#自动-transform)用来简化配置。 +`自动 transform`会尝试将 pipeline 执行上下文中所有的字段都保存下来。 +`select` 处理器在这里能选择上下文中的字段并保留或者移除,在`自动 transform`模式下即反映了最终的表结构。 + +`select` 处理器的选项非常简单: +- `type` (可选) + - `include` (默认): 只保留选中的字段列表 + - `exclude`: 从当前的上下文中移除选中的字段列表 +- `fields`: 选择的字段列表 + +以下是一个简单的示例: +```YAML +processors: + - dissect: + fields: + - message + patterns: + - "%{+ts} %{+ts} %{http_status_code} %{content}" + - date: + fields: + - ts + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + - select: + fields: + - http_status_code + - ts +``` + +通过 `dissect` 和 `date` 处理器之后,现在上下文中有四个字段: `ts`,`http_status_code`,`content` 和最初的 `message`。 +在没有 `select` 处理器的情况下,四个字段都会被保存下来。 +`select` 处理器在这里选择了 `http_status_code` 和 `ts` 两个字段来保存(默认 `include` 行为),等效于从 pipeline 执行上下文中删除了 `content` 和 `message` 字段,使得最终只有 `http_status_code` 和 `ts` 这两个字段被保存到数据库中。 + +上述的示例也可以用以下 `select` 处理器配置来达成效果: +```YAML + - select: + type: exclude + fields: + - content + - message +``` + +### `vrl` + +:::warning 实验性特性 +此实验性功能可能存在预期外的行为,其功能未来可能发生变化。 +::: + +`vrl` 处理器使用 pipeline 上下文作为环境来运行 vrl 编程脚本。 +相比于简单的处理器,它功能更加强大,允许你编写编程代码来此操作上下文中的变量;不过执行 vrl 脚本会消耗更多的资源。 +更多的 vrl 语言介绍和使用,请参考[官方网站](https://vector.dev/docs/reference/vrl/)。 + +`vrl` 处理器目前只有一个配置项,就是 `source`(源码)。以下是一个示例: +```YAML +processors: + - date: + field: time + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + ignore_missing: true + - vrl: + source: | + .from_source = "channel_2" + cond, err = .id1 > .id2 + if (cond) { + .from_source = "channel_1" + } + del(.id1) + del(.id2) + . +``` + +这份配置使用 `|` 在 YAML 中开启一个多行的文本。随后即可编写整个脚本。 + +在使用 `vrl` 处理器时,有一些需要注意的点: +1. 整个脚本必须以一个单独的 `.` 行作为结尾,表示将整个上下文作为脚本的返回值。 +2. vrl 脚本的返回值中不能包含任何的 `regex` 类型的变量。在脚本的过程中可以使用这种类型,但是在返回之前需要 `del`(删除) 掉。 +3. 由于 pipeline 的类型和 vrl 的类型之前存在转换,经过 vrl 处理的类型会变成最大的容量类型,即 `i64`, `u64` 和 `Timestamp::nanoseconds`。 + +### `filter` + +`filter` 处理器用于根据指定条件筛选数据行,从而移除不需要的数据。 + +以下是一个简单的 `filter` 处理器配置: +```YAML +processors: + - date: + field: time + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + - filter: + field: name + mode: simple + match_op: in + case_insensitive: true + targets: + - John + - Wick +transform: + - field: name + type: string + - field: time + type: time + index: timestamp +``` +`filter` 处理器在这里会检查 pipeline 上下文中的 `name` 变量的值。 +如果它的值和 targets 列表 `['John', 'Wick']` 中的任意值匹配,则认为条件判断成功。 +这条输入数据的处理将会被中止,不会被持久化到数据库中。 + +`filter` 处理器接受以下参数: +1. `field`(或者 `fields`):用于比较的上下文变量,可以是一个或者多个;任意一个满足条件即会触发过滤。 +2. `mode`(可选):默认为 `simple`,即为简单字符串匹配。这个字段是为了将来对 `filter` 处理器的功能进行扩展。 +3. `match_op`(可选):如果 mode 是 `simple`,这个选项可以设置为 `in` 或者 `not_in`,意为检查目标列表是否包含变量。默认为 `in`。 +4. `case_insensitive`(可选):默认为 `true`. +5. `targets`: 用于比较的目标列表。 + +## Transform + +Transform 用于对 log 数据进行转换,并且指定在数据库表中列的索引信息。其配置位于 YAML 文件中的 `transform` 字段下。 + +从 `v0.15` 开始,GreptimeDB 引入了版本 2 格式和自动 transform,可以大幅简化配置。具体详情见下。 + +Transform 由一个或多个配置组成,每个配置包含以下字段: + +- `fields`: 需要转换的字段名列表 +- `type`: 指定在数据库中的数据类型 +- `index`(可选): 索引类型 +- `tag`(可选): 设置列为 tag +- `on_failure`(可选): 转换失败时的处理方式 +- `default`(可选): 默认值 + +### 版本 2 中的 Transform + +在最初的 pipeline 版本中,你需要在 transform 中手动指定所有的字段,来将它们持久化到数据库中。 +如果一个字段没有在 transform 中被指定,那么它将会被丢弃。 +当字段的数量不断增加时,配置将会变得繁琐、容易出错。 + +从 `v0.15` 开始,GreptimeDB 引入了一种新的 transform 模式,使得编写 pipeline 配置变得更加简单。 +你只需要在 transform 指定需要设置索引和数据类型转换的字段即可;其他 pipeline 上下文中的字段将会被 pipeline 引擎自动转换并保存。 +配合 `select` 处理器,我们可以决定什么字段会被最终保留在数据库中。 + +但是这无法兼容已经存在的 pipeline 配置文件。 +如果你已经在 pipeline 配置中使用了 `dissect` 或者 `regex` 处理器,那么在升级数据库版本后,原始的日志文本,因为还留存于 pipeline 上下文中,会被立刻写入到数据库中。 + +因此,GreptimeDB pipeline 引入了 `version` 字段来执行要使用的 transform 版本,就像 Docker Compose 文件的版本号字段一样。 +以下是一个示例: +```YAML +version: 2 +processors: + - date: + field: input_str + formats: + - "%Y-%m-%dT%H:%M:%S%.3fZ" + +transform: + - field: input_str, ts + type: time, ms + index: timestamp +``` + +只需要在配置文件的开头加上 `version: 2`,pipeline 引擎就会以新的 transform 模式来处理数据: +1. 顺序执行所有配置的 transform 规则。 +2. 将 pipeline 上下文中的所有字段保存到最终的结果表中 + +注意: +- Transform 规则**必须设置一个时间索引列**。 +- 版本 2 中的 transform 规则执行会将原始字段从 pipeline 上下文中移除,故你无法在 transform 规则对同一个字段引用多次 + +### 自动 transform + +在版本 2 中 transform 的配置编写已经进行了大幅的简化。 +即使如此,在某些场景下,我们仍然希望能够结合处理器的处理能力与 `greptime_identity` 的自动字段保存能力,从而无需编写任何转换代码,即可让 pipeline 引擎自动推导并保存字段。 + +现在自定义 pipeline 支持了这点。 +如果 pipeline 配置中没有 transform 模块,pipeline 引擎将会尝试为上下文中的变量自动推导数据类型,并将它们持久化到数据库中,就像 `greptime_identity` 一样。 + +当在 GreptimeDB 中创建表时,必须指定一个时间索引列。在这个场景中,pipeline 引擎会尝试从上下文中寻找一个 `timestamp` +类型的字段,并将其设置成时间索引列。`timestamp` 类型的字段是 `date` 或者 `epoch` processor 的产物。所以在 processors 声明中,必须存在一个 +`date` 或者 `epoch` processor。同时,只允许存在一个 `timestamp` 类型的字段,多个 `timestamp` 字段的情况下会因无法判断在哪一列上设置时间索引而报错。 + +例如,以下 pipeline 配置现在是有效的。 +```YAML +version: 2 +processors: + - dissect: + fields: + - message + patterns: + - '%{ip_address} - %{username} [%{timestamp}] "%{http_method} %{request_line} %{protocol}" %{status_code} %{response_size}' + ignore_missing: true + - date: + fields: + - timestamp + formats: + - "%d/%b/%Y:%H:%M:%S %z" +``` + +其产生的表结构如下: +``` +mysql> desc auto_trans; ++---------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++---------------+---------------------+------+------+---------+---------------+ +| timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| host | String | | YES | | FIELD | +| http_method | String | | YES | | FIELD | +| ip_address | String | | YES | | FIELD | +| message | String | | YES | | FIELD | +| protocol | String | | YES | | FIELD | +| request_line | String | | YES | | FIELD | +| response_size | String | | YES | | FIELD | +| service | String | | YES | | FIELD | +| source_type | String | | YES | | FIELD | +| status_code | String | | YES | | FIELD | +| username | String | | YES | | FIELD | ++---------------+---------------------+------+------+---------+---------------+ +12 rows in set (0.03 sec) +``` + +可以看到所有的字段都被保存下来了,包括原始的 `message` 字段。注意所有的字段都被保存成 `String` 类型,`timestamp` 字段自动被设置成时间索引列。 + +### `fields` 字段 + +每个字段名都是一个字符串。 +在 transform 中 `fields` 也可以使用重命名,语法参考[这里](#processor-的输入和输出)。 +字段的最终命名会被作为数据库表中的列的名字。 + +### `type` 字段 + +GreptimeDB 目前内置了以下几种转换类型: + +- `int8`, `int16`, `int32`, `int64`: 整数类型。 +- `uint8`, `uint16`, `uint32`, `uint64`: 无符号整数类型。 +- `float32`, `float64`: 浮点数类型。 +- `string`: 字符串类型。 +- `time`: 时间类型。将被转换为 GreptimeDB `timestamp(9)` 类型。 +- `epoch`: 时间戳类型。将被转换为 GreptimeDB `timestamp(n)` 类型。n 为时间戳精度,n 的值视 epoch 精度而定。当精度为 `s` 时,n 为 0;当精度为 `ms` 时,n 为 3;当精度为 `us` 时,n 为 6;当精度为 `ns` 时,n 为 9。 + +如果字段在转换过程中获得了非法值,Pipeline 将会抛出异常。例如将一个字符串 `abc` 转换为整数时,由于该字符串不是一个合法的整数,Pipeline 将会抛出异常。 + +### `index` 字段 + +`Pipeline` 会将处理后的数据写入到 GreptimeDB 自动创建的数据表中。为了提高查询效率,GreptimeDB 会为表中的某些列创建索引。`index` 字段用于指定哪些字段需要被索引。关于 GreptimeDB 的索引类型,请参考[数据索引](/user-guide/manage-data/data-index.md)文档。 + +GreptimeDB 支持以下四种字段的索引类型: + +- `timestamp`: 用于指定某列是时间索引列 +- `inverted`: 用于指定某列使用 inverted 类型的索引(倒排索引) +- `fulltext`: 用于指定某列使用 fulltext 类型的索引(全文索引),该列需要是字符串类型 +- `skipping`: 用于指定某列使用 skipping 类型的索引(跳数索引),该列需要是字符串类型 + + +不提供 `index` 字段时,GreptimeDB 将不会在该字段上建立索引。 + +在 GreptimeDB 中,一张表里必须包含一个 `timestamp` 类型的列作为该表的时间索引列,因此一个 Pipeline 有且只有一个时间索引列。 + +#### 时间戳列 + +通过 `index: timestamp` 指定哪个字段是时间索引列,写法请参考下方的 [Transform 示例](#transform-示例)。 + +#### Inverted 索引 + +通过 `index: inverted` 指定在哪个列上建立倒排索引,写法请参考下方的 [Transform 示例](#transform-示例)。 + +#### Fulltext 索引 + +通过 `index: fulltext` 指定在哪个列上建立全文索引,该索引可大大提升 [日志搜索](/user-guide/logs/fulltext-search.md) 的性能,写法请参考下方的 [Transform 示例](#transform-示例)。 + +#### Skipping 索引 + +通过 `index: skipping` 指定在哪个列上建立跳数索引,该索引只需少量存储空间的索引文件即可以加速在高基数列上的查询,写法请参考下方的 [Transform 示例](#transform-示例)。 + +### `tag` 字段 + +`Pipeline` 支持手动指定 tag 列。关于 tag 列的更多信息,请参考[数据模型](/user-guide/concepts/data-model.md)文档。写法请参考下方的 [Transform 示例](#transform-示例)。 + +### `on_failure` 字段 + +`on_failure` 字段用于指定转换失败时的处理方式,支持以下几种方式: + +- `ignore`: 忽略转换失败的字段,不写入数据库。 +- `default`: 写入默认值。默认值由 `default` 字段指定。 + +### `default` 字段 + +`default` 字段用于指定转换失败时的默认值。 + +### Transform 示例 + +例如,对于以下 log 数据: + +```json +{ + "num_field_a": "3", + "string_field_a": "john", + "string_field_b": "It was snowing when he was born.", + "time_field_a": 1625760000 +} +``` + +使用以下配置: + +```yaml +transform: + - fields: + - string_field_a, name + type: string + index: skipping + tag: true + - fields: + - num_field_a, age + type: int32 + index: inverted + - fields: + - string_field_b, description + type: string + index: fulltext + - fields: + - time_field_a, born_time + type: epoch, s + index: timestamp +``` + +将得到以下结果: + +``` +{ + "name": "john", + "age": 3, + "description": "It was snowing when he was born.", + "born_time": 2021-07-08 16:00:00 +} +``` + +## Dispatcher + +Dispatcher 允许用户将数据路由到其他 Pipeline 上。这是为了应对当多种日志类型共享 +单一来源且需要存储在不同结构的单独表中。 + +配置例子如下: + +```yaml +dispatcher: + field: type + rules: + - value: http + table_suffix: http + pipeline: http + - value: db + table_suffix: db + +``` + +Dispatcher 在 processor 之后执行。当匹配到相应的规则时,下一个 pipeline 将被执行。 + +你可以指定路由数据所依据的字段名 `field`,并指定路由规则 `rules`。假如 `field` +字段匹配到规则中的 `value`,数据将被路由到 `pipeline`。如果规则中没有指定 +`pipeline`,将会根据当前的数据结构推断表结构。在上面的例子里,如果用户输入的数据 +中 `type` 字段的值为 `http`,我们将把数据路由给名为 `http` 的 pipeline 执行。如 +果 `type` 字段的值为 `db`,我们将用当前数据的结构作为表结构存储。 + +写入的目标表名由 `table_suffix` 指定,这个后缀将和请求输入的 `table` 参数及下划 +线组合形成最终的表名。例如,请求的表名叫做 `applogs`,当匹配到上面例子中的 +`http` 规则时,最终的表名叫做 `applogs_http`。 + +如果没有规则匹配到,数据将执行当前 pipeline 中定一个 transform 规则。 + +## Table suffix + +:::warning 实验性特性 +此实验性功能可能存在预期外的行为,其功能未来可能发生变化。 +::: + +在一些场景下,你可能需要将写入的日志数据基于输入的字段值保存到不同表上。 +比如你可能希望按照产生的应用名将日志保存到不同的表上,在表名上添加这个应用名的后缀。 + +一个配置示例如下: +```yaml +table_suffix: _${app_name} +``` + +语法非常简单: 使用 `${}` 来引用 pipeline 执行上下文中的变量。 +该变量可以是输入数据中直接存在的,也可以是前序处理流程中产生的。 +变量替换完成之后,整个字符串会被添加到输入的表名后。 + +注意: +1. 引用的变量必须是一个整数或者字符串类型的数据 +2. 如果在执行过程中遇到任何错误(例如变量不存在或者无效数据类型),输入的表名会被作为最终表名 + +下面举一个例子。以下是输入数据: +```JSON +[ + {"type": "db"}, + {"type": "http"}, + {"t": "test"} +] +``` + +输入的表名为 `persist_app`,pipeline 配置如下: +```YAML +table_suffix: _${type} +``` + +这三行输入数据会被写入到三张不同的表中: +1. `persist_app_db` +2. `persist_app_http` +3. `persist_app`, 因为输入的数据中并没有 `type` 字段,所以使用了默认的表名 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/pipeline/write-log-api.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/pipeline/write-log-api.md new file mode 100644 index 0000000000..0c23d9d4d1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/pipeline/write-log-api.md @@ -0,0 +1,161 @@ +--- +keywords: [日志写入, HTTP 接口, Pipeline 配置, 数据格式, 请求参数] +description: 介绍如何通过 HTTP 接口使用指定的 Pipeline 将日志写入 GreptimeDB,包括请求参数、数据格式和示例。 +--- + +# 写入日志的 API + +在写入日志之前,请先阅读 [Pipeline 配置](/user-guide/logs/use-custom-pipelines.md#上传-pipeline)完成配置的设定和上传。 + +## HTTP API + +你可以使用以下命令通过 HTTP 接口写入日志: + +```shell +curl -X "POST" "http://localhost:4000/v1/ingest?db=&table=&pipeline_name=&version=&skip_error=" \ + -H "Content-Type: application/x-ndjson" \ + -H "Authorization: Basic {{authentication}}" \ + -d "$" +``` + + +### 请求参数 + +此接口接受以下参数: + +- `db`:数据库名称。 +- `table`:表名称。 +- `pipeline_name`:[Pipeline](./pipeline-config.md) 名称。 +- `version`:Pipeline 版本号。可选,默认使用最新版本。 +- `skip_error`:写入日志时是否跳过错误。可选,默认为 `false`。当设置为 `true` 时,GreptimeDB 会跳过遇到错误的单条日志项并继续处理剩余的日志,不会因为一条日志项的错误导致整个请求失败。 + +### `Content-Type` 和 Body 数据格式 + +GreptimeDB 使用 `Content-Type` header 来决定如何解码请求体内容。目前我们支持以下两种格式: +- `application/json`: 包括普通的 JSON 格式和 NDJSON 格式。 +- `application/x-ndjson`: 指定 NDJSON 格式,会尝试先分割行再进行解析,可以达到精确的错误检查。 +- `text/plain`: 通过换行符分割的多行日志文本行。 + +#### `application/json` 和 `application/x-ndjson` 格式 + +以下是一份 JSON 格式请求体内容的示例: + +```JSON +[ + {"message":"127.0.0.1 - - [25/May/2024:20:16:37 +0000] \"GET /index.html HTTP/1.1\" 200 612 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\""}, + {"message":"192.168.1.1 - - [25/May/2024:20:17:37 +0000] \"POST /api/login HTTP/1.1\" 200 1784 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36\""}, + {"message":"10.0.0.1 - - [25/May/2024:20:18:37 +0000] \"GET /images/logo.png HTTP/1.1\" 304 0 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0\""}, + {"message":"172.16.0.1 - - [25/May/2024:20:19:37 +0000] \"GET /contact HTTP/1.1\" 404 162 \"-\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1\""} +] +``` + +请注意整个 JSON 是一个数组(包含多行日志)。每个 JSON 对象代表即将要被 Pipeline 引擎处理的一行日志。 + +JSON 对象中的 key 名,也就是这里的 `message`,会被用作 Pipeline processor 处理时的 field 名称。比如: + +```yaml +processors: + - dissect: + fields: + # `message` 是 JSON 对象中的 key 名 + - message + patterns: + - '%{ip_address} - - [%{timestamp}] "%{http_method} %{request_line}" %{status_code} %{response_size} "-" "%{user_agent}"' + ignore_missing: true + +# pipeline 文件的剩余部分在这里省略 +``` + +我们也可以将这个请求体内容改写成 NDJSON 的格式,如下所示: + +```JSON +{"message":"127.0.0.1 - - [25/May/2024:20:16:37 +0000] \"GET /index.html HTTP/1.1\" 200 612 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\""} +{"message":"192.168.1.1 - - [25/May/2024:20:17:37 +0000] \"POST /api/login HTTP/1.1\" 200 1784 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36\""} +{"message":"10.0.0.1 - - [25/May/2024:20:18:37 +0000] \"GET /images/logo.png HTTP/1.1\" 304 0 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0\""} +{"message":"172.16.0.1 - - [25/May/2024:20:19:37 +0000] \"GET /contact HTTP/1.1\" 404 162 \"-\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1\""} +``` + +注意到最外层的数组符被消去了,现在每个 JSON 对象通过换行符分割而不是 `,`。 + +#### `text/plain` 格式 + +纯文本日志在整个生态系统中被广泛应用。GreptimeDB 同样支持日志数据以 `text/plain` 格式进行输入,使得我们可以直接从日志产生源进行写入。 + +以下是一份和上述样例请求体内容等价的文本请求示例: + +```plain +127.0.0.1 - - [25/May/2024:20:16:37 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" +192.168.1.1 - - [25/May/2024:20:17:37 +0000] "POST /api/login HTTP/1.1" 200 1784 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36" +10.0.0.1 - - [25/May/2024:20:18:37 +0000] "GET /images/logo.png HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0" +172.16.0.1 - - [25/May/2024:20:19:37 +0000] "GET /contact HTTP/1.1" 404 162 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1" +``` + +仅需要将 `Content-Type` header 设置成 `text/plain`,即可将纯文本请求发送到 GreptimeDB。 + +主要注意的是,和 JSON 格式自带 key 名可以被 Pipeline processor 识别和处理不同,`text/plain` 格式直接将整行文本输入到 Pipeline engine。在这种情况下我们可以使用 `message` 来指代整行输入文本,例如: + +```yaml +processors: + - dissect: + fields: + # 使用 `message` 作为 field 名称 + - message + patterns: + - '%{ip_address} - - [%{timestamp}] "%{http_method} %{request_line}" %{status_code} %{response_size} "-" "%{user_agent}"' + ignore_missing: true + +# pipeline 文件的剩余部分在这里省略 +``` + +对于 `text/plain` 格式的输入,推荐首先使用 `dissect` 或者 `regex` processor 将整行文本分割成不同的字段,以便进行后续的处理。 + +## 设置表选项 + +写入日志的表选项需要在 pipeline 中配置。 +从 `v0.15` 开始,pipeline 引擎可以识别特定的变量名称,并且通过这些变量对应的值设置相应的建表选项。 +通过与 `vrl` 处理器的结合,现在可以非常轻易地通过输入的数据在 pipeline 的执行过程中设置建表选项。 + +以下是支持的表选项变量名: +- `greptime_auto_create_table` +- `greptime_ttl` +- `greptime_append_mode` +- `greptime_merge_mode` +- `greptime_physical_table` +- `greptime_skip_wal` + +请前往[表选项](/reference/sql/create.md#表选项)文档了解每一个选项的详细含义。 + +以下是 pipeline 特有的变量: +- `greptime_table_suffix`: 在给定的目标表后增加后缀 + +以如下 pipeline 文件为例 +```YAML +processors: + - date: + field: time + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + ignore_missing: true + - vrl: + source: | + .greptime_table_suffix, err = "_" + .id + .greptime_table_ttl = "1d" + . +``` + +在这份 vrl 脚本中,我们将表后缀变量设置为输入字段中的 `id`(通过一个下划线连接),然后将 ttl 设置成 `1d`。 +然后我们使用如下数据执行写入。 + +```JSON +{ + "id": "2436", + "time": "2024-05-25 20:16:37.217" +} +``` + +假设给定的表名为 `d_table`,那么最终的表名就会按照预期被设置成 `d_table_2436`。这个表同样的 ttl 同样会被设置成 1 天。 + +## 示例 + +请参考[快速开始](/user-guide/logs/quick-start.md)和[使用自定义 pipeline 中的](/user-guide/logs/use-custom-pipelines.md#使用-pipeline-写入日志)写入日志部分的文档。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql-tools.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql-tools.md new file mode 100644 index 0000000000..bd6436e05e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/reference/sql/admin.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/admin.md new file mode 100644 index 0000000000..bccf7efe37 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/admin.md @@ -0,0 +1,45 @@ +--- +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/deployments-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/deployments-administration/manage-data/region-migration.md)。 +* `procedure_state(procedure_id)` 根据 ID 查询 Procedure 状态。 +* `flush_flow(flow_name)` 将 Flow 的输出刷新到目标接收表。 +* `reconcile_table(table_name)` 修复指定表的元数据不一致问题,详细信息请阅读 [table reconciliation](/user-guide/deployments-administration/maintenance/table-reconciliation.md)。 +* `reconcile_database(database_name)` 修复指定数据库中所有表的元数据不一致问题,详细信息请阅读 [table reconciliation](/user-guide/deployments-administration/maintenance/table-reconciliation.md)。 +* `reconcile_catalog()` 修复整个集群中所有表的元数据不一致问题,详细信息请阅读 [table reconciliation](/user-guide/deployments-administration/maintenance/table-reconciliation.md)。 + +例如: +```sql +-- 刷新表 test -- +admin flush_table("test"); + +-- 为表 test 启动 compaction 任务,默认并行度为 1 -- +admin compact_table("test"); + +-- 启动常规 compaction,并行度设置为 2 -- +admin compact_table("test", "regular", "parallelism=2"); + +-- 启动 SWCS compaction,使用默认时间窗口,并行度设置为 2 -- +admin compact_table("test", "swcs", "parallelism=2"); + +-- 启动 SWCS compaction,自定义时间窗口和并行度 -- +admin compact_table("test", "swcs", "window=1800,parallelism=2"); +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/alter.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/alter.md new file mode 100644 index 0000000000..c9a857a33a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/alter.md @@ -0,0 +1,247 @@ +--- +keywords: [修改数据库, 修改表, ALTER 语句, SQL ALTER, 数据库设置, 表设置] +description: ALTER 用于修改数据库的设置、表的设置或表的元数据。 +--- + +# ALTER + +`ALTER` 可以用来修改数据库的设置,表的设置或表的元数据,包括: + +* 修改数据库选项 +* 添加/删除/修改列 +* 设置/取消列默认值 +* 重命名表 +* 修改表选项 + +## ALTER DATABASE + + +`ALTER DATABASE` 语句可以用来修改数据库的选项。 + +### 语法 + +```sql +ALTER DATABASE db + [SET = [, ...] + | UNSET [, ...] + ] +``` + +当前支持修改以下数据库选项: +- `ttl`: 数据库中数据的默认保留时间。过期的数据会被异步删除。 + - 如果之前未设置 ttl,通过 `ALTER` 设置新的 ttl 后,超过保留时间的数据将被删除。 + - 如果之前已设置过 ttl,通过 `ALTER` 修改 ttl 后,新的保留时间将立即生效,超过新保留时间的数据将被删除。 + - 如果之前已设置过 ttl,通过 `ALTER` 取消 ttl 设置后,新增的数据将不会被删除,但已被删除的数据无法恢复。 + +### 示例 + +#### 修改数据库中数据的默认保留时间 + +修改数据库中数据的默认保留时间为 1 天: + +```sql +ALTER DATABASE db SET 'ttl'='1d'; +``` + +取消数据库中数据的默认保留时间设置: + +```sql +ALTER DATABASE db UNSET 'ttl'; +``` + +## ALTER TABLE + +## 语法 + +```sql +ALTER TABLE [db.]table + [ADD COLUMN name1 type1 [options], ADD COLUMN name2 type2 [options], ... + | DROP COLUMN name + | MODIFY COLUMN name type + | MODIFY COLUMN name SET DEFAULT value + | MODIFY COLUMN name DROP DEFAULT + | MODIFY COLUMN name SET FULLTEXT INDEX [WITH ] + | MODIFY COLUMN name UNSET FULLTEXT INDEX + | RENAME name + | SET = [, ...] + ] +``` + + +### 增加列 + +在表中增加新列: + +```sql +ALTER TABLE monitor ADD COLUMN load_15 double; +``` + +列的定义和 [CREATE](./create.md) 中的定义方式一样。 + +我们可以在表中同时增加多个列: + +```sql +ALTER TABLE monitor ADD COLUMN disk_usage double, ADD COLUMN disk_free double; +``` + +我们可以设置新列的位置。比如放在第一位: + +```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`)。 + +### 设置列默认值 + +为现有列设置默认值: + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 SET DEFAULT 0.0; +``` + +设置字符串默认值: + +```sql +ALTER TABLE monitor MODIFY COLUMN `status` SET DEFAULT 'active'; +``` + +默认值将在插入新行时使用,当该列没有显式提供值时。 + +移除列的默认值: + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 DROP DEFAULT; +``` + +删除默认值后,该列将使用 `NULL` 作为默认值。数据库只允许对可为空的列删除默认值。 + +### 修改表的参数 + +`ALTER TABLE` 语句也可以用来更改表的选项。 +当前支持修改以下表选项: +- `ttl`: 表数据的保留时间。 +- `compaction.twcs.time_window`: TWCS compaction 策略的时间窗口,其值是一个[时间范围字符段](/reference/time-durations.md)。 +- `compaction.twcs.max_output_file_size`: TWCS compaction 策略的最大允许输出文件大小。 +- `compaction.twcs.trigger_file_num`: 某个窗口内触发 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.trigger_file_num'='8'; +``` + +### 移除表参数 + +```sql +ALTER TABLE monitor UNSET 'ttl'; +``` + +### 创建列的索引 + +在列上启用倒排索引: + +```sql +ALTER TABLE monitor MODIFY COLUMN host SET INVERTED INDEX; +``` + +启用列的全文索引: + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 SET FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'bloom'); +``` + +在启用列的全文索引时,可以使用 `FULLTEXT INDEX WITH` 指定以下选项: + +- `analyzer`:设置全文索引的分析器语言。支持的值为 `English` 和 `Chinese`。默认为 `English`。 +- `case_sensitive`:设置全文索引是否区分大小写。支持的值为 `true` 和 `false`。默认为 `false`。 +- `backend`:设置全文索引的后端实现。支持的值为 `bloom` 和 `tantivy`。默认为 `bloom`。 +- `granularity`:(适用于 `bloom` 后端)每个过滤器覆盖的数据块大小。粒度越小,过滤效果越好,但索引大小会增加。默认为 `10240`。 +- `false_positive_rate`:(适用于 `bloom` 后端)错误识别块的概率。该值越低,准确性越高(过滤效果越好),但索引大小会增加。该值为介于 `0` 和 `1` 之间的浮点数。默认为 `0.01`。 + +更多关于全文索引配置和性能对比的信息,请参考[全文索引配置指南](/user-guide/manage-data/data-index.md#全文索引)。 + +与 `CREATE TABLE` 一样,可以不带 `WITH` 选项,全部使用默认值。 + +启用列上的跳数索引: +```sql +ALTER TABLE monitor MODIFY COLUMN host SET SKIPPING INDEX WITH(granularity = 1024, type = 'BLOOM'); +``` + +跳数索引的有效选项包括: +* `type`: 索引类型,目前仅支持 `BLOOM` 即布隆过滤器。 +* `granularity`: (适用于 `BLOOM` 类型)每个过滤器覆盖的数据块大小。粒度越小,过滤效果越好,但索引大小会增加。默认为 `10240`。 +* `false_positive_rate`: (适用于 `BLOOM` 类型)错误识别块的概率。该值越低,准确性越高(过滤效果越好),但索引大小会增加。该值为介于 `0` 和 `1` 之间的浮点数。默认为 `0.01`。 + +### 移除列的索引 + +语法如下: + +```sql +ALTER TABLE [table] MODIFY COLUMN [column] UNSET [INVERTED | SKIPPING | FULLTEXT] INDEX; +``` + +例如,移除倒排索引: + +```sql +ALTER TABLE monitor_pk MODIFY COLUMN host UNSET INVERTED INDEX; +``` + +移除跳数索引: + +```sql +ALTER TABLE monitor_pk MODIFY COLUMN host UNSET SKIPPING INDEX; +``` + +移除全文索引: + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 UNSET FULLTEXT INDEX; +``` + +修改列的全文索引选项时,列的数据类型必须是字符串类型。 + +当列的全文索引未开启过时,可以启用全文索引,并设置 `analyzer` 和 `case_sensitive` 选项;当列的全文索引选项已经启用时,可以关闭全文索引,**但不能修改选项,跳数索引也是如此**。 + +### 重命名表 + +```sql +ALTER TABLE monitor RENAME monitor_new; +``` + +该命令只是重命名表,不会修改表中的数据。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/case.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/case.md new file mode 100644 index 0000000000..9bcb03ca6c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/reference/sql/cast.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/cast.md new file mode 100644 index 0000000000..01f28fa475 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/cast.md @@ -0,0 +1,35 @@ +--- +keywords: [数据类型转换, CAST 语句, SQL CAST, 类型转换, 数据类型, SQL 语法] +description: CAST 用于将一个数据类型的表达式转换为另一个数据类型。 +--- + +# CAST + +`CAST` 用于将一个数据类型的表达式转换为另一个数据类型。 + +## Syntax + +```sql +CAST (expression AS data_type) +``` + +## 参数 + +- expression: 需要类型转换的表达式。 +- data_type: 需要被转换为的数据类型。 + +# 示例 + +将字符串转换为 `INT` 类型: + + ```sql + SELECT CAST('123' AS INT) ; + ``` + +```sql ++-------------+ +| Utf8("123") | ++-------------+ +| 123 | ++-------------+ +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/compatibility.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/compatibility.md new file mode 100644 index 0000000000..56c899fd36 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/compatibility.md @@ -0,0 +1,25 @@ +--- +keywords: [ANSI SQL, SQL 兼容性, SQL 扩展, SQL 语法, 数据库兼容性, SQL 特性] +description: GreptimeDB 支持的 SQL 是 ANSI SQL 的子集,并且拥有一些特有的扩展。 +--- + +# ANSI Compatibility + +GreptimeDB 支持的 SQL 是 ANSI SQL 的子集,并且拥有一些特有的扩展。一些主要的不兼容和扩展描述如下: + +1. 建表 + * 支持特有的 `TIME INDEX` 约束,详细请参考[数据模型](/user-guide/concepts/data-model.md)和 [CREATE](./create.md) 建表语法一节。 + * 目前仅支持 `PRIMARY KEY` 约束,不支持其他类型的约束,也不支持外键。 + * 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 中还是标准的双引号 `"`。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/copy.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/copy.md new file mode 100644 index 0000000000..bdae6e7a54 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/copy.md @@ -0,0 +1,227 @@ +--- +keywords: [数据导入, 数据导出, COPY 语句, SQL COPY, 数据库复制, 表复制] +description: COPY 语句用于导入和导出表或数据库的数据。 +--- + +# COPY + +## COPY TABLE +### COPY TO + +`COPY TO` 被用来将表的内容导出到文件中,其语法如下: + +```sql +COPY tbl TO '/xxx/xxx/output.parquet' WITH (FORMAT = 'parquet'); +``` + +命令以 `COPY` 关键字开始,后面跟着要导出数据的表名(本例中为 `tbl`)。 +`TO` 指定导出数据的文件路径和名称(本例中为 `/xxx/xxx/output.parquet`)。 + +例如,可以使用自定义时间戳和日期格式导出数据到 CSV 文件: + +```sql +COPY tbl TO '/path/to/file.csv' WITH ( + FORMAT = 'csv', + TIMESTAMP_FORMAT = '%Y/%m/%d %H:%M:%S', + DATE_FORMAT = '%Y-%m-%d' +); +``` + +#### `WITH` 选项 + +`WITH` 可以添加一些选项,比如文件的 `FORMAT` 用来指定导出文件的格式。本例中的格式为 Parquet,它是一种用于大数据处理的列式存储格式。Parquet 为大数据分析高效地压缩和编码列式数据。 + +| 选项 | 描述 | 是否必需 | +|---|---|---| +| `FORMAT` | 目标文件格式,例如 JSON, CSV, Parquet | **是** | +| `START_TIME`/`END_TIME`| 需要导出数据的时间范围,时间范围为左闭右开 | 可选 | +| `TIMESTAMP_FORMAT` | 导出 CSV 格式时自定义时间戳列的格式。使用 [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) 格式说明符(例如 `'%Y-%m-%d %H:%M:%S'`)。仅支持 CSV 格式。 | 可选 | +| `DATE_FORMAT` | 导出 CSV 格式时自定义日期列的格式。使用 [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) 格式说明符(例如 `'%Y-%m-%d'`)。仅支持 CSV 格式。 | 可选 | +| `TIME_FORMAT` | 导出 CSV 格式时自定义时间列的格式。使用 [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) 格式说明符(例如 `'%H:%M:%S'`)。仅支持 CSV 格式。 | 可选 | + +#### `CONNECTION` 选项 + +`COPY TO` 支持导出数据到云存储上,比如 S3。详情请参考 [连接 S3](#连接-s3)。 + + +### COPY FROM + +`COPY FROM` 被用来将文件中的数据导入到表中,其语法如下: + +```sql +COPY [.] +FROM { '/[]' } +[ [ WITH ] + ( + [ FORMAT = { 'CSV' | 'JSON' | 'PARQUET' | 'ORC' } ] + [ PATTERN = '' ] + ) +] +[LIMIT NUM] +``` + +命令以 `COPY` 关键字开始,后面跟着要导入数据的表名。 + +#### `WITH` 选项 + +`FORMAT` 指定导入文件的格式,本例中为 Parquet。 + +选项 `PATTERN` 允许使用通配符(如 *)指定匹配某种模式的多个输入文件。例如,你可以使用以下语法导入目录(必须是绝对路径)"/path/to/folder" 中文件名包含 `parquet` 的所有文件: + +```sql +COPY tbl FROM '/path/to/folder/' WITH (FORMAT = 'parquet', PATTERN = '.*parquet.*'); +``` + +例如,如果你只有一个文件需要导入,可以使用下方的语法: + +```sql +COPY tbl FROM '/path/to/folder/xxx.parquet' WITH (FORMAT = 'parquet'); +``` + +| 选项 | 描述 | 是否必需 | +|---|---|---| +| `FORMAT` | 目标文件格式,例如 JSON, CSV, Parquet, ORC | **是** | +| `PATTERN` | 使用正则匹配文件,例如 `*_today.parquet` | 可选 | + +:::tip NOTE +CSV 文件必须带有 header,包含表的列名。 +::: + +#### Connection 选项 + +`COPY FROM` 同样支持从云存储上导入数据,比如 S3。详情请参考 [连接 S3](#连接-s3)。 + +#### LIMIT 选项 + +可以通过 `LIMIT` 手动限制一次插入的最大行数。 + +### 连接 S3 + +你可以从 S3 导入/导出数据 + +```sql +-- COPY FROM +COPY tbl FROM '' WITH (FORMAT = 'parquet') CONNECTION(REGION = 'us-west-2'); + +-- COPY TO +COPY tbl TO '' WITH (FORMAT = 'parquet') CONNECTION(REGION = 'us-west-2'); +``` + +#### URL + +注意:你应该使用 `S3://bucket/key-name` 指定文件。下方的例子展示了正确的格式: + +``` +S3://my-bucket/data.parquet +``` + +另一种方式是使用 Virtual-hosted–style(`ENABLE_VIRTUAL_HOST_STYLE` 需要设置成 `true`),例如: + +``` +https://bucket-name.s3.region-code.amazonaws.com/key-name +``` + +:::tip NOTE +可以在 S3 控制台上点击 `Copy S3 URI` 或者 `COPY URL` 直接获取对应的 URL/HTTP 前缀或者完整路径。 +::: + +#### 选项 + +你可以设置这些 **CONNECTION** 选项: + +| 选项 | 描述 | 是否必需 | +|---|---|---| +| `REGION` | AWS region 名称,例如 `us-west-2` | **是** | +| `ENDPOINT` | The bucket endpoint,例如 `s3.us-west-2.amazonaws.com` | 可选 | +| `ACCESS_KEY_ID` | 用于连接 AWS S3 兼容的对象存储的访问密钥 ID | 可选 | +| `SECRET_ACCESS_KEY` | 用于连接 AWS S3 兼容的对象存储的秘密访问密钥 | 可选 | +| `ENABLE_VIRTUAL_HOST_STYLE` | 如果你使用 virtual hosting 的方式来定位 bucket,将该选项设置为 "true" | 可选 | +| `SESSION_TOKEN` | 用于连接 AWS S3 服务的临时凭证。 | 可选 | + +## COPY 查询结果 + +你可以使用 `COPY` 语句将查询结果导出到文件中。语法如下: + +```sql +COPY () TO '' WITH (FORMAT = { 'CSV' | 'JSON' | 'PARQUET' }); +``` + +| 选项 | 描述 | 是否必需 | +|---|---|---| +| `QUERY` | 要执行的 SQL SELECT 语句 | **是** | +| `PATH` | 输出文件的路径 | **是** | +| `FORMAT` | 输出文件格式:'CSV'、'JSON' 或 'PARQUET' | **是** | +| `TIMESTAMP_FORMAT` | 导出 CSV 格式时自定义时间戳列的格式。使用 [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) 格式说明符。仅支持 CSV 格式。 | 可选 | +| `DATE_FORMAT` | 导出 CSV 格式时自定义日期列的格式。使用 [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) 格式说明符。仅支持 CSV 格式。 | 可选 | +| `TIME_FORMAT` | 导出 CSV 格式时自定义时间列的格式。使用 [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) 格式说明符。仅支持 CSV 格式。 | 可选 | + +例如,以下语句将查询结果导出到 CSV 文件中: + +```sql +COPY (SELECT * FROM tbl WHERE host = 'host1') TO '/path/to/file.csv' WITH (FORMAT = 'csv'); +``` + +也可以在导出到 CSV 时指定自定义日期和时间格式: + +```sql +COPY (SELECT * FROM tbl WHERE host = 'host1') TO '/path/to/file.csv' WITH ( + FORMAT = 'csv', + TIMESTAMP_FORMAT = '%m-%d-%Y %H:%M:%S', + DATE_FORMAT = '%Y/%m/%d' +); +``` + +## COPY DATABASE + +`COPY` 语句除可以导入/导出表之外,也可以导入/导出指定的数据库,其语法如下: + +```sql +COPY DATABASE + [TO | FROM] '' + WITH ( + FORMAT = { 'CSV' | 'JSON' | 'PARQUET' } + START_TIME = "", + END_TIME = "" + ) + [CONNECTION( + REGION = "", + ENDPOINT = "", + ACCESS_KEY_ID = "", + SECRET_ACCESS_KEY = "", + ENABLE_VIRTUAL_HOST_STYLE = "[true | false]", + )] +``` + +| 选项 | 描述 | 是否必需 | +|---|---|---| +| `FORMAT` | 目标文件格式,例如 JSON, CSV, Parquet | **是** | +| `START_TIME`/`END_TIME`| 需要导出数据的时间范围,时间范围为左闭右开 | 可选 | + +> - 当导入/导出表时,`` 参数必须以 `/` 结尾; +> - COPY DATABASE 同样可以通过 `CONNECTION` 参数将数据导入/导出的路径指向 S3 等对象存储 + + +### 示例 + +```sql +-- 将 public 数据库中所有数据导出到 /tmp/export/ 目录下 +COPY DATABASE public TO '/tmp/export/' WITH (FORMAT='parquet'); + +-- 将 public 数据库中时间范围在 2022-04-11 08:00:00 到 2022-04-11 09:00:00 之间的数据导出到 /tmp/export/ 目录下 +COPY DATABASE public TO '/tmp/export/' WITH (FORMAT='parquet', START_TIME='2022-04-11 08:00:00', END_TIME='2022-04-11 09:00:00'); + +-- 从 /tmp/export/ 目录恢复 public 数据库的数据 +COPY DATABASE public FROM '/tmp/export/' WITH (FORMAT='parquet'); +``` + +## Windows 平台上的路径 + +请注意,在 Windows 平台上执行 `COPY`/`COPY DATABASE` 语句时,请使用 `/` 代替 `` 中的 `\`,如 `C:/some_dir/output.parquet`。 + +```sql +-- 下列语句将会报错 +COPY tbl TO 'C:\xxx\xxx\output.parquet' WITH (FORMAT = 'parquet'); + +-- 下列语句能够正常执行 +COPY tbl TO 'C:/xxx/xxx/output.parquet' WITH (FORMAT = 'parquet'); +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/create.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/create.md new file mode 100644 index 0000000000..43480516db --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/create.md @@ -0,0 +1,488 @@ +--- +keywords: [创建数据库, 创建表, CREATE 语句, SQL 创建, 数据库选项, 表选项] +description: CREATE 用于创建新的数据库或表,支持指定列、主键、时间索引、存储引擎和其他选项。 +--- + +# CREATE + +`CREATE` 用于创建新的数据库或者表。 + +## CREATE DATABASE + +### Syntax + +创建新数据库: + +```sql +CREATE DATABASE [IF NOT EXISTS] db_name [WITH ] +``` + +如果 `db_name` 数据库已经存在,`CREATE` 语句的行为如下: + +- 不会创建新的数据库。 +- 当 `IF NOT EXISTS` 子句被指定时,不会返回错误。 +- 否则,返回错误。 + +数据库也可以通过使用 `WITH` 关键字配置与 `CREATE TABLE` 语句类似的选项。数据库支持以下选项: + +- `ttl` - 数据库中所有表的数据存活时间(不能设置为 `instant`) +- `memtable.type` - 内存表类型(`time_series`、`partition_tree`) +- `append_mode` - 数据库中的表是否为仅追加模式(`true`/`false`) +- `merge_mode` - 合并重复行的策略(`last_row`、`last_non_null`) +- `skip_wal` - 是否为数据库中的表禁用预写日志(`'true'`/`'false'`) +- `compaction.*` - 压缩相关设置(如 `compaction.type`、`compaction.twcs.time_window`) + +阅读更多关于[表选项](#表选项)的信息。 + +:::note 重要的行为差异 +数据库选项的行为有所不同: + +- **TTL**:此选项具有**持续影响**。没有指定 TTL 的表会持续继承这个数据库级别的值。更改数据库 TTL 会立即影响所有没有明确自行设置 TTL 的表。 + +- **其他选项**(`memtable.type`、`append_mode`、`merge_mode`、`skip_wal`、`compaction.*`):这些选项充当**模板变量**,仅在创建新表时应用。更改这些数据库级别的选项不会影响已存在的表——它们仅作为新创建表的默认值。 +::: + +在创建表时,如果未提供相应的表选项,将使用在数据库级别配置的选项或者默认值。 + +### 示例 + +创建名为 `test` 的数据库: + +```sql +CREATE DATABASE test; +``` + +```sql +Query OK, 1 row affected (0.05 sec) +``` + +使用 `IF NOT EXISTS` 再次创建: + +```sql +CREATE DATABASE IF NOT EXISTS test; +``` + +创建一个具有 7 天 `TTL`(数据存活时间)的数据库,也就是该数据库中的所有表如果没有单独设置 TTL 选项,都将继承此选项值。 + +```sql +CREATE DATABASE test WITH (ttl='7d'); +``` + +创建一个带有多个选项的数据库,包括仅追加模式和自定义内存表类型: + +```sql +CREATE DATABASE test WITH ( + ttl='30d', + 'memtable.type'='partition_tree', + 'append_mode'='true' +); +``` + +创建一个禁用预写日志并设置自定义合并模式的数据库: + +```sql +CREATE DATABASE test WITH ( + 'skip_wal'='true', + 'merge_mode'='last_non_null' +); +``` + + +## CREATE TABLE + +### Syntax + +在 `db` 或当前数据库中创建新表: + +```sql +CREATE TABLE [IF NOT EXISTS] [db.]table_name +( + column1 type1 [NULL | NOT NULL] [DEFAULT expr1] [TIME INDEX] [PRIMARY KEY] [indexes] [COMMENT comment1], + column2 type2 [NULL | NOT NULL] [DEFAULT expr2] [TIME INDEX] [PRIMARY KEY] [indexes] [COMMENT comment2], + ... + [TIME INDEX (column)], + [PRIMARY KEY(column1, column2, ...)], +) +[ + PARTITION ON COLUMNS(column1, column2, ...) ( + , + ... + ) +] +ENGINE = engine WITH([TTL | storage | ...] = expr, ...) +``` + +表 schema 由 `ENGINE` 之前的括号指定,表 schema 是列的定义和表的约束。 +列定义包括列名称和数据类型,以及可选的 `NULL`、`NOT NULL`、`DEFAULT` 等。 + +关于 `engine` 选项和表引擎的选择,请阅读[表引擎](/reference/about-greptimedb-engines.md)介绍。 + +### 表约束 + +表约束包括以下内容: + +- `TIME INDEX` 指定时间索引列,每个表只能有一个时间索引列。它表示 GreptimeDB 的 [数据模型](/user-guide/concepts/data-model.md) 中的 `Timestamp` 类型。 +- `PRIMARY KEY` 指定表的主键列,它表示 GreptimeDB 的 [数据模型](/user-guide/concepts/data-model.md) 中的 `Tag` 类型。它不能包含时间索引列,但是它总是隐式地将时间索引列添加到键的末尾。 +- 其他列是 GreptimeDB 的 [数据模型](/user-guide/concepts/data-model.md) 中的 `Field` 类型。 + +:::tip 注意 +`CREATE` 语句中指定的 `PRIMARY KEY` **不是** 传统关系数据库中的主键。 +实际上,传统关系数据库中的 `PRIMARY KEY` 相当于 GreptimeDB 中的 `PRIMARY KEY` 和 `TIME INDEX` 的组合。 +换句话说,`PRIMARY KEY` 和 `TIME INDEX` 一起构成了 GreptimeDB 中行的唯一标识符。 +::: + +如果表已经存在且创建表时指定了 `IF NOT EXISTS`,`CREATE` 语句不会返回错误;否则返回错误。 + +#### 索引 + + +GreptimeDB 提供了丰富的索引实现来加速查询,请在[索引](/user-guide/manage-data/data-index.md)章节查看更多信息。 + +### 表选项 + +用户可以使用 `WITH` 添加表选项。有效的选项包括以下内容: + +| 选项 | 描述 | 值 | +| ------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `ttl` | 表数据的存储时间 | 一个时间范围字符串,例如 `'60m'`, `'1h'` 代表 1 小时, `'14d'` 代表 14 天等。支持的时间单位有:`s` / `m` / `h` / `d` | +| `storage` | 自定义表的存储引擎,存储引擎提供商的名字 | 字符串,类似 `S3`、`Gcs` 等。必须在 `[[storage.providers]]` 列表里配置,参考 [configuration](/user-guide/deployments-administration/configuration.md#存储引擎提供商)。 | +| `compaction.type` | Compaction 策略 | 字符串值。只支持 `twcs`。你可以阅读这篇[文章](https://cassandra.apache.org/doc/latest/cassandra/managing/operating/compaction/twcs.html)来了解 `twcs` compaction 策略 | +| `compaction.twcs.trigger_file_num` | 某个窗口内触发 compaction 的最小文件数量阈值 | 字符串值,如 '8'。只在 `compaction.type` 为 `twcs` 时可用 | +| `compaction.twcs.time_window` | Compaction 时间窗口 | 字符串值,如 '1d' 表示 1 天。该表会根据时间戳将数据分区到不同的时间窗口中。只在 `compaction.type` 为 `twcs` 时可用 | +| `compaction.twcs.max_output_file_size` | TWCS compaction 的最大输出文件大小 | 字符串值,如 '1GB'、'512MB'。设置 TWCS compaction 产生的文件的最大大小。只在 `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` | 表级注释 | 字符串值。 | +| `index.type` | Index 类型 | **仅用于 metric engine** 字符串值,支持 `none`, `skipping`. | +| `skip_wal` | 是否关闭表的预写日志 | 字符串类型。当设置为 `'true'` 时表的写入数据将不会持久化到预写日志,可以避免存储磨损同时提升写入吞吐。但是当进程重启时,尚未 flush 的数据会丢失。请仅在数据源本身可以确保可靠性的情况下使用此功能。 | + +#### 创建指定 TTL 的表 +例如,创建一个存储数据 TTL(Time-To-Live) 为七天的表: + +```sql +CREATE TABLE IF NOT EXISTS temperatures( + ts TIMESTAMP TIME INDEX, + temperature DOUBLE DEFAULT 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, +) with(ttl='7d', storage="Gcs"); +``` + +#### 创建自定义 compaction 参数的表 +创建带自定义 twcs compaction 参数的表。这个表会尝试根据数据的时间戳将数据按 1 天的时间窗口分区,并会在最新时间窗口内的文件超过 8 个时合并该窗口的文件 + +```sql +CREATE TABLE IF NOT EXISTS temperatures( + ts TIMESTAMP TIME INDEX, + temperature DOUBLE DEFAULT 10, +) +with( + 'compaction.type'='twcs', + 'compaction.twcs.time_window'='1d', + 'compaction.twcs.trigger_file_num'='8', + 'compaction.twcs.max_output_file_size'='1GB' +); +``` + +#### 创建 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` 模式下,表会通过保留每个字段的最新非 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 | ++-------+-------------------------+------+--------+ +``` + +#### 创建 metric engine 的物理表 + +metric engine 使用合成物理宽表来存储大量的小表数据,实现重用相同列和元数据的效果。详情请参考 [metric engine 文档](/contributor-guide/datanode/metric-engine)和[表引擎](/reference/about-greptimedb-engines.md)介绍。 + +创建一个使用 metric engine 的物理表。 +```sql +CREATE TABLE greptime_physical_table ( + greptime_timestamp TIMESTAMP(3) NOT NULL, + greptime_value DOUBLE NULL, + TIME INDEX (greptime_timestamp), +) +engine = metric +with ( + "physical_metric_table" = "", +); +``` + +#### 创建一个带有跳数索引的物理表 + +默认情况下,metric engine 不会为列创建索引。你可以通过设置 `index.type` 为 `skipping` 来设置索引类型。 + +创建一个带有跳数索引的物理表。所有自动添加的列都将应用跳数索引。 + +```sql +CREATE TABLE greptime_physical_table ( + greptime_timestamp TIMESTAMP(3) NOT NULL, + greptime_value DOUBLE NULL, + TIME INDEX (greptime_timestamp), +) +engine = metric +with ( + "physical_metric_table" = "", + "index.type" = "skipping", +); +``` + + +### 列选项 + +GreptimeDB 支持以下列选项: + +| 选项 | 描述 | +| ----------------- | -------------------------------------------------------- | +| NULL | 列值可以为 `null` | +| NOT NULL | 列值不能为 `null` | +| DEFAULT `expr` | 该列的默认值是 `expr`,其类型必须是该列的类型 | +| COMMENT `comment` | 列注释,必须为字符串类型 | +| FULLTEXT INDEX | 创建全文索引,可以加速全文搜索操作。仅适用于字符串类型列 | +| SKIPPING INDEX | 创建跳数索引,可以加速查询稀疏数据。 | +| INVERTED INDEX | 创建倒排索引,可以加速查询稠密数据。 | + +表约束 `TIME INDEX` 和 `PRIMARY KEY` 也可以通过列选项设置,但是它们只能在列定义中指定一次,在多个列选项中指定 `PRIMARY KEY` 会报错: + +```sql +CREATE TABLE system_metrics ( + host STRING PRIMARY KEY, + idc STRING PRIMARY KEY, + cpu_util DOUBLE, + memory_util DOUBLE, + disk_util DOUBLE, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP(), + TIME INDEX(ts) +); +``` + +会得到报错: + +```sql + Illegal primary keys definition: not allowed to inline multiple primary keys in columns options +``` + +正确的做法是使用 `PRIMARY KEY()` 来指定多个列作为主键: + +```sql +CREATE TABLE system_metrics ( + host STRING, + idc STRING, + cpu_util DOUBLE, + memory_util DOUBLE, + disk_util DOUBLE, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + PRIMARY KEY(host, idc), +); +``` + +```sql +Query OK, 0 rows affected (0.01 sec) +``` + +#### `INDEX` 列选项 + +更多关于索引配置、性能对比和使用指南的信息,请参考[索引](/user-guide/manage-data/data-index.md)章节。 + +### Region 分区规则 + +请参考 [分区](/contributor-guide/frontend/table-sharding.md#partition) 章节。 + +## CREATE EXTERNAL TABLE + +### Syntax + +在 `db` 或当前数据库中创建新的文件外部表: + +```sql +CREATE EXTERNAL 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], + ... + [TIME INDEX (column)], + [PRIMARY KEY(column1, column2, ...)] + ) +] WITH ( + LOCATION = url, + FORMAT = { 'CSV' | 'JSON' | 'PARQUET' | 'ORC' } + [,PATTERN = regex_pattern ] + [,REGION = region ] + [,ENDPOINT = uri ] + [,ACCESS_KEY_ID = key_id ] + [,SECRET_ACCESS_KEY = access_key ] + [,ENABLE_VIRTUAL HOST_STYLE = { TRUE | FALSE }] + [,SESSION_TOKEN = token ] + ... +) +``` + +### 表选项 + +| 选项 | 描述 | 是否必需 | +| ---------- | ------------------------------------------------------------------ | -------- | +| `LOCATION` | 外部表的位置,例如 `s3://[]`, `//[]` | **是** | +| `FORMAT` | 目标文件的格式,例如 JSON,CSV,Parquet, ORC | **是** | +| `PATTERN` | 使用正则来匹配文件,例如 `*_today.parquet` | 可选 | + +#### S3 + +| 选项 | 描述 | 是否必需 | +| --------------------------- | --------------------------------------------------------------- | -------- | +| `REGION` | AWS region 名称,例如 us-east-1 | **是** | +| `ENDPOINT` | The bucket endpoint | 可选 | +| `ACCESS_KEY_ID` | 用于连接 AWS S3 兼容对象存储的访问密钥 ID | 可选 | +| `SECRET_ACCESS_KEY` | 用于连接 AWS S3 兼容对象存储的秘密访问密钥 | 可选 | +| `ENABLE_VIRTUAL HOST_STYLE` | 如果你想要使用 virtual hosting 来定位 bucket,将其设置为 `true` | 可选 | +| `SESSION_TOKEN` | 用于连接 AWS S3 服务的临时凭证 | 可选 | + +### 时间索引列 + +在利用 `CREATE EXTERNAL TABLE` 语句创建外部表时,要求使用 `TIME INDEX` 约束来指定一个时间索引列。 + +### 示例 + +你可以在创建外部表时不带有列定义,列定义将会被自动推断: + +```sql +CREATE EXTERNAL TABLE IF NOT EXISTS city WITH (location='/var/data/city.csv',format='csv'); +``` + +在这个例子中,我们没有明确定义表的列,为满足外边表必须指定**时间索引列**的要求,`CREATE EXTERNAL TABLE` 语句会依据下述规则推断出时间索引列: + +1. 如果可以从文件元数据中推断出时间索引列,那么就用该列作为时间索引列。 +2. 如果存在名为 `greptime_timestamp` 的列(该列的类型必须为 `TIMESTAMP`,否则将抛出错误),那么就用该列作为时间索引列。 +3. 否则,将自动创建名为 `greptime_timestamp` 的列作为时间索引列,并添加 `DEFAULT '1970-01-01 00:00:00+0000'` 约束。 + +或者带有列定义: + +```sql +CREATE EXTERNAL TABLE city ( + host string, + ts timestamp, + cpu float64 default 0, + memory float64, + TIME INDEX (ts), + PRIMARY KEY(host) +) WITH (location='/var/data/city.csv', format='csv'); +``` + +在这个例子中,我们明确定义了 `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#视图)。 + +## 创建 Trigger + +请参考 [CREATE TRIGGER](/reference/sql/trigger-syntax.md#create-trigger) 文档。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/data-types.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/data-types.md new file mode 100644 index 0000000000..c536069215 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/data-types.md @@ -0,0 +1,407 @@ +--- +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() - '5 minute'::INTERVAL; +``` + +```sql ++----------------------------------------------+ +| now() - IntervalMonthDayNano("300000000000") | ++----------------------------------------------+ +| 2024-06-24 21:24:05.012306 | ++----------------------------------------------+ +``` + +GreptimeDB 还支持类似 `3y2mon4h` 这样不包含空格的简写形式: + +```sql +SELECT '3y2mon4h'::INTERVAL; +``` + +``` ++---------------------------------------------------------+ +| IntervalMonthDayNano("3010670175542044842954670112768") | ++---------------------------------------------------------+ +| P3Y2M0DT4H0M0S | ++---------------------------------------------------------+ +``` + +同样也支持符号数: + +```sql +SELECT '-1h5m'::INTERVAL; +``` + +``` ++----------------------------------------------+ +| 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 | + +#### INTERVAL 关键字 + +在上述示例中,我们使用了 `cast` 类型转换操作 `'{quantity unit}'::INTERVAL` 来演示 interval 类型。实际上,interval 类型也可以使用 `INTERVAL` 关键字支持的语法,不过不同数据库方言之间的行为有所差异: + +1. 在 MySQL 中,语法为 `INTERVAL {quantity} {unit}`,其中 `quantity` 可以是数字或字符串,具体取决于上下文。例如: +```sql +mysql> SELECT INTERVAL 1 YEAR; ++--------------------------------------------------------------------------------------+ +| IntervalMonthDayNano("IntervalMonthDayNano { months: 12, days: 0, nanoseconds: 0 }") | ++--------------------------------------------------------------------------------------+ +| P1Y0M0DT0H0M0S | ++--------------------------------------------------------------------------------------+ +1 row in set (0.01 sec) + +mysql> SELECT INTERVAL '1 YEAR 2' MONTH; ++--------------------------------------------------------------------------------------+ +| IntervalMonthDayNano("IntervalMonthDayNano { months: 14, days: 0, nanoseconds: 0 }") | ++--------------------------------------------------------------------------------------+ +| P1Y2M0DT0H0M0S | ++--------------------------------------------------------------------------------------+ +1 row in set (0.00 sec) +``` + +2. 在 PostgreSQL 和默认的 GreptimeDB 方言中,语法为 `INTERVAL '{quantity unit}'`,即 INTERVAL 关键字后跟 interval 字符串: +```sql +public=> SELECT INTERVAL '1 year'; + IntervalMonthDayNano("IntervalMonthDayNano { months: 12, days: 0, nanoseconds: 0 }") +-------------------------------------------------------------------------------------- + 1 year +(1 row) + +public=> SELECT INTERVAL '1 year 2 month'; + IntervalMonthDayNano("IntervalMonthDayNano { months: 14, days: 0, nanoseconds: 0 }") +-------------------------------------------------------------------------------------- + 1 year 2 mons +(1 row) +``` + +## JSON 类型(实验功能) + +:::warning +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 位毫秒精度的间戳,等同于 `TimestampMicrosecond` | 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 | TimestampMicrosecond | | 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-1.0/reference/sql/delete.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/delete.md new file mode 100644 index 0000000000..4d78aa4a57 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/delete.md @@ -0,0 +1,30 @@ +--- +keywords: [SQL DELETE 语句, 删除行数据, 数据删除, SQL 示例, 数据库操作] +description: DELETE 用于从表中删除行数据,满足条件的行会立刻被标记,后续查询无法获取这些行数据。 +--- + +# DELETE + +`DELETE` 用于从表中删除行数据。 + +## Syntax + +```sql +DELETE FROM [db.]table WHERE expr +``` + +上述命令从表 `[db.]table` 中删除满足 `expr` 的行。被删除的行会立刻被标记,后续的查询立刻不能获取到这些行数据。 + +## 示例 + +例如,有一个带有主键 `host` 的表: + +```sql +CREATE TABLE monitor ( host STRING, ts TIMESTAMP, cpu DOUBLE DEFAULT 0, memory DOUBLE, TIME INDEX (ts), PRIMARY KEY(host)) ; +``` + +删除 host 为 `host1` 以及时间戳为 `1655276557000` 的行: + +```sql +DELETE FROM monitor WHERE host = 'host1' and ts = 1655276557000; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/describe_table.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/describe_table.md new file mode 100644 index 0000000000..5a129f5a6c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/describe_table.md @@ -0,0 +1,44 @@ +--- +keywords: [SQL DESCRIBE TABLE 语句, 表结构描述, 列信息, 数据库表, SQL 示例] +description: DESCRIBE TABLE 用于描述数据库中表的结构,包括列名、类型、主键、是否为空、默认值和语义类型。 +--- + +# DESCRIBE TABLE + +`DESCRIBE [TABLE] [db.]table` 描述了 `db` 或当前使用的数据库中的表结构。 + +## 示例 + +描述表 `monitor`: + +```sql +DESCRIBE TABLE monitor; +``` + +或者 + +```sql +DESCRIBE monitor; +``` + +```sql +```sql ++--------+----------------------+------+------+---------------------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------+----------------------+------+------+---------------------+---------------+ +| host | String | PRI | YES | | TAG | +| ts | TimestampMillisecond | PRI | NO | current_timestamp() | TIMESTAMP | +| cpu | Float64 | | YES | 0 | FIELD | +| memory | Float64 | | YES | | FIELD | ++--------+----------------------+------+------+---------------------+---------------+ +4 rows in set (0.00 sec) +``` + +结果中展示相应的表结构: + +* `Column`: 列名 +* `Type`: 列类型 +* `Key`: `PRI` 表示该列在 `PRIMARY KEY` 约束里。 +* `Null`: `YES` 表示可以为空,否则为 `NO` +* `Default`: 列的默认值 +* `Semantic Type`:该列的语义类型,对应数据模型中的 `TAG`、`FIELD` 或 `TIMESTAMP`。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/distinct.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/distinct.md new file mode 100644 index 0000000000..a5f7afea9a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/distinct.md @@ -0,0 +1,23 @@ +--- +keywords: [SQL DISTINCT 语句, 唯一值选择, 数据去重, SQL 示例, 数据分析] +description: SELECT DISTINCT 用于从一组数据中选择唯一值,可以与过滤条件结合使用。 +--- + +# DISTINCT + +`SELECT DISTINCT` 用于从一组数据中选择唯一值,从查询的输出中返回唯一值,其基本语法如下: + +```sql +SELECT DISTINCT idc +FROM system_metrics; +``` + +`SELECT DISTINCT` 可以与 filter 结合使用: + +```sql +SELECT DISTINCT idc, host +FROM system_metrics +WHERE host != 'host2'; +``` + +`SELECT DISTINCT` 是 GreptimeDB SQL 中一个简单但功能强大的命令,它允许用户将数据压缩成唯一值的综合。它可以用于一个或多个列,使其在数据分析和报告中非常灵活。使用 `SELECT DISTINCT` 是获取表中存储的数据类型概述的好方法。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/drop.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/drop.md new file mode 100644 index 0000000000..101df13be8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/drop.md @@ -0,0 +1,99 @@ +--- +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; +``` + +## DROP 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) +``` + +## DROP 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) +``` + +## DROP TRIGGER + +请参考 [Trigger 语法](/reference/sql/trigger-syntax.md#drop-trigger)文档。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/explain.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/explain.md new file mode 100644 index 0000000000..408c4a5be1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/explain.md @@ -0,0 +1,95 @@ +--- +keywords: [SQL EXPLAIN 语句, 执行计划, 查询优化, ANALYZE 子句, SQL 示例] +description: EXPLAIN 用于提供语句的执行计划,ANALYZE 子句将执行语句并测量每个计划节点的时间和输出行数。 +--- + +# EXPLAIN + +`EXPLAIN` 用于提供语句的执行计划。 + +## Syntax + +```sql +EXPLAIN [ANALYZE] [VERBOSE] SELECT ... +``` + +`ANALYZE` 子句将执行语句并测量每个计划节点花费的时间以及输出的总行数等。 + +`VERBOSE` 子句可以进一步提供执行计划时详细的信息。 + +## 示例 + +Explain 以下的查询: + +```sql +EXPLAIN SELECT * FROM monitor where host='host1'\G +``` + +样例输出: + +```sql +*************************** 1. row *************************** +plan_type: logical_plan + plan: MergeScan [is_placeholder=false] +*************************** 2. row *************************** +plan_type: physical_plan + plan: MergeScanExec: peers=[4612794875904(1074, 0), ] +``` + +`plan_type` 列指示了是 `logical_plan` 还是 `physical_plan`,`plan` 列详细说明了执行计划。 + +`MergeScan` 计划负责合并多个 region 的查询结果。物理计划 `MergeScanExec` 中的 `peers` 数组包含了将要扫描的 region 的 ID。 + +使用 `ANALYZE` 解释执行计划: + +```sql +EXPLAIN ANALYZE SELECT * FROM monitor where host='host1'\G +``` + +样例输出: + +```sql +*************************** 1. row *************************** +stage: 0 + node: 0 + plan: MergeScanExec: peers=[4612794875904(1074, 0), ] metrics=[output_rows: 0, greptime_exec_read_cost: 0, finish_time: 3301415, first_consume_time: 3299166, ready_time: 3104209, ] + +*************************** 2. row *************************** +stage: 1 + node: 0 + plan: SeqScan: region=4612794875904(1074, 0), partition_count=0 (0 memtable ranges, 0 file 0 ranges) metrics=[output_rows: 0, mem_used: 0, build_parts_cost: 1, build_reader_cost: 1, elapsed_await: 1, elapsed_poll: 21250, scan_cost: 1, yield_cost: 1, ] + +*************************** 3. row *************************** +stage: NULL + node: NULL + plan: Total rows: 0 +``` + +`EXPLAIN ANALYZE` 语句提供了每个执行阶段的指标。`SeqScan` 计划会扫描一个 region 的数据。 + +获取查询执行更详细的信息: + +```sql +EXPLAIN ANALYZE VERBOSE SELECT * FROM monitor where host='host1'; +``` + +样例输出: + +```sql +*************************** 1. row *************************** +stage: 0 + node: 0 + plan: MergeScanExec: peers=[4612794875904(1074, 0), ] metrics=[output_rows: 0, greptime_exec_read_cost: 0, finish_time: 3479084, first_consume_time: 3476000, ready_time: 3209041, ] + +*************************** 2. row *************************** +stage: 1 + node: 0 + plan: SeqScan: region=4612794875904(1074, 0), partition_count=0 (0 memtable ranges, 0 file 0 ranges), projection=["host", "ts", "cpu", "memory"], filters=[host = Utf8("host1")], metrics_per_partition: [[partition=0, {prepare_scan_cost=579.75µs, build_reader_cost=0ns, scan_cost=0ns, convert_cost=0ns, yield_cost=0ns, total_cost=789.708µs, num_rows=0, num_batches=0, num_mem_ranges=0, num_file_ranges=0, build_parts_cost=0ns, rg_total=0, rg_fulltext_filtered=0, rg_inverted_filtered=0, rg_minmax_filtered=0, rg_bloom_filtered=0, rows_before_filter=0, rows_fulltext_filtered=0, rows_inverted_filtered=0, rows_bloom_filtered=0, rows_precise_filtered=0, num_sst_record_batches=0, num_sst_batches=0, num_sst_rows=0, first_poll=785.041µs}]] metrics=[output_rows: 0, mem_used: 0, build_parts_cost: 1, build_reader_cost: 1, elapsed_await: 1, elapsed_poll: 17208, scan_cost: 1, yield_cost: 1, ] + +*************************** 3. row *************************** +stage: NULL + node: NULL + plan: Total rows: 0 +``` + +`EXPLAIN ANALYZE VERBOSE` 语句会展示计划执行阶段更详细的指标信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/approximate.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/approximate.md new file mode 100644 index 0000000000..6ade634657 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/approximate.md @@ -0,0 +1,265 @@ +--- +keywords: [近似函数, 近似去重计数, 近似分位数, SQL 函数] +description: 列出和描述 GreptimeDB 中可用的近似函数,包括它们的用法和示例。 +--- + +# 近似函数 + +本页面列出了 GreptimeDB 中的近似函数,这些函数用于近似数据分析。 + +:::warning +下述的近似函数目前仍处于实验阶段,可能会在未来的版本中发生变化。 +::: + +## 近似去重计数 (HLL) + +这里使用了 [HyperLogLog](https://algo.inria.fr/flajolet/Publications/FlFuGaMe07.pdf) (HLL) 算法来计算一组值的近似去重计数。它在内存使用和速度方面提供了高效的性能。GreptimeDB 提供了三个函数来处理 HLL 算法,具体描述如下: + +:::warning +由于算法的近似性质,结果可能不完全精确,但通常非常接近实际的去重计数。HyperLogLog 算法的相对标准误差约为 1.04/√m,其中 m 是算法中使用的寄存器数量。GreptimeDB 默认使用 16384 个寄存器,这使得相对标准误差约为 0.008125(即 0.8125%)。 +::: + +### `hll` + +`hll(value)` 从给定列创建二进制的 HyperLogLog 状态。`value` 可以是你希望计算近似去重计数的任何列。它返回 HLL 状态的二进制表示,可以存储在表中或用于进一步计算。有关如何结合其他函数使用此函数计算近似去重计数的完整示例,请参阅 [完整使用示例](#完整使用示例)。 + +### `hll_merge` + +`hll_merge(hll_state)` 将多个 HyperLogLog 状态合并为一个。当你需要合并多个 HLL 计算结果时,例如聚合来自不同时间窗口或来源的数据时,这非常有用。`hll_state` 参数是由 [`hll`](#hll) 创建的 HLL 状态的二进制表示。合并后的状态可用于计算所有合并状态的近似去重计数。有关如何结合其他函数使用此函数计算近似去重计数的完整示例,请参阅 [完整使用示例](#完整使用示例)。 + + +### `hll_count` + +`hll_count(hll_state)` 从 HyperLogLog 状态中计算得到近似去重计数的结果。此函数接受由 `hll` 创建或由 `hll_merge` 合并的 HLL 状态,并返回近似的去重值计数。有关如何结合其他函数使用此函数计算近似去重计数的完整示例,请参阅 [完整使用示例](#完整使用示例)。 + +### 完整使用示例 + +此示例演示了如何组合使用这些函数来计算近似的去重的用户 ID 的数量。 + +首先创建用于存储用户访问日志的基础表 `access_log`,以及用于在 10 秒时间窗口内存储 HyperLogLog 状态的 `access_log_10s` 表。请注意,`state` 列的类型为 `BINARY`,它将以二进制格式存储 HyperLogLog 状态。 +```sql +CREATE TABLE access_log ( + `url` STRING, + user_id BIGINT, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY (`url`, `user_id`) +); + +CREATE TABLE access_log_10s ( + `url` STRING, + time_window timestamp time INDEX, + state BINARY, + PRIMARY KEY (`url`) +); +``` + +将一些示例数据插入到 `access_log` 中: +```sql +INSERT INTO access_log VALUES + ("/dashboard", 1, "2025-03-04 00:00:00"), + ("/dashboard", 1, "2025-03-04 00:00:01"), + ("/dashboard", 2, "2025-03-04 00:00:05"), + ("/dashboard", 2, "2025-03-04 00:00:10"), + ("/dashboard", 2, "2025-03-04 00:00:13"), + ("/dashboard", 4, "2025-03-04 00:00:15"), + ("/not_found", 1, "2025-03-04 00:00:10"), + ("/not_found", 3, "2025-03-04 00:00:11"), + ("/not_found", 4, "2025-03-04 00:00:12"); +``` + +现在我们可以使用 `hll` 函数为 `user_id` 列创建 10 秒时间窗口的 HyperLogLog 状态。输出将是 HLL 状态的二进制表示,其中包含计算后续近似去重计数所需的信息。`date_bin` 函数用于将数据分组到 10 秒的时间窗口中。因此,此 `INSERT INTO` 语句将为 `access_log` 表中每个 10 秒时间窗口创建 HyperLogLog 状态,并将其插入到 `access_log_10s` 表中: +```sql +-- 使用 10 秒窗口查询来计算 HyperLogLog 状态: +INSERT INTO + access_log_10s +SELECT + `url`, + date_bin("10s" :: INTERVAL, ts) AS time_window, + hll(`user_id`) AS state +FROM + access_log +GROUP BY + `url`, + time_window; +-- 结果类似: +-- Query OK, 3 rows affected (0.05 sec) +``` +然后我们可以使用 `hll_count` 函数从 HyperLogLog 状态(即 `state` 列)中检索近似去重计数。例如,要获取每个 10 秒时间窗口的用户访问近似去重计数,我们可以运行以下查询: +```sql +-- 使用 `hll_count` 查询 `access_log_10s` 中的近似数据,请注意对于小型数据集,结果可能不是很准确。 +SELECT `url`, `time_window`, hll_count(state) FROM access_log_10s; + +-- 结果如下: +-- +------------+---------------------+---------------------------------+ +-- | url | time_window | hll_count(access_log_10s.state) | +-- +------------+---------------------+---------------------------------+ +-- | /dashboard | 2025-03-04 00:00:00 | 2 | +-- | /dashboard | 2025-03-04 00:00:10 | 2 | +-- | /not_found | 2025-03-04 00:00:10 | 3 | +-- +------------+---------------------+---------------------------------+ +``` + +此外,我们可以通过使用 `hll_merge` 合并 HyperLogLog 状态,将 10 秒的数据聚合到 1 分钟级别。这使我们能够计算更大时间窗口的近似去重计数,这对于分析随时间变化的趋势非常有用。以下查询演示了如何实现: +```sql +-- 使用 `hll_merge` 合并 HyperLogLog 状态,将 10 秒的数据聚合到 1 分钟级别。 +SELECT + `url`, + date_bin('1 minute' :: INTERVAL, `time_window`) AS time_window_1m, + hll_count(hll_merge(state)) as uv_per_min +FROM + access_log_10s +GROUP BY + `url`, + date_bin('1 minute' :: INTERVAL, `time_window`); + +-- 结果如下: +-- +------------+---------------------+------------+ +-- | url | time_window_1m | uv_per_min | +-- +------------+---------------------+------------+ +-- | /dashboard | 2025-03-04 00:00:00 | 3 | +-- | /not_found | 2025-03-04 00:00:00 | 3 | +-- +------------+---------------------+------------+ +``` + +请注意 `hll_merge` 函数如何用于合并 `access_log_10s` 表中的 HyperLogLog 状态,然后 `hll_count` 函数用于计算每个 1 分钟时间窗口的近似去重计数。如果只使用 `hll_merge` 而不使用 `hll_count`,结果将只是合并后的 HyperLogLog 状态的不可读二进制表示,这对于分析没有太大用处。因此,我们使用 `hll_count` 从合并后的状态中计算得到近似去重计数。 + +以下流程图说明了 HyperLogLog 函数的上述用法。首先,原始事件数据按时间窗口和 URL 分组,然后使用 `hll` 函数为每个时间窗口和 URL 创建一个 HyperLogLog 状态,接着使用 `hll_count` 函数检索每个时间窗口和 URL 的近似去重计数。最后,使用 `hll_merge` 函数合并每个 URL 的 HyperLogLog 状态,然后再次使用 `hll_count` 函数检索 1 分钟时间窗口的近似去重计数。 +![HLL 用例流程图](/hll.svg) + +## 近似分位数(UDDSketch) + +使用 [UDDSketch](https://arxiv.org/abs/2004.08604) 算法提供了三个函数用于近似分位数计算。 + +:::warning +UDDSketch 算法旨在提供具有可调误差率的近似分位数,这有助于实现高效的内存使用和快速计算。结果可能并非完全精确,但通常非常接近实际分位数。 +::: + +### `uddsketch_state` + +`uddsketch_state` 函数用于从给定列创建二进制格式的 UDDSketch 状态。它接受三个参数: +- `bucket_num`:用于记录分位数信息的桶数量。关于如何确定该值,请参阅[如何确定桶数量和误差率](#如何确定桶数量和误差率)。 +- `error_rate`:分位数计算所需的误差率。 +- `value`:用于计算分位数的列。 + +例如,对于下述表 `percentile_base`,我们可以为 `value` 列创建一个 `uddsketch_state`,其中桶数量为 128,误差率为 0.01 (1%)。输出将是 UDDSketch 状态的二进制表示,其中包含后续计算近似分位数所需的信息。 + +该输出的二进制状态可被视为 `value` 列中值的直方图,后续可使用 `uddsketch_merge` 进行合并,或使用 `uddsketch_calc` 计算分位数。有关如何结合使用这些函数来计算近似分位数的完整示例,请参阅[UDDSketch 完整使用示例](#uddsketch-完整使用示例)。 + +### `uddsketch_merge` + +`uddsketch_merge` 函数用于将多个 UDDSketch 状态合并为一个。它接受三个参数: +- `bucket_num`:用于记录分位数信息的桶数量。关于如何确定该值,请参阅[如何确定桶数量和误差率](#如何确定桶数量和误差率)。 +- `error_rate`:分位数计算所需的误差率。 +- `udd_state`:由 `uddsketch_state` 创建的 UDDSketch 状态的二进制表示。 + +当你需要合并来自不同时间窗口或来源的结果时,此函数非常有用。请注意,`bucket_num` 和 `error_rate` 必须与创建原始状态时使用的参数匹配,否则合并将失败。 + +例如,如果你有来自不同时间窗口的多个 UDDSketch 状态,你可以将它们合并为一个状态,以计算所有数据的整体分位数。该输出的二进制状态随后可用于使用 `uddsketch_calc` 计算分位数。有关如何结合使用这些函数来计算近似分位数的完整示例,请参阅[UDDSketch 完整使用示例](#uddsketch-完整使用示例)。 + + +### `uddsketch_calc` + +`uddsketch_calc` 函数用于从 UDDSketch 状态计算近似分位数。它接受两个参数: +- `quantile`:一个介于 0 和 1 之间的值,表示要计算的目标分位数,例如,0.99 代表第 99 百分位数。 +- `udd_state`:由 `uddsketch_state` 创建或由 `uddsketch_merge` 合并的 UDDSketch 状态的二进制表示。 + +有关如何结合使用这些函数来计算近似分位数的完整示例,请参阅[UDDSketch 完整使用示例](#uddsketch-完整使用示例)。 + +### 如何确定桶数量和误差率 + +`bucket_num` 参数设置了 UDDSketch 算法可使用的内部容器的最大数量,直接控制其内存占用。可以将其视为跟踪不同值范围的物理存储容量。更大的 `bucket_num` 允许 UddSketch 状态更准确地表示更宽的数据动态范围(即最大值和最小值之间更大的比率)。如果此限制对于你的数据而言过小,UddSketch 状态将被迫合并非常高或非常低的值,从而降低其准确性。对于大多数用例,`bucket_num` 的推荐值为 128,这在准确性和内存使用之间提供了良好的平衡。 + +`error_rate` 定义了分位数计算所需的精度。它保证任何计算出的分位数(例如 p99)都在真实值的某个*相对*百分比范围内。例如,`error_rate` 为 `0.01` 确保结果在实际值的 1% 以内。较小的 `error_rate` 提供更高的准确性,因为它强制 UDDSketch 算法使用更细粒度的桶来区分更接近的数字。 + +这两个参数之间存在直接的权衡关系。为了达到小 `error_rate` 所承诺的高精度,UDDSketch 算法需要足够的 `bucket_num`,特别是对于跨度较大的数据。`bucket_num` 充当了精度的物理限制。如果你的 `bucket_num` 受到内存限制,那么将 `error_rate` 设置为极小值并不会提高精度,因为受到可用桶数量的限制。 + +### UDDSketch 完整使用示例 +本示例演示了如何使用上述三个 `uddsketch` 函数来计算一组值的近似分位数。 + +首先创建用于存储原始数据的基表 `percentile_base`,以及用于存储 5 秒时间窗口内 UDDSketch 状态的 `percentile_5s` 表。请注意,`percentile_state` 列的类型为 `BINARY`,它将以二进制格式存储 UDDSketch 状态。 +```sql +CREATE TABLE percentile_base ( + `id` INT PRIMARY KEY, + `value` DOUBLE, + `ts` timestamp(0) time index +); + +CREATE TABLE percentile_5s ( + `percentile_state` BINARY, + `time_window` timestamp(0) time index +); +``` + +向 `percentile_base` 插入一些示例数据: +```sql +INSERT INTO percentile_base (`id`, `value`, `ts`) VALUES + (1, 10.0, 1), + (2, 20.0, 2), + (3, 30.0, 3), + (4, 40.0, 4), + (5, 50.0, 5), + (6, 60.0, 6), + (7, 70.0, 7), + (8, 80.0, 8), + (9, 90.0, 9), + (10, 100.0, 10); +``` + +现在我们可以使用 `uddsketch_state` 函数为 `value` 列创建一个 UDDSketch 状态,其中桶数量为 128,误差率为 0.01 (1%)。输出将是 UDDSketch 状态的二进制表示,其中包含后续计算近似分位数所需的信息。`date_bin` 函数用于将数据分到 5 秒的时间窗口中。因此,此 `INSERT INTO` 语句将为 `percentile_base` 表中每个 5 秒时间窗口创建 UDDSketch 状态,并将其插入到 `percentile_5s` 表中: + +```sql +INSERT INTO + percentile_5s +SELECT + uddsketch_state(128, 0.01, `value`) AS percentile_state, + date_bin('5 seconds' :: INTERVAL, `ts`) AS time_window +FROM + percentile_base +GROUP BY + time_window; +-- 结果类似: +-- Query OK, 3 rows affected (0.05 sec) +``` + +现在我们可以使用 `uddsketch_calc` 函数从 UDDSketch 状态中计算近似分位数。例如,要获取每个 5 秒时间窗口的近似第 99 百分位数 (p99),我们可以运行以下查询: +```sql +-- 查询 percentile_5s 以获取近似第 99 百分位数 +SELECT + time_window, + uddsketch_calc(0.99, `percentile_state`) AS p99 +FROM + percentile_5s; + +-- 结果如下: +-- +---------------------+--------------------+ +-- | time_window | p99 | +-- +---------------------+--------------------+ +-- | 1970-01-01 00:00:00 | 40.04777053326359 | +-- | 1970-01-01 00:00:05 | 89.13032933635911 | +-- | 1970-01-01 00:00:10 | 100.49456770856492 | +-- +---------------------+--------------------+ +``` +请注意,在上述查询中,`percentile_state` 列是由 `uddsketch_state` 创建的 UDDSketch 状态。 + +此外,我们可以通过使用 `uddsketch_merge` 合并 UDDSketch 状态,将 5 秒的数据聚合到 1 分钟级别。这使我们能够计算更大时间窗口的近似分位数,这对于分析随时间变化的趋势非常有用。以下查询演示了如何实现: +```sql +-- 此外,我们可以通过使用 `uddsketch_merge` 合并 UDDSketch 状态,将 5 秒的数据聚合到 1 分钟级别。 +SELECT + date_bin('1 minute' :: INTERVAL, `time_window`) AS time_window_1m, + uddsketch_calc(0.99, uddsketch_merge(128, 0.01, `percentile_state`)) AS p99 +FROM + percentile_5s +GROUP BY + time_window_1m; + +-- 结果如下: +-- +---------------------+--------------------+ +-- | time_window_1m | p99 | +-- +---------------------+--------------------+ +-- | 1970-01-01 00:00:00 | 100.49456770856492 | +-- +---------------------+--------------------+ +``` +请注意 `uddsketch_merge` 函数是如何用于合并 `percentile_5s` 表中的 UDDSketch 状态,然后 `uddsketch_calc` 函数用于计算每个 1 分钟时间窗口的近似第 99 百分位数 (p99)。 + +以下流程图说明了 UDDSketch 函数的上述用法。首先,原始事件数据按时间窗口分组,然后使用 `uddsketch_state` 函数为每个时间窗口创建一个 UDDSketch 状态,接着使用 `uddsketch_calc` 函数检索每个时间窗口的近似第 99 分位数。最后,使用 `uddsketch_merge` 函数合并每个时间窗口的 UDDSketch 状态,然后再次使用 `uddsketch_calc` 函数检索 1 分钟时间窗口的近似第 99 分位数。 +![UDDSketch 用例流程图](/udd.svg) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/df-functions.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/df-functions.md new file mode 100644 index 0000000000..f69beb3e59 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/df-functions.md @@ -0,0 +1,5812 @@ +--- +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. + +### Math Functions + +- [abs](#abs) +- [acos](#acos) +- [acosh](#acosh) +- [asin](#asin) +- [asinh](#asinh) +- [atan](#atan) +- [atan2](#atan2) +- [atanh](#atanh) +- [cbrt](#cbrt) +- [ceil](#ceil) +- [cos](#cos) +- [cosh](#cosh) +- [cot](#cot) +- [degrees](#degrees) +- [exp](#exp) +- [factorial](#factorial) +- [floor](#floor) +- [gcd](#gcd) +- [isnan](#isnan) +- [iszero](#iszero) +- [lcm](#lcm) +- [ln](#ln) +- [log](#log) +- [log10](#log10) +- [log2](#log2) +- [nanvl](#nanvl) +- [pi](#pi) +- [pow](#pow) +- [power](#power) +- [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. + +```sql +abs(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `acos` + +Returns the arc cosine or inverse cosine of a number. + +```sql +acos(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `acosh` + +Returns the area hyperbolic cosine or inverse hyperbolic cosine of a number. + +```sql +acosh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `asin` + +Returns the arc sine or inverse sine of a number. + +```sql +asin(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `asinh` + +Returns the area hyperbolic sine or inverse hyperbolic sine of a number. + +```sql +asinh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `atan` + +Returns the arc tangent or inverse tangent of a number. + +```sql +atan(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `atan2` + +Returns the arc tangent or inverse tangent of `expression_y / expression_x`. + +```sql +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. + +##### `atanh` + +Returns the area hyperbolic tangent or inverse hyperbolic tangent of a number. + +```sql +atanh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `cbrt` + +Returns the cube root of a number. + +```sql +cbrt(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `ceil` + +Returns the nearest integer greater than or equal to a number. + +```sql +ceil(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `cos` + +Returns the cosine of a number. + +```sql +cos(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `cosh` + +Returns the hyperbolic cosine of a number. + +```sql +cosh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `cot` + +Returns the cotangent of a number. + +```sql +cot(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `degrees` + +Converts radians to degrees. + +```sql +degrees(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `exp` + +Returns the base-e exponential of a number. + +```sql +exp(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `factorial` + +Factorial. Returns 1 if value is less than 2. + +```sql +factorial(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `floor` + +Returns the nearest integer less than or equal to a number. + +```sql +floor(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `gcd` + +Returns the greatest common divisor of `expression_x` and `expression_y`. Returns 0 if both inputs are zero. + +```sql +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 operators. +- **expression_y**: Second numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `isnan` + +Returns true if a given number is +NaN or -NaN otherwise returns false. + +```sql +isnan(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `iszero` + +Returns true if a given number is +0.0 or -0.0 otherwise returns false. + +```sql +iszero(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `lcm` + +Returns the least common multiple of `expression_x` and `expression_y`. Returns 0 if either input is zero. + +```sql +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 operators. +- **expression_y**: Second numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `ln` + +Returns the natural logarithm of a number. + +```sql +ln(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `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. + +```sql +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. + +##### `log10` + +Returns the base-10 logarithm of a number. + +```sql +log10(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `log2` + +Returns the base-2 logarithm of a number. + +```sql +log2(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `nanvl` + +Returns the first argument if it's not _NaN_. +Returns the second argument otherwise. + +```sql +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 π. + +```sql +pi() +``` + +##### `pow` + +_Alias of [power](#power)._ + +##### `power` + +Returns a base expression raised to the power of an exponent. + +```sql +power(base, exponent) +``` + +###### Arguments + +- **base**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **exponent**: Exponent numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Aliases + +- pow + +##### `radians` + +Converts degrees to radians. + +```sql +radians(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `random` + +Returns a random float value in the range [0, 1). +The random seed is unique to each row. + +```sql +random() +``` + +##### `round` + +Rounds a number to the nearest integer. + +```sql +round(numeric_expression[, decimal_places]) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of 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`. + +```sql +signum(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `sin` + +Returns the sine of a number. + +```sql +sin(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `sinh` + +Returns the hyperbolic sine of a number. + +```sql +sinh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `sqrt` + +Returns the square root of a number. + +```sql +sqrt(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `tan` + +Returns the tangent of a number. + +```sql +tan(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `tanh` + +Returns the hyperbolic tangent of a number. + +```sql +tanh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `trunc` + +Truncates a number to a whole number or truncated to the specified decimal places. + +```sql +trunc(numeric_expression[, decimal_places]) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of 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 + +- [coalesce](#coalesce) +- [greatest](#greatest) +- [ifnull](#ifnull) +- [least](#least) +- [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. + +```sql +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 | ++----------------------------------------+ +``` + +##### `greatest` + +Returns the greatest value in a list of expressions. Returns _null_ if all expressions are _null_. + +```sql +greatest(expression1[, ..., expression_n]) +``` + +###### Arguments + +- **expression1, expression_n**: Expressions to compare and return the greatest value.. Can be a constant, column, or function, and any combination of arithmetic operators. Pass as many expression arguments as necessary. + +###### Example + +```sql +> select greatest(4, 7, 5); ++---------------------------+ +| greatest(4,7,5) | ++---------------------------+ +| 7 | ++---------------------------+ +``` + +##### `ifnull` + +_Alias of [nvl](#nvl)._ + +##### `least` + +Returns the smallest value in a list of expressions. Returns _null_ if all expressions are _null_. + +```sql +least(expression1[, ..., expression_n]) +``` + +###### Arguments + +- **expression1, expression_n**: Expressions to compare and return the smallest value. Can be a constant, column, or function, and any combination of arithmetic operators. Pass as many expression arguments as necessary. + +###### Example + +```sql +> select least(4, 7, 5); ++---------------------------+ +| least(4,7,5) | ++---------------------------+ +| 4 | ++---------------------------+ +``` + +##### `nullif` + +Returns _null_ if _expression1_ equals _expression2_; otherwise it returns _expression1_. +This can be used to perform the inverse operation of [`coalesce`](#coalesce). + +```sql +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_. + +```sql +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_. + +```sql +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) +- [overlay](#overlay) +- [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. + +```sql +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. + +```sql +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. + +```sql +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 | ++-------------------------------------------+ +``` + +###### Alternative Syntax + +```sql +trim(BOTH trim_str FROM str) +``` + +```sql +trim(trim_str FROM str) +``` + +###### 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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +###### 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). + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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___ | ++-------------------------------------------+ +``` + +###### Alternative Syntax + +```sql +trim(LEADING trim_str FROM str) +``` + +**Related functions**: + +- [btrim](#btrim) +- [rtrim](#rtrim) + +##### `octet_length` + +Returns the length of a string in bytes. + +```sql +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) + +##### `overlay` + +Returns the string which is replaced by another string from the specified position and specified count length. + +```sql +overlay(str PLACING substr FROM pos [FOR count]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **substr**: Substring to replace in str. +- **pos**: The start position to start the replace in str. +- **count**: The count of characters to be replaced from start position of str. If not specified, will use substr length instead. + +###### Example + +```sql +> select overlay('Txxxxas' placing 'hom' from 2 for 4); ++--------------------------------------------------------+ +| overlay(Utf8("Txxxxas"),Utf8("hom"),Int64(2),Int64(4)) | ++--------------------------------------------------------+ +| Thomas | ++--------------------------------------------------------+ +``` + +##### `position` + +_Alias of [strpos](#strpos)._ + +##### `repeat` + +Returns a string with an input string repeated a specified number. + +```sql +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. + +```sql +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 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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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 | ++-------------------------------------------+ +``` + +###### Alternative Syntax + +```sql +trim(TRAILING trim_str FROM str) +``` + +**Related functions**: + +- [btrim](#btrim) +- [ltrim](#ltrim) + +##### `split_part` + +Splits a string based on a specified delimiter and returns the substring in the specified position. + +```sql +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. + +```sql +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. + +```sql +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 | ++----------------------------------------+ +``` + +###### Alternative Syntax + +```sql +position(substr in origstr) +``` + +###### Aliases + +- instr +- position + +##### `substr` + +Extracts a substring of a specified number of characters from a specific starting position in a string. + +```sql +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 | ++----------------------------------------------+ +``` + +###### Alternative Syntax + +```sql +substring(str from start_pos for length) +``` + +###### 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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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_count](#regexp_count) +- [regexp_like](#regexp_like) +- [regexp_match](#regexp_match) +- [regexp_replace](#regexp_replace) + +##### `regexp_count` + +Returns the number of matches that a [regular expression](https://docs.rs/regex/latest/regex/#syntax) has in a string. + +```sql +regexp_count(str, regexp[, start, 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. +- **start**: - **start**: Optional start position (the first position is 1) to search for the regular expression. 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_count('abcAbAbc', 'abc', 2, 'i'); ++---------------------------------------------------------------+ +| regexp_count(Utf8("abcAbAbc"),Utf8("abc"),Int64(2),Utf8("i")) | ++---------------------------------------------------------------+ +| 1 | ++---------------------------------------------------------------+ +``` + +##### `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. + +```sql +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 the first [regular expression](https://docs.rs/regex/latest/regex/#syntax) matches in a string. + +```sql +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). + +```sql +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 + +- [current_date](#current_date) +- [current_time](#current_time) +- [current_timestamp](#current_timestamp) +- [date_bin](#date_bin) +- [date_format](#date_format) +- [date_part](#date_part) +- [date_trunc](#date_trunc) +- [datepart](#datepart) +- [datetrunc](#datetrunc) +- [from_unixtime](#from_unixtime) +- [make_date](#make_date) +- [now](#now) +- [to_char](#to_char) +- [to_date](#to_date) +- [to_local_time](#to_local_time) +- [to_timestamp](#to_timestamp) +- [to_timestamp_micros](#to_timestamp_micros) +- [to_timestamp_millis](#to_timestamp_millis) +- [to_timestamp_nanos](#to_timestamp_nanos) +- [to_timestamp_seconds](#to_timestamp_seconds) +- [to_unixtime](#to_unixtime) +- [today](#today) + +##### `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. + +```sql +current_date() +``` + +###### Aliases + +- today + +##### `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. + +```sql +current_time() +``` + +##### `current_timestamp` + +_Alias of [now](#now)._ + +##### `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`. + +```sql +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 + +###### Example + +```sql +-- Bin the timestamp into 1 day intervals +> SELECT date_bin(interval '1 day', time) as bin +FROM VALUES ('2023-01-01T18:18:18Z'), ('2023-01-03T19:00:03Z') t(time); ++---------------------+ +| bin | ++---------------------+ +| 2023-01-01T00:00:00 | +| 2023-01-03T00:00:00 | ++---------------------+ +2 row(s) fetched. + +-- Bin the timestamp into 1 day intervals starting at 3AM on 2023-01-01 +> SELECT date_bin(interval '1 day', time, '2023-01-01T03:00:00') as bin +FROM VALUES ('2023-01-01T18:18:18Z'), ('2023-01-03T19:00:03Z') t(time); ++---------------------+ +| bin | ++---------------------+ +| 2023-01-01T03:00:00 | +| 2023-01-03T03:00:00 | ++---------------------+ +2 row(s) fetched. +``` + +##### `date_format` + +_Alias of [to_char](#to_char)._ + +##### `date_part` + +Returns the specified part of the date as an integer. + +```sql +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. + +###### Alternative Syntax + +```sql +extract(field FROM source) +``` + +###### Aliases + +- datepart + +##### `date_trunc` + +Truncates a timestamp value to a specified precision. + +```sql +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 + +##### `datepart` + +_Alias of [date_part](#date_part)._ + +##### `datetrunc` + +_Alias of [date_trunc](#date_trunc)._ + +##### `from_unixtime` + +Converts an integer to RFC3339 timestamp format (`YYYY-MM-DDT00:00:00.000000000Z`). Integers and unsigned integers are interpreted as seconds since the unix epoch (`1970-01-01T00:00:00Z`) return the corresponding timestamp. + +```sql +from_unixtime(expression[, timezone]) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **timezone**: Optional timezone to use when converting the integer to a timestamp. If not provided, the default timezone is UTC. + +###### Example + +```sql +> select from_unixtime(1599572549, 'America/New_York'); ++-----------------------------------------------------------+ +| from_unixtime(Int64(1599572549),Utf8("America/New_York")) | ++-----------------------------------------------------------+ +| 2020-09-08T09:42:29-04:00 | ++-----------------------------------------------------------+ +``` + +##### `make_date` + +Make a date from year/month/day component parts. + +```sql +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 + +```sql +> 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) + +##### `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. + +```sql +now() +``` + +###### Aliases + +- current_timestamp + +##### `to_char` + +Returns a string representation of a date, time, timestamp or duration based on a [Chrono format](https://docs.rs/chrono/latest/chrono/format/strftime/index.html). Unlike the PostgreSQL equivalent of this function numerical formatting is not supported. + +```sql +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](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) string to use to convert the expression. +- **day**: Day to use when making the date. Can be a constant, column or function, and any combination of arithmetic operators. + +###### Example + +```sql +> 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](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/to_char.rs) + +###### Aliases + +- date_format + +##### `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`. + +```sql +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) + +##### `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. + +```sql +to_local_time(expression) +``` + +###### Arguments + +- **expression**: Time expression to operate on. Can be a constant, column, or function. + +###### Example + +```sql +> 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. + +```sql +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](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_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_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](https://docs.rs/chrono/latest/chrono/format/strftime/index.html)s are provided. Integers and unsigned integers are interpreted as microseconds since the unix epoch (`1970-01-01T00:00:00Z`) Returns the corresponding timestamp. + +```sql +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](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_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_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 formats](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) are provided. Integers and unsigned integers are interpreted as milliseconds since the unix epoch (`1970-01-01T00:00:00Z`). Returns the corresponding timestamp. + +```sql +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](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_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_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](https://docs.rs/chrono/latest/chrono/format/strftime/index.html)s are provided. Integers and unsigned integers are interpreted as nanoseconds since the unix epoch (`1970-01-01T00:00:00Z`). Returns the corresponding timestamp. + +```sql +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](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_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](https://docs.rs/chrono/latest/chrono/format/strftime/index.html)s are provided. Integers and unsigned integers are interpreted as seconds since the unix epoch (`1970-01-01T00:00:00Z`). Returns the corresponding timestamp. + +```sql +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](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_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) + +##### `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](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) are provided. + +```sql +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](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_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 | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +##### `today` + +_Alias of [current_date](#current_date)._ + +### Array Functions + +- [array_any_value](#array_any_value) +- [array_append](#array_append) +- [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_element](#array_element) +- [array_empty](#array_empty) +- [array_except](#array_except) +- [array_extract](#array_extract) +- [array_has](#array_has) +- [array_has_all](#array_has_all) +- [array_has_any](#array_has_any) +- [array_indexof](#array_indexof) +- [array_intersect](#array_intersect) +- [array_join](#array_join) +- [array_length](#array_length) +- [array_max](#array_max) +- [array_ndims](#array_ndims) +- [array_pop_back](#array_pop_back) +- [array_pop_front](#array_pop_front) +- [array_position](#array_position) +- [array_positions](#array_positions) +- [array_prepend](#array_prepend) +- [array_push_back](#array_push_back) +- [array_push_front](#array_push_front) +- [array_remove](#array_remove) +- [array_remove_all](#array_remove_all) +- [array_remove_n](#array_remove_n) +- [array_repeat](#array_repeat) +- [array_replace](#array_replace) +- [array_replace_all](#array_replace_all) +- [array_replace_n](#array_replace_n) +- [array_resize](#array_resize) +- [array_reverse](#array_reverse) +- [array_slice](#array_slice) +- [array_sort](#array_sort) +- [array_to_string](#array_to_string) +- [array_union](#array_union) +- [arrays_overlap](#arrays_overlap) +- [cardinality](#cardinality) +- [empty](#empty) +- [flatten](#flatten) +- [generate_series](#generate_series) +- [list_any_value](#list_any_value) +- [list_append](#list_append) +- [list_cat](#list_cat) +- [list_concat](#list_concat) +- [list_contains](#list_contains) +- [list_dims](#list_dims) +- [list_distance](#list_distance) +- [list_distinct](#list_distinct) +- [list_element](#list_element) +- [list_empty](#list_empty) +- [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_max](#list_max) +- [list_ndims](#list_ndims) +- [list_pop_back](#list_pop_back) +- [list_pop_front](#list_pop_front) +- [list_position](#list_position) +- [list_positions](#list_positions) +- [list_prepend](#list_prepend) +- [list_push_back](#list_push_back) +- [list_push_front](#list_push_front) +- [list_remove](#list_remove) +- [list_remove_all](#list_remove_all) +- [list_remove_n](#list_remove_n) +- [list_repeat](#list_repeat) +- [list_replace](#list_replace) +- [list_replace_all](#list_replace_all) +- [list_replace_n](#list_replace_n) +- [list_resize](#list_resize) +- [list_reverse](#list_reverse) +- [list_slice](#list_slice) +- [list_sort](#list_sort) +- [list_to_string](#list_to_string) +- [list_union](#list_union) +- [make_array](#make_array) +- [make_list](#make_list) +- [range](#range) +- [string_to_array](#string_to_array) +- [string_to_list](#string_to_list) + +##### `array_any_value` + +Returns the first non-null element in the array. + +```sql +array_any_value(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select array_any_value([NULL, 1, 2, 3]); ++-------------------------------+ +| array_any_value(List([NULL,1,2,3])) | ++-------------------------------------+ +| 1 | ++-------------------------------------+ +``` + +###### Aliases + +- list_any_value + +##### `array_append` + +Appends an element to the end of an array. + +```sql +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 + +```sql +> select array_append([1, 2, 3], 4); ++--------------------------------------+ +| array_append(List([1,2,3]),Int64(4)) | ++--------------------------------------+ +| [1, 2, 3, 4] | ++--------------------------------------+ +``` + +###### Aliases + +- list_append +- array_push_back +- list_push_back + +##### `array_cat` + +_Alias of [array_concat](#array_concat)._ + +##### `array_concat` + +Concatenates arrays. + +```sql +array_concat(array[, ..., array_n]) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. +- **array_n**: Subsequent array column or literal array to concatenate. + +###### Example + +```sql +> 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_concat +- list_cat + +##### `array_contains` + +_Alias of [array_has](#array_has)._ + +##### `array_dims` + +Returns an array of the array's dimensions. + +```sql +array_dims(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> 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. + +```sql +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 + +```sql +> 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. + +```sql +array_distinct(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> 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. + +```sql +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 + +```sql +> 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_empty` + +_Alias of [empty](#empty)._ + +##### `array_except` + +Returns an array of the elements that appear in the first array but not in the second. + +```sql +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 + +```sql +> 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 + +##### `array_extract` + +_Alias of [array_element](#array_element)._ + +##### `array_has` + +Returns true if the array contains the element. + +```sql +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. + +###### Example + +```sql +> select array_has([1, 2, 3], 2); ++-----------------------------+ +| array_has(List([1,2,3]), 2) | ++-----------------------------+ +| true | ++-----------------------------+ +``` + +###### Aliases + +- list_has +- array_contains +- list_contains + +##### `array_has_all` + +Returns true if all elements of sub-array exist in array. + +```sql +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. + +###### Example + +```sql +> select array_has_all([1, 2, 3, 4], [2, 3]); ++--------------------------------------------+ +| array_has_all(List([1,2,3,4]), List([2,3])) | ++--------------------------------------------+ +| true | ++--------------------------------------------+ +``` + +###### Aliases + +- list_has_all + +##### `array_has_any` + +Returns true if any elements exist in both arrays. + +```sql +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. + +###### Example + +```sql +> select array_has_any([1, 2, 3], [3, 4]); ++------------------------------------------+ +| array_has_any(List([1,2,3]), List([3,4])) | ++------------------------------------------+ +| true | ++------------------------------------------+ +``` + +###### Aliases + +- list_has_any +- arrays_overlap + +##### `array_indexof` + +_Alias of [array_position](#array_position)._ + +##### `array_intersect` + +Returns an array of elements in the intersection of array1 and array2. + +```sql +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 + +```sql +> 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. + +```sql +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 + +```sql +> select array_length([1, 2, 3, 4, 5], 1); ++-------------------------------------------+ +| array_length(List([1,2,3,4,5]), 1) | ++-------------------------------------------+ +| 5 | ++-------------------------------------------+ +``` + +###### Aliases + +- list_length + +##### `array_max` + +Returns the maximum value in the array. + +```sql +array_max(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select array_max([3,1,4,2]); ++-----------------------------------------+ +| array_max(List([3,1,4,2])) | ++-----------------------------------------+ +| 4 | ++-----------------------------------------+ +``` + +###### Aliases + +- list_max + +##### `array_ndims` + +Returns the number of dimensions of the array. + +```sql +array_ndims(array, element) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. +- **element**: Array element. + +###### Example + +```sql +> select array_ndims([[1, 2, 3], [4, 5, 6]]); ++----------------------------------+ +| array_ndims(List([1,2,3,4,5,6])) | ++----------------------------------+ +| 2 | ++----------------------------------+ +``` + +###### Aliases + +- list_ndims + +##### `array_pop_back` + +Returns the array without the last element. + +```sql +array_pop_back(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select array_pop_back([1, 2, 3]); ++-------------------------------+ +| array_pop_back(List([1,2,3])) | ++-------------------------------+ +| [1, 2] | ++-------------------------------+ +``` + +###### Aliases + +- list_pop_back + +##### `array_pop_front` + +Returns the array without the first element. + +```sql +array_pop_front(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select array_pop_front([1, 2, 3]); ++-------------------------------+ +| array_pop_front(List([1,2,3])) | ++-------------------------------+ +| [2, 3] | ++-------------------------------+ +``` + +###### Aliases + +- list_pop_front + +##### `array_position` + +Returns the position of the first occurrence of the specified element in the array. + +```sql +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 + +```sql +> select array_position([1, 2, 2, 3, 1, 4], 2); ++----------------------------------------------+ +| array_position(List([1,2,2,3,1,4]),Int64(2)) | ++----------------------------------------------+ +| 2 | ++----------------------------------------------+ +> select array_position([1, 2, 2, 3, 1, 4], 2, 3); ++----------------------------------------------------+ +| array_position(List([1,2,2,3,1,4]),Int64(2), Int64(3)) | ++----------------------------------------------------+ +| 3 | ++----------------------------------------------------+ +``` + +###### Aliases + +- list_position +- array_indexof +- list_indexof + +##### `array_positions` + +Searches for an element in the array, returns all occurrences. + +```sql +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 position in the array. + +###### Example + +```sql +> 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_prepend` + +Prepends an element to the beginning of an array. + +```sql +array_prepend(element, array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. +- **element**: Element to prepend to the array. + +###### Example + +```sql +> select array_prepend(1, [2, 3, 4]); ++---------------------------------------+ +| array_prepend(Int64(1),List([2,3,4])) | ++---------------------------------------+ +| [1, 2, 3, 4] | ++---------------------------------------+ +``` + +###### Aliases + +- list_prepend +- array_push_front +- list_push_front + +##### `array_push_back` + +_Alias of [array_append](#array_append)._ + +##### `array_push_front` + +_Alias of [array_prepend](#array_prepend)._ + +##### `array_remove` + +Removes the first element from the array equal to the given value. + +```sql +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 + +```sql +> 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_all` + +Removes all elements from the array equal to the given value. + +```sql +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 + +```sql +> 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_remove_n` + +Removes the first `max` elements from the array equal to the given value. + +```sql +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 + +```sql +> 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_repeat` + +Returns an array containing element `count` times. + +```sql +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 + +```sql +> 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_replace` + +Replaces the first occurrence of the specified element with another specified element. + +```sql +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 + +```sql +> 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_all` + +Replaces all occurrences of the specified element with another specified element. + +```sql +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 + +```sql +> 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_replace_n` + +Replaces the first `max` occurrences of the specified element with another specified element. + +```sql +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 + +```sql +> 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_resize` + +Resizes the list to contain size elements. Initializes new elements with value or empty if value is not set. + +```sql +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 + +```sql +> 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_reverse` + +Returns the array with the order of the elements reversed. + +```sql +array_reverse(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> 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. + +```sql +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 + +```sql +> 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_sort` + +Sort array. + +```sql +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 + +```sql +> select array_sort([3, 1, 2]); ++-----------------------------+ +| array_sort(List([3,1,2])) | ++-----------------------------+ +| [1, 2, 3] | ++-----------------------------+ +``` + +###### Aliases + +- list_sort + +##### `array_to_string` + +Converts each element to its text representation. + +```sql +array_to_string(array, delimiter[, null_string]) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. +- **delimiter**: Array element separator. +- **null_string**: Optional. String to replace null values in the array. If not provided, nulls will be handled by default behavior. + +###### Example + +```sql +> 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 + +- list_to_string +- array_join +- list_join + +##### `array_union` + +Returns an array of elements that are present in both arrays (all elements from both arrays) with out duplicates. + +```sql +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 + +```sql +> 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 + +##### `arrays_overlap` + +_Alias of [array_has_any](#array_has_any)._ + +##### `cardinality` + +Returns the total number of elements in the array. + +```sql +cardinality(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> 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. + +```sql +empty(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select empty([1]); ++------------------+ +| empty(List([1])) | ++------------------+ +| 0 | ++------------------+ +``` + +###### Aliases + +- array_empty +- list_empty + +##### `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. + +```sql +flatten(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select flatten([[1, 2], [3, 4]]); ++------------------------------+ +| flatten(List([1,2], [3,4])) | ++------------------------------+ +| [1, 2, 3, 4] | ++------------------------------+ +``` + +##### `generate_series` + +Similar to the range function, but it includes the upper bound. + +```sql +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 + +```sql +> 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_contains` + +_Alias of [array_has](#array_has)._ + +##### `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_except](#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_intersect](#array_intersect)._ + +##### `list_join` + +_Alias of [array_to_string](#array_to_string)._ + +##### `list_length` + +_Alias of [array_length](#array_length)._ + +##### `list_max` + +_Alias of [array_max](#array_max)._ + +##### `list_ndims` + +_Alias of [array_ndims](#array_ndims)._ + +##### `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_prepend` + +_Alias of [array_prepend](#array_prepend)._ + +##### `list_push_back` + +_Alias of [array_append](#array_append)._ + +##### `list_push_front` + +_Alias of [array_prepend](#array_prepend)._ + +##### `list_remove` + +_Alias of [array_remove](#array_remove)._ + +##### `list_remove_all` + +_Alias of [array_remove_all](#array_remove_all)._ + +##### `list_remove_n` + +_Alias of [array_remove_n](#array_remove_n)._ + +##### `list_repeat` + +_Alias of [array_repeat](#array_repeat)._ + +##### `list_replace` + +_Alias of [array_replace](#array_replace)._ + +##### `list_replace_all` + +_Alias of [array_replace_all](#array_replace_all)._ + +##### `list_replace_n` + +_Alias of [array_replace_n](#array_replace_n)._ + +##### `list_resize` + +_Alias of [array_resize](#array_resize)._ + +##### `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 array using the specified input expressions. + +```sql +make_array(expression1[, ..., expression_n]) +``` + +###### 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 + +```sql +> 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)._ + +##### `range` + +Returns an Arrow array between start and stop with step. The range start..end contains all values with `start <= x < end`. It is empty if `start >= end`. Step cannot be 0. + +```sql +range(start, stop, step) +``` + +###### 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 (cannot be 0). Steps less than a day are supported only for timestamp ranges. + +###### Example + +```sql +> select range(2, 10, 3); ++-----------------------------------+ +| range(Int64(2),Int64(10),Int64(3))| ++-----------------------------------+ +| [2, 5, 8] | ++-----------------------------------+ + +> select range(DATE '1992-09-01', DATE '1993-03-01', INTERVAL '1' MONTH); ++--------------------------------------------------------------+ +| range(DATE '1992-09-01', DATE '1993-03-01', INTERVAL '1' MONTH) | ++--------------------------------------------------------------+ +| [1992-09-01, 1992-10-01, 1992-11-01, 1992-12-01, 1993-01-01, 1993-02-01] | ++--------------------------------------------------------------+ +``` + +##### `string_to_array` + +Splits a string into an array of substrings based on a delimiter. Any substrings matching the optional `null_str` argument are replaced with NULL. + +```sql +string_to_array(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`. + +###### Example + +```sql +> select string_to_array('abc##def', '##'); ++-----------------------------------+ +| string_to_array(Utf8('abc##def')) | ++-----------------------------------+ +| ['abc', 'def'] | ++-----------------------------------+ +> select string_to_array('abc def', ' ', 'def'); ++---------------------------------------------+ +| string_to_array(Utf8('abc def'), Utf8(' '), Utf8('def')) | ++---------------------------------------------+ +| ['abc', NULL] | ++---------------------------------------------+ +``` + +###### Aliases + +- string_to_list + +##### `string_to_list` + +_Alias of [string_to_array](#string_to_array)._ + +### Struct Functions + +- [named_struct](#named_struct) +- [row](#row) +- [struct](#struct) + +##### `named_struct` + +Returns an Arrow struct using the specified name and input expressions pairs. + +```sql +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. + +```sql +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 + +### Map Functions + +- [element_at](#element_at) +- [map](#map) +- [map_extract](#map_extract) +- [map_keys](#map_keys) +- [map_values](#map_values) + +##### `element_at` + +_Alias of [map_extract](#map_extract)._ + +##### `map` + +Returns an Arrow map with the specified key-value pairs. + +The `make_map` function creates a map from two lists: one for keys and one for values. Each key must be unique and non-null. + +```sql +map(key, value) +map(key: value) +make_map(['key1', 'key2'], ['value1', 'value2']) +``` + +###### Arguments + +- **key**: For `map`: Expression to be used for key. Can be a constant, column, function, or any combination of arithmetic or string operators. + For `make_map`: The list of keys to be used in the map. Each key must be unique and non-null. +- **value**: For `map`: Expression to be used for value. Can be a constant, column, function, or any combination of arithmetic or string operators. + For `make_map`: The list of values to be mapped to the corresponding keys. + +###### Example + +```sql +-- Using map function +SELECT MAP('type', 'test'); +---- +{type: test} + +SELECT MAP(['POST', 'HEAD', 'PATCH'], [41, 33, null]); +---- +{POST: 41, HEAD: 33, PATCH: NULL} + +SELECT MAP([[1,2], [3,4]], ['a', 'b']); +---- +{[1, 2]: a, [3, 4]: b} + +SELECT MAP { 'a': 1, 'b': 2 }; +---- +{a: 1, b: 2} + +-- Using make_map function +SELECT MAKE_MAP(['POST', 'HEAD'], [41, 33]); +---- +{POST: 41, HEAD: 33} + +SELECT MAKE_MAP(['key1', 'key2'], ['value1', null]); +---- +{key1: value1, key2: } +``` + +##### `map_extract` + +Returns a list containing the value for the given key or an empty list if the key is not present in the map. + +```sql +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 the previously listed. + +###### Example + +```sql +SELECT map_extract(MAP {'a': 1, 'b': NULL, 'c': 3}, 'a'); +---- +[1] + +SELECT map_extract(MAP {1: 'one', 2: 'two'}, 2); +---- +['two'] + +SELECT map_extract(MAP {'x': 10, 'y': NULL, 'z': 30}, 'y'); +---- +[] +``` + +###### Aliases + +- element_at + +##### `map_keys` + +Returns a list of all keys in the map. + +```sql +map_keys(map) +``` + +###### Arguments + +- **map**: Map expression. Can be a constant, column, or function, and any combination of map operators. + +###### Example + +```sql +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` + +Returns a list of all values in the map. + +```sql +map_values(map) +``` + +###### Arguments + +- **map**: Map expression. Can be a constant, column, or function, and any combination of map operators. + +###### Example + +```sql +SELECT map_values(MAP {'a': 1, 'b': NULL, 'c': 3}); +---- +[1, , 3] + +SELECT map_values(map([100, 5], [42, 43])); +---- +[42, 43] +``` + +### 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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +sha512(expression) +``` + +###### Arguments + +- **expression**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select sha512('foo'); ++-------------------------------------------+ +| sha512(Utf8("foo")) | ++-------------------------------------------+ +| | ++-------------------------------------------+ +``` + +### Union Functions + +Functions to work with the union data type, also know as tagged unions, variant types, enums or sum types. Note: Not related to the SQL UNION operator + +- [union_extract](#union_extract) +- [union_tag](#union_tag) + +##### `union_extract` + +Returns the value of the given field in the union when selected, or NULL otherwise. + +```sql +union_extract(union, field_name) +``` + +###### Arguments + +- **union**: Union expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **field_name**: String expression to operate on. Must be a constant. + +###### Example + +```sql +❯ select union_column, union_extract(union_column, 'a'), union_extract(union_column, 'b') from table_with_union; ++--------------+----------------------------------+----------------------------------+ +| union_column | union_extract(union_column, 'a') | union_extract(union_column, 'b') | ++--------------+----------------------------------+----------------------------------+ +| {a=1} | 1 | | +| {b=3.0} | | 3.0 | +| {a=4} | 4 | | +| {b=} | | | +| {a=} | | | ++--------------+----------------------------------+----------------------------------+ +``` + +##### `union_tag` + +Returns the name of the currently selected field in the union + +```sql +union_tag(union_expression) +``` + +###### Arguments + +- **union**: Union expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +❯ select union_column, union_tag(union_column) from table_with_union; ++--------------+-------------------------+ +| union_column | union_tag(union_column) | ++--------------+-------------------------+ +| {a=1} | a | +| {b=3.0} | b | +| {a=4} | a | +| {b=} | b | +| {a=} | a | ++--------------+-------------------------+ +``` + +### 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. + +```sql +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. + +```sql +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')`. + +```sql +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. + +```sql +version() +``` + +###### Example + +```sql +> select version(); ++--------------------------------------------+ +| version() | ++--------------------------------------------+ +| Apache DataFusion 42.0.0, aarch64 on macos | ++--------------------------------------------+ +``` +404: Not Found + + + + +## Aggregate Functions + +Aggregate functions operate on a set of values to compute a single result. + +### General Functions + +- [array_agg](#array_agg) +- [avg](#avg) +- [bit_and](#bit_and) +- [bit_or](#bit_or) +- [bit_xor](#bit_xor) +- [bool_and](#bool_and) +- [bool_or](#bool_or) +- [count](#count) +- [first_value](#first_value) +- [grouping](#grouping) +- [last_value](#last_value) +- [max](#max) +- [mean](#mean) +- [median](#median) +- [min](#min) +- [string_agg](#string_agg) +- [sum](#sum) +- [var](#var) +- [var_pop](#var_pop) +- [var_population](#var_population) +- [var_samp](#var_samp) +- [var_sample](#var_sample) + +##### `array_agg` + +Returns an array created from the expression elements. If ordering is required, elements are inserted in the specified order. +This aggregation function can only mix DISTINCT and ORDER BY if the ordering expression is exactly the same as the argument expression. + +```sql +array_agg(expression [ORDER BY expression]) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT array_agg(column_name ORDER BY other_column) FROM table_name; ++-----------------------------------------------+ +| array_agg(column_name ORDER BY other_column) | ++-----------------------------------------------+ +| [element1, element2, element3] | ++-----------------------------------------------+ +> SELECT array_agg(DISTINCT column_name ORDER BY column_name) FROM table_name; ++--------------------------------------------------------+ +| array_agg(DISTINCT column_name ORDER BY column_name) | ++--------------------------------------------------------+ +| [element1, element2, element3] | ++--------------------------------------------------------+ +``` + +##### `avg` + +Returns the average of numeric values in the specified column. + +```sql +avg(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT avg(column_name) FROM table_name; ++---------------------------+ +| avg(column_name) | ++---------------------------+ +| 42.75 | ++---------------------------+ +``` + +###### Aliases + +- mean + +##### `bit_and` + +Computes the bitwise AND of all non-null input values. + +```sql +bit_and(expression) +``` + +###### Arguments + +- **expression**: Integer expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `bit_or` + +Computes the bitwise OR of all non-null input values. + +```sql +bit_or(expression) +``` + +###### Arguments + +- **expression**: Integer expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `bit_xor` + +Computes the bitwise exclusive OR of all non-null input values. + +```sql +bit_xor(expression) +``` + +###### Arguments + +- **expression**: Integer expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `bool_and` + +Returns true if all non-null input values are true, otherwise false. + +```sql +bool_and(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT bool_and(column_name) FROM table_name; ++----------------------------+ +| bool_and(column_name) | ++----------------------------+ +| true | ++----------------------------+ +``` + +##### `bool_or` + +Returns true if all non-null input values are true, otherwise false. + +```sql +bool_and(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT bool_and(column_name) FROM table_name; ++----------------------------+ +| bool_and(column_name) | ++----------------------------+ +| true | ++----------------------------+ +``` + +##### `count` + +Returns the number of non-null values in the specified column. To include null values in the total count, use `count(*)`. + +```sql +count(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT count(column_name) FROM table_name; ++-----------------------+ +| count(column_name) | ++-----------------------+ +| 100 | ++-----------------------+ + +> SELECT count(*) FROM table_name; ++------------------+ +| count(*) | ++------------------+ +| 120 | ++------------------+ +``` + +##### `first_value` + +Returns the first element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group. + +```sql +first_value(expression [ORDER BY expression]) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT first_value(column_name ORDER BY other_column) FROM table_name; ++-----------------------------------------------+ +| first_value(column_name ORDER BY other_column)| ++-----------------------------------------------+ +| first_element | ++-----------------------------------------------+ +``` + +##### `grouping` + +Returns 1 if the data is aggregated across the specified column, or 0 if it is not aggregated in the result set. + +```sql +grouping(expression) +``` + +###### Arguments + +- **expression**: Expression to evaluate whether data is aggregated across the specified column. Can be a constant, column, or function. + +###### Example + +```sql +> SELECT column_name, GROUPING(column_name) AS group_column + FROM table_name + GROUP BY GROUPING SETS ((column_name), ()); ++-------------+-------------+ +| column_name | group_column | ++-------------+-------------+ +| value1 | 0 | +| value2 | 0 | +| NULL | 1 | ++-------------+-------------+ +``` + +##### `last_value` + +Returns the last element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group. + +```sql +last_value(expression [ORDER BY expression]) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT last_value(column_name ORDER BY other_column) FROM table_name; ++-----------------------------------------------+ +| last_value(column_name ORDER BY other_column) | ++-----------------------------------------------+ +| last_element | ++-----------------------------------------------+ +``` + +##### `max` + +Returns the maximum value in the specified column. + +```sql +max(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT max(column_name) FROM table_name; ++----------------------+ +| max(column_name) | ++----------------------+ +| 150 | ++----------------------+ +``` + +##### `mean` + +_Alias of [avg](#avg)._ + +##### `median` + +Returns the median value in the specified column. + +```sql +median(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT median(column_name) FROM table_name; ++----------------------+ +| median(column_name) | ++----------------------+ +| 45.5 | ++----------------------+ +``` + +##### `min` + +Returns the minimum value in the specified column. + +```sql +min(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT min(column_name) FROM table_name; ++----------------------+ +| min(column_name) | ++----------------------+ +| 12 | ++----------------------+ +``` + +##### `string_agg` + +Concatenates the values of string expressions and places separator values between them. If ordering is required, strings are concatenated in the specified order. This aggregation function can only mix DISTINCT and ORDER BY if the ordering expression is exactly the same as the first argument expression. + +```sql +string_agg([DISTINCT] expression, delimiter [ORDER BY expression]) +``` + +###### Arguments + +- **expression**: The string expression to concatenate. Can be a column or any valid string expression. +- **delimiter**: A literal string used as a separator between the concatenated values. + +###### Example + +```sql +> SELECT string_agg(name, ', ') AS names_list + FROM employee; ++--------------------------+ +| names_list | ++--------------------------+ +| Alice, Bob, Bob, Charlie | ++--------------------------+ +> SELECT string_agg(name, ', ' ORDER BY name DESC) AS names_list + FROM employee; ++--------------------------+ +| names_list | ++--------------------------+ +| Charlie, Bob, Bob, Alice | ++--------------------------+ +> SELECT string_agg(DISTINCT name, ', ' ORDER BY name DESC) AS names_list + FROM employee; ++--------------------------+ +| names_list | ++--------------------------+ +| Charlie, Bob, Alice | ++--------------------------+ +``` + +##### `sum` + +Returns the sum of all values in the specified column. + +```sql +sum(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT sum(column_name) FROM table_name; ++-----------------------+ +| sum(column_name) | ++-----------------------+ +| 12345 | ++-----------------------+ +``` + +##### `var` + +Returns the statistical sample variance of a set of numbers. + +```sql +var(expression) +``` + +###### Arguments + +- **expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Aliases + +- var_sample +- var_samp + +##### `var_pop` + +Returns the statistical population variance of a set of numbers. + +```sql +var_pop(expression) +``` + +###### Arguments + +- **expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Aliases + +- var_population + +##### `var_population` + +_Alias of [var_pop](#var_pop)._ + +##### `var_samp` + +_Alias of [var](#var)._ + +##### `var_sample` + +_Alias of [var](#var)._ + +### Statistical Functions + +- [corr](#corr) +- [covar](#covar) +- [covar_pop](#covar_pop) +- [covar_samp](#covar_samp) +- [nth_value](#nth_value) +- [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_sxy](#regr_sxy) +- [regr_syy](#regr_syy) +- [stddev](#stddev) +- [stddev_pop](#stddev_pop) +- [stddev_samp](#stddev_samp) + +##### `corr` + +Returns the coefficient of correlation between two numeric values. + +```sql +corr(expression1, expression2) +``` + +###### Arguments + +- **expression1**: First expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression2**: Second expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT corr(column1, column2) FROM table_name; ++--------------------------------+ +| corr(column1, column2) | ++--------------------------------+ +| 0.85 | ++--------------------------------+ +``` + +##### `covar` + +_Alias of [covar_samp](#covar_samp)._ + +##### `covar_pop` + +Returns the sample covariance of a set of number pairs. + +```sql +covar_samp(expression1, expression2) +``` + +###### Arguments + +- **expression1**: First expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression2**: Second expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT covar_samp(column1, column2) FROM table_name; ++-----------------------------------+ +| covar_samp(column1, column2) | ++-----------------------------------+ +| 8.25 | ++-----------------------------------+ +``` + +##### `covar_samp` + +Returns the sample covariance of a set of number pairs. + +```sql +covar_samp(expression1, expression2) +``` + +###### Arguments + +- **expression1**: First expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression2**: Second expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT covar_samp(column1, column2) FROM table_name; ++-----------------------------------+ +| covar_samp(column1, column2) | ++-----------------------------------+ +| 8.25 | ++-----------------------------------+ +``` + +###### Aliases + +- covar + +##### `nth_value` + +Returns the nth value in a group of values. + +```sql +nth_value(expression, n ORDER BY expression) +``` + +###### Arguments + +- **expression**: The column or expression to retrieve the nth value from. +- **n**: The position (nth) of the value to retrieve, based on the ordering. + +###### Example + +```sql +> SELECT dept_id, salary, NTH_VALUE(salary, 2) OVER (PARTITION BY dept_id ORDER BY salary ASC) AS second_salary_by_dept + FROM employee; ++---------+--------+-------------------------+ +| dept_id | salary | second_salary_by_dept | ++---------+--------+-------------------------+ +| 1 | 30000 | NULL | +| 1 | 40000 | 40000 | +| 1 | 50000 | 40000 | +| 2 | 35000 | NULL | +| 2 | 45000 | 45000 | ++---------+--------+-------------------------+ +``` + +##### `regr_avgx` + +Computes the average of the independent variable (input) expression_x for the non-null paired data points. + +```sql +regr_avgx(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_avgy` + +Computes the average of the dependent variable (output) expression_y for the non-null paired data points. + +```sql +regr_avgy(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_count` + +Counts the number of non-null paired data points. + +```sql +regr_count(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_intercept` + +Computes the y-intercept of the linear regression line. For the equation (y = kx + b), this function returns b. + +```sql +regr_intercept(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_r2` + +Computes the square of the correlation coefficient between the independent and dependent variables. + +```sql +regr_r2(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of 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. + +```sql +regr_slope(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_sxx` + +Computes the sum of squares of the independent variable. + +```sql +regr_sxx(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_sxy` + +Computes the sum of products of paired data points. + +```sql +regr_sxy(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_syy` + +Computes the sum of squares of the dependent variable. + +```sql +regr_syy(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `stddev` + +Returns the standard deviation of a set of numbers. + +```sql +stddev(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT stddev(column_name) FROM table_name; ++----------------------+ +| stddev(column_name) | ++----------------------+ +| 12.34 | ++----------------------+ +``` + +###### Aliases + +- stddev_samp + +##### `stddev_pop` + +Returns the population standard deviation of a set of numbers. + +```sql +stddev_pop(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT stddev_pop(column_name) FROM table_name; ++--------------------------+ +| stddev_pop(column_name) | ++--------------------------+ +| 10.56 | ++--------------------------+ +``` + +##### `stddev_samp` + +_Alias of [stddev](#stddev)._ + +### Approximate Functions + +- [approx_distinct](#approx_distinct) +- [approx_median](#approx_median) +- [approx_percentile_cont](#approx_percentile_cont) +- [approx_percentile_cont_with_weight](#approx_percentile_cont_with_weight) + +##### `approx_distinct` + +Returns the approximate number of distinct input values calculated using the HyperLogLog algorithm. + +```sql +approx_distinct(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT approx_distinct(column_name) FROM table_name; ++-----------------------------------+ +| approx_distinct(column_name) | ++-----------------------------------+ +| 42 | ++-----------------------------------+ +``` + +##### `approx_median` + +Returns the approximate median (50th percentile) of input values. It is an alias of `approx_percentile_cont(0.5) WITHIN GROUP (ORDER BY x)`. + +```sql +approx_median(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT approx_median(column_name) FROM table_name; ++-----------------------------------+ +| approx_median(column_name) | ++-----------------------------------+ +| 23.5 | ++-----------------------------------+ +``` + +##### `approx_percentile_cont` + +Returns the approximate percentile of input values using the t-digest algorithm. + +```sql +approx_percentile_cont(percentile, centroids) WITHIN GROUP (ORDER BY expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **percentile**: Percentile to compute. Must be a float value between 0 and 1 (inclusive). +- **centroids**: Number of centroids to use in the t-digest algorithm. _Default is 100_. A higher number results in more accurate approximation but requires more memory. + +###### Example + +```sql +> SELECT approx_percentile_cont(0.75, 100) WITHIN GROUP (ORDER BY column_name) FROM table_name; ++-----------------------------------------------------------------------+ +| approx_percentile_cont(0.75, 100) WITHIN GROUP (ORDER BY column_name) | ++-----------------------------------------------------------------------+ +| 65.0 | ++-----------------------------------------------------------------------+ +``` + +##### `approx_percentile_cont_with_weight` + +Returns the weighted approximate percentile of input values using the t-digest algorithm. + +```sql +approx_percentile_cont_with_weight(weight, percentile) WITHIN GROUP (ORDER BY expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **weight**: Expression to use as weight. Can be a constant, column, or function, and any combination of arithmetic operators. +- **percentile**: Percentile to compute. Must be a float value between 0 and 1 (inclusive). + +###### Example + +```sql +> SELECT approx_percentile_cont_with_weight(weight_column, 0.90) WITHIN GROUP (ORDER BY column_name) FROM table_name; ++---------------------------------------------------------------------------------------------+ +| approx_percentile_cont_with_weight(weight_column, 0.90) WITHIN GROUP (ORDER BY column_name) | ++---------------------------------------------------------------------------------------------+ +| 78.5 | ++---------------------------------------------------------------------------------------------+ +``` + + + + +## Window Functions + +A _window function_ performs a calculation across a set of table rows that are somehow related to the current row. +This is 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 + +```sql +function([expr]) + OVER( + [PARTITION BY expr[, …]] + [ORDER BY expr [ ASC | DESC ][, …]] + [ frame_clause ] + ) +``` + +where **frame_clause** is one of: + +```sql + { 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 + +- [cume_dist](#cume_dist) +- [dense_rank](#dense_rank) +- [ntile](#ntile) +- [percent_rank](#percent_rank) +- [rank](#rank) +- [row_number](#row_number) + +##### `cume_dist` + +Relative rank of the current row: (number of rows preceding or peer with the current row) / (total rows). + +```sql +cume_dist() +``` + +###### Example + +```sql + --Example usage of the cume_dist window function: + SELECT salary, + cume_dist() OVER (ORDER BY salary) AS cume_dist + FROM employees; +``` + +```sql ++--------+-----------+ +| salary | cume_dist | ++--------+-----------+ +| 30000 | 0.33 | +| 50000 | 0.67 | +| 70000 | 1.00 | ++--------+-----------+ +``` + +##### `dense_rank` + +Returns the rank of the current row without gaps. This function ranks rows in a dense manner, meaning consecutive ranks are assigned even for identical values. + +```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 + +##### `percent_rank` + +Returns the percentage rank of the current row within its partition. The value ranges from 0 to 1 and is computed as `(rank - 1) / (total_rows - 1)`. + +```sql +percent_rank() +``` + +##### `rank` + +Returns the rank of the current row within its partition, allowing gaps between ranks. This function provides a ranking similar to `row_number`, but skips ranks for identical values. + +```sql +rank() +``` + +##### `row_number` + +Number of the current row within its partition, counting from 1. + +```sql +row_number() +``` + +### Analytical Functions + +- [first_value](#first_value) +- [lag](#lag) +- [last_value](#last_value) +- [lead](#lead) +- [nth_value](#nth_value) + +##### `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 + +##### `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). + +```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. + +##### `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 + +##### `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). + +```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. + +##### `nth_value` + +Returns the value evaluated at the nth row of the window frame (counting from 1). Returns NULL if no such row exists. + +```sql +nth_value(expression, n) +``` + +###### Arguments + +- **expression**: The column from which to retrieve the nth value. +- **n**: Integer. Specifies the row number (starting from 1) in the window frame. + +###### Example + +```sql +-- Sample employees table: +CREATE TABLE employees (id INT, salary INT); +INSERT INTO employees (id, salary) VALUES +(1, 30000), +(2, 40000), +(3, 50000), +(4, 60000), +(5, 70000); + +-- Example usage of nth_value: +SELECT nth_value(salary, 2) OVER ( + ORDER BY salary + ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW +) AS nth_value +FROM employees; +``` + +```text ++-----------+ +| nth_value | ++-----------+ +| 40000 | +| 40000 | +| 40000 | +| 40000 | +| 40000 | ++-----------+ +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/geo.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/geo.md new file mode 100644 index 0000000000..780c7d05d9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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, + ); + +``` + + +## 空间测量 + +### `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-1.0/reference/sql/functions/ip.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/ip.md new file mode 100644 index 0000000000..0d557755cc --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/ip.md @@ -0,0 +1,257 @@ +--- +keywords: ["IP", "IPv4", "IPv6", "CIDR", "地址", "网络", "范围", "转换", "操作", "SQL", "函数"] +description: 关于 IP 地址操作、字符串/数字格式转换、CIDR 表示法以及 IPv4 和 IPv6 范围检查的 SQL 函数文档。 +--- + +import TOCInline from '@theme/TOCInline'; + +# IP 函数 + + + +本文档介绍了可用于 IP 地址操作和比较的函数。 + +### `ipv4_to_cidr(ip_string [, subnet_mask])` + +**描述:** + +将 IPv4 地址字符串转换为 CIDR 表示法。如果提供了 `subnet_mask` 参数(UInt8 类型,取值范围 0-32),则使用指定的子网掩码。否则,函数会根据输入字符串末尾的零或提供的八位字节数来自动检测子网(例如,'192.168' 表示 /16,'192' 表示 /8)。生成的 CIDR 表示法中的 IP 地址会根据子网掩码将主机位清零。 + +**参数:** + +* `ip_string`: String - IPv4 地址字符串(例如,'192.168.1.1','10.0.0.0','172.16')。不完整的地址将用零补全。 +* `subnet_mask` (可选): UInt8 - 期望的子网掩码长度(例如,24, 16, 8)。 + +**返回类型:** + +String - CIDR 表示法中的 IPv4 地址(例如,'192.168.1.0/24')。若输入无效,则返回 NULL。 + +**示例:** + +```sql +-- 自动检测子网 +SELECT ipv4_to_cidr('192.168.1.0'); +-- 输出: '192.168.1.0/24' + +SELECT ipv4_to_cidr('172.16'); +-- 输出: '172.16.0.0/16' + +-- 指定子网掩码 +SELECT ipv4_to_cidr('192.168.1.1', 24); +-- 输出: '192.168.1.0/24' + +SELECT ipv4_to_cidr('10.0.0.1', 16); +-- 输出: '10.0.0.0/16' +``` + +### `ipv6_to_cidr(ip_string [, subnet_mask])` + +**描述:** + +将 IPv6 地址字符串转换为 CIDR 表示法。如果提供了 `subnet_mask` 参数(UInt8 类型,取值范围 0-128),则使用指定的子网掩码。否则,函数会尝试根据地址末尾的零段或常见前缀(如 `fe80::` 代表 /16 或 `2001:db8::` 代表 /32)来自动检测子网。生成的 CIDR 表示法中的 IP 地址会根据子网掩码将主机位清零。 + +**参数:** + +* `ip_string`: String - IPv6 地址字符串(例如,'2001:db8::1','fe80::')。不完整的地址在可能的情况下会被补全(例如,'2001:db8' 变为 '2001:db8::')。 +* `subnet_mask` (可选): UInt8 - 期望的子网掩码长度(例如,48, 64, 128)。 + +**返回类型:** + +String - CIDR 表示法中的 IPv6 地址(例如,'2001:db8::/32')。若输入无效,则返回 NULL。 + +**示例:** + +```sql +-- 自动检测子网 +SELECT ipv6_to_cidr('2001:db8::'); +-- 输出: '2001:db8::/32' + +SELECT ipv6_to_cidr('fe80::1'); +-- 输出: 'fe80::/16' + +SELECT ipv6_to_cidr('::1'); +-- 输出: '::1/128' + +-- 指定子网掩码 +SELECT ipv6_to_cidr('2001:db8::', 48); +-- 输出: '2001:db8::/48' + +SELECT ipv6_to_cidr('fe80::1', 10); +-- 输出: 'fe80::/10' +``` + +### `ipv4_num_to_string(ip_number)` + +**描述:** + +将 UInt32 类型的数字转换为标准的 A.B.C.D 格式的 IPv4 地址字符串。该数字被视为大端字节序(Big-Endian)的 IPv4 地址。 + +**参数:** + +* `ip_number`: UInt32 - IPv4 地址的数字形式。 + +**返回类型:** + +String - 点分十进制表示法中的 IPv4 地址(例如,'192.168.0.1')。 + +**示例:** + +```sql +SELECT ipv4_num_to_string(3232235521); -- 0xC0A80001 +-- 输出: '192.168.0.1' + +SELECT ipv4_num_to_string(167772161); -- 0x0A000001 +-- 输出: '10.0.0.1' + +SELECT ipv4_num_to_string(0); +-- 输出: '0.0.0.0' +``` + +### `ipv4_string_to_num(ip_string)` + +**描述:** + +将 A.B.C.D 格式的 IPv4 地址字符串转换为其对应的 UInt32 数字(大端序)。 + +**参数:** + +* `ip_string`: String - 点分十进制表示法中的 IPv4 地址。 + +**返回类型:** + +UInt32 - IPv4 地址的数字表示。若输入格式无效,则返回 NULL 或抛出错误。 + +**示例:** + +```sql +SELECT ipv4_string_to_num('192.168.0.1'); +-- 输出: 3232235521 + +SELECT ipv4_string_to_num('10.0.0.1'); +-- 输出: 167772161 + +SELECT ipv4_string_to_num('0.0.0.0'); +-- 输出: 0 +``` + +### `ipv6_num_to_string(hex_string)` + +**描述:** + +将 32 个字符长的十六进制字符串(代表 IPv6 地址)转换为其标准格式的字符串表示(例如,'2001:db8::1')。能正确处理 IPv4 映射的 IPv6 地址(例如,'::ffff:192.168.0.1')。十六进制字符的大小写不敏感。 + +**参数:** + +* `hex_string`: String - 代表 IPv6 地址 16 个字节的 32 位十六进制字符串。 + +**返回类型:** + +String - 标准格式的 IPv6 地址字符串。若输入不是有效的 32 位十六进制字符串,则返回 NULL 或抛出错误。 + +**示例:** + +```sql +SELECT ipv6_num_to_string('20010db8000000000000000000000001'); +-- 输出: '2001:db8::1' + +SELECT ipv6_num_to_string('00000000000000000000ffffc0a80001'); +-- 输出: '::ffff:192.168.0.1' +``` + +### `ipv6_string_to_num(ip_string)` + +**描述:** + +将标准格式的 IPv6 地址字符串或点分十进制格式的 IPv4 地址字符串转换为其 16 字节的二进制表示。如果输入是 IPv4 地址字符串,它会先被内部转换为 IPv6 映射的等价形式(例如,'192.168.0.1' 内部变为 '::ffff:192.168.0.1'),然后再转换为二进制表示。 + +**参数:** + +* `ip_string`: String - IPv6 或 IPv4 地址字符串。 + +**返回类型:** + +Binary - IPv6 地址的 16 字节二进制数据。若输入格式无效,则返回 NULL 或抛出错误。 + +**示例:** + +```sql +-- IPv6 输入 +SELECT ipv6_string_to_num('2001:db8::1'); +-- 输出: 2001:db8::1 的二进制表示 + +-- IPv4 输入 (映射到 IPv6) +SELECT ipv6_string_to_num('192.168.0.1'); +-- 输出: ::ffff:192.168.0.1 的二进制表示 + +-- IPv4 映射的 IPv6 输入 +SELECT ipv6_string_to_num('::ffff:192.168.0.1'); +-- 输出: ::ffff:192.168.0.1 的二进制表示 +``` + +### `ipv4_in_range(ip_string, cidr_string)` + +**描述:** + +检查给定的 IPv4 地址字符串是否落在指定的 CIDR 范围字符串之内。 + +**参数:** + +* `ip_string`: String - 待检查的 IPv4 地址(例如,'192.168.1.5')。 +* `cidr_string`: String - 用于检查的 CIDR 范围(例如,'192.168.1.0/24')。 + +**返回类型:** + +Boolean - 如果 IP 地址在指定范围内,则返回 `true`,否则返回 `false`。若输入无效,则返回 NULL 或抛出错误。 + +**示例:** + +```sql +SELECT ipv4_in_range('192.168.1.5', '192.168.1.0/24'); +-- 输出: true + +SELECT ipv4_in_range('192.168.2.1', '192.168.1.0/24'); +-- 输出: false + +SELECT ipv4_in_range('10.0.0.1', '10.0.0.0/8'); +-- 输出: true + +SELECT ipv4_in_range('8.8.8.8', '0.0.0.0/0'); -- /0 匹配所有地址 +-- 输出: true + +SELECT ipv4_in_range('192.168.1.1', '192.168.1.1/32'); -- /32 表示精确匹配单个地址 +-- 输出: true +``` + +### `ipv6_in_range(ip_string, cidr_string)` + +**描述:** + +检查给定的 IPv6 地址字符串是否落在指定的 CIDR 范围字符串之内。 + +**参数:** + +* `ip_string`: String - 待检查的 IPv6 地址(例如,'2001:db8::1')。 +* `cidr_string`: String - 用于检查的 CIDR 范围(例如,'2001:db8::/32')。 + +**返回类型:** + +Boolean - 如果 IP 地址在指定范围内,则返回 `true`,否则返回 `false`。若输入无效,则返回 NULL 或抛出错误。 + +**示例:** + +```sql +SELECT ipv6_in_range('2001:db8::1', '2001:db8::/32'); +-- 输出: true + +SELECT ipv6_in_range('2001:db8:1::', '2001:db8::/32'); +-- 输出: true + +SELECT ipv6_in_range('2001:db9::1', '2001:db8::/32'); +-- 输出: false + +SELECT ipv6_in_range('::1', '::1/128'); +-- 输出: true + +SELECT ipv6_in_range('fe80::1', 'fe80::/16'); +-- 输出: true +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/json.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/json.md new file mode 100644 index 0000000000..e9baee1794 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/json.md @@ -0,0 +1,128 @@ +--- +keywords: [JSON函数, 数据转换, SQL 查询, 数据库 JSON, JSON 操作] +description: 列出了 GreptimeDB 中的所有 JSON 函数,包括函数的定义、使用方法和相关的 SQL 查询示例。 +--- + +# JSON 函数(试验功能) + +:::warning +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-1.0/reference/sql/functions/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/overview.md new file mode 100644 index 0000000000..0bef5dbde9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/overview.md @@ -0,0 +1,284 @@ +--- +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.md)。 + +### `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_term(expression, term)` 用于全文检索。阅读[查询日志](/user-guide/logs/fulltext-search.md)文档获取更多详情。 +* `regexp_extract(str, regexp)` 提取字符串中与正则表达式匹配的第一个子串。如果没有找到匹配项则返回 `NULL`。 + +#### regexp_extract + +提取字符串中与[正则表达式](https://docs.rs/regex/latest/regex/#syntax)匹配的第一个子串。如果没有找到匹配项则返回 `NULL`。 + +```sql +regexp_extract(str, regexp) +``` + +**参数:** + +- **str**: 要操作的字符串表达式。可以是常量、列或函数,以及运算符的任意组合。 +- **regexp**: 要匹配的正则表达式。可以是常量、列或函数。 + +**关于转义的说明:** + +GreptimeDB 在 MySQL 和 PostgreSQL 兼容模式下的正则表达式转义行为有所不同: +- **MySQL 模式**:转义序列需要使用双反斜杠(例如 `\\d`、`\\s`) +- **PostgreSQL 模式**:默认情况下单反斜杠即可(例如 `\d`、`\s`),或者使用 `E''` 前缀以与 MySQL 保持一致(例如 `E'\\d'`) + +**示例:** + +```sql +SELECT regexp_extract('version 1.2.3', '\d+\.\d+\.\d+'); +-- 返回: 1.2.3 + +SELECT regexp_extract('Phone: 123-456-7890', '\d{3}-\d{3}-\d{4}'); +-- 返回: 123-456-7890 + +SELECT regexp_extract('no match here', '\d+\.\d+\.\d+'); +-- 返回: NULL +``` + +### 数学函数 + +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 | ++-------------------------+ +``` + +### 日期和时间函数 + +DataFusion [时间和日期函数](./df-functions.md#time-and-date-functions)。GreptimeDB 额外提供: + +* [date_add](#data_add) +* [date_sub](#data_sub) +* [date_format](#date_format) +* [to_unixtime](#to_unixtime) +* [timezone](#timezone) + +#### date_add + +* `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 + +* `date_sub(expression, interval)` 从 Timestamp、Date 或 DateTime 减去一个间隔值: + +```sql +SELECT date_sub('2023-12-06 07:39:46.222'::TIMESTAMP_MS, '5 day'::INTERVAL); +``` + +``` ++-----------------------------------------------------------------------------------------------------------------------------------------+ +| 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 + +* `date_format(expression, fmt)` 将 Timestamp、Date 或 DateTime 格式化: + +支持 `Date32`、`Date64` 和所有 `Timestamp` 类型。 + +```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 + +* `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 + +* `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)。 + +### 近似函数 + +GreptimeDB 支持一些近似函数用于数据分析,例如近似去重计数(hll)、近似分位数(uddsketch)等。[了解 GreptimeDB 中近似函数](./approximate.md)。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/vector.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/vector.md new file mode 100644 index 0000000000..b5a9553c66 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/functions/vector.md @@ -0,0 +1,470 @@ +--- +keywords: [向量函数, 距离计算, 向量运算, SQL 查询, 数据库向量] +description: 列出了 GreptimeDB 中的所有向量函数,包括函数的定义、使用方法和相关的 SQL 查询示例。 +--- + +# 向量函数 + +本页面列出了 GreptimeDB 中所有支持的向量相关函数。向量函数主要用于处理向量运算,比如基础运算、距离计算、转换函数等。 + +## 基础运算 + +### `vec_scalar_add` + +向量与标量的加法运算。将向量中的每个元素与标量相加,返回新的向量。 + +示例: + +```sql +SELECT vec_to_string(vec_scalar_add(2.0, parse_vec('[1.0, 2.0, 3.0]'))); +``` + +```sql ++------------------------------------------------------------------------------+ +| vec_to_string(vec_scalar_add(Float64(2),parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++------------------------------------------------------------------------------+ +| [3,4,5] | ++------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_scalar_add(2.0, '[1.0, 2.0, 3.0]')); -- 隐式转换字符串为向量 +``` + +```sql ++-------------------------------------------------------------------+ +| vec_to_string(vec_scalar_add(Float64(2),Utf8("[1.0, 2.0, 3.0]"))) | ++-------------------------------------------------------------------+ +| [3,4,5] | ++-------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_scalar_add(-2.0, parse_vec('[1.0, 2.0, 3.0]'))); -- 减法运算 +``` + +```sql ++-------------------------------------------------------------------------------+ +| vec_to_string(vec_scalar_add(Float64(-2),parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++-------------------------------------------------------------------------------+ +| [-1,0,1] | ++-------------------------------------------------------------------------------+ +``` + +### `vec_scalar_mul` + +向量与标量的乘法运算。将向量中的每个元素与标量相乘,返回新的向量。 + +示例: + +```sql +SELECT vec_to_string(vec_scalar_mul(2.0, parse_vec('[1.0, 2.0, 3.0]'))); +``` + +```sql ++------------------------------------------------------------------------------+ +| vec_to_string(vec_scalar_mul(Float64(2),parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++------------------------------------------------------------------------------+ +| [2,4,6] | ++------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_scalar_mul(2.0, '[1.0, 2.0, 3.0]')); -- 隐式转换字符串为向量 +``` + +```sql ++------------------------------------------------------------------------------+ +| vec_to_string(vec_scalar_mul(Float64(2),parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++------------------------------------------------------------------------------+ +| [2,4,6] | ++------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_scalar_mul(1.0/2.0, parse_vec('[1.0, 2.0, 3.0]'))); -- 除法运算 +``` + +```sql ++-------------------------------------------------------------------------------------------+ +| vec_to_string(vec_scalar_mul(Float64(1) / Float64(2),parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++-------------------------------------------------------------------------------------------+ +| [0.5,1,1.5] | ++-------------------------------------------------------------------------------------------+ +``` + +### `vec_add` + +向量之间的加法运算。将两个向量的对应元素相加,返回新的向量。 + +示例: + +```sql +SELECT vec_to_string(vec_add(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]'))); +``` + +```sql ++-----------------------------------------------------------------------------------------------+ +| vec_to_string(vec_add(parse_vec(Utf8("[1.0, 2.0, 3.0]")),parse_vec(Utf8("[2.0, 1.0, 4.0]")))) | ++-----------------------------------------------------------------------------------------------+ +| [3,3,7] | ++-----------------------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_add('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]')); -- 隐式转换字符串为向量 +``` + +```sql ++-------------------------------------------------------------------------+ +| vec_to_string(vec_add(Utf8("[1.0, 2.0, 3.0]"),Utf8("[2.0, 1.0, 4.0]"))) | ++-------------------------------------------------------------------------+ +| [3,3,7] | ++-------------------------------------------------------------------------+ +``` + +### `vec_sub` + +向量之间的减法运算。将两个向量的对应元素相减,返回新的向量。 + +示例: + +```sql +SELECT vec_to_string(vec_sub(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]'))); +``` + +```sql ++-----------------------------------------------------------------------------------------------+ +| vec_to_string(vec_sub(parse_vec(Utf8("[1.0, 2.0, 3.0]")),parse_vec(Utf8("[2.0, 1.0, 4.0]")))) | ++-----------------------------------------------------------------------------------------------+ +| [-1,1,-1] | ++-----------------------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_sub('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]')); -- 隐式转换字符串为向量 +``` + +```sql ++-------------------------------------------------------------------------+ +| vec_to_string(vec_sub(Utf8("[1.0, 2.0, 3.0]"),Utf8("[2.0, 1.0, 4.0]"))) | ++-------------------------------------------------------------------------+ +| [-1,1,-1] | ++-------------------------------------------------------------------------+ +``` + +### `vec_mul` + +向量之间的乘法运算。将两个向量的对应元素相乘,返回新的向量。 + +示例: + +```sql +SELECT vec_to_string(vec_mul(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]'))); +``` + +```sql ++-----------------------------------------------------------------------------------------------+ +| vec_to_string(vec_mul(parse_vec(Utf8("[1.0, 2.0, 3.0]")),parse_vec(Utf8("[2.0, 1.0, 4.0]")))) | ++-----------------------------------------------------------------------------------------------+ +| [2,2,12] | ++-----------------------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_mul('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]')); -- 隐式转换字符串为向量 +``` + +```sql ++-------------------------------------------------------------------------+ +| vec_to_string(vec_mul(Utf8("[1.0, 2.0, 3.0]"),Utf8("[2.0, 1.0, 4.0]"))) | ++-------------------------------------------------------------------------+ +| [2,2,12] | ++-------------------------------------------------------------------------+ +``` + +### `vec_div` + +向量之间的除法运算。将两个向量的对应元素相除,返回新的向量。 + +示例: + +```sql +SELECT vec_to_string(vec_div(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]'))); +``` + +```sql ++-----------------------------------------------------------------------------------------------+ +| vec_to_string(vec_div(parse_vec(Utf8("[1.0, 2.0, 3.0]")),parse_vec(Utf8("[2.0, 1.0, 4.0]")))) | ++-----------------------------------------------------------------------------------------------+ +| [0.5,2,0.75] | ++-----------------------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_div('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]')); -- 隐式转换字符串为向量 +``` + +```sql ++-------------------------------------------------------------------------+ +| vec_to_string(vec_div(Utf8("[1.0, 2.0, 3.0]"),Utf8("[2.0, 1.0, 4.0]"))) | ++-------------------------------------------------------------------------+ +| [0.5,2,0.75] | ++-------------------------------------------------------------------------+ +``` + +### `vec_elem_sum` + +向量中所有元素求和,返回一个标量。 + +示例: + +```sql +SELECT vec_elem_sum(parse_vec('[1.0, 2.0, 3.0]')); +``` + +```sql ++--------------------------------------------------+ +| vec_elem_sum(parse_vec(Utf8("[1.0, 2.0, 3.0]"))) | ++--------------------------------------------------+ +| 6 | ++--------------------------------------------------+ +``` + +```sql +SELECT vec_elem_sum('[1.0, 2.0, 3.0]'); -- 隐式转换字符串为向量 +``` + +```sql ++---------------------------------------+ +| vec_elem_sum(Utf8("[1.0, 2.0, 3.0]")) | ++---------------------------------------+ +| 6 | ++---------------------------------------+ +``` + +### `vec_elem_product` + +向量中所有元素求积,返回一个标量。 + +示例: + +```sql +SELECT vec_elem_product(parse_vec('[1.0, 2.0, 3.0]')); +``` + +```sql ++------------------------------------------------------+ +| vec_elem_product(parse_vec(Utf8("[1.0, 2.0, 3.0]"))) | ++------------------------------------------------------+ +| 6 | ++------------------------------------------------------+ +``` + +```sql +SELECT vec_elem_product('[1.0, 2.0, 3.0]'); -- 隐式转换字符串为向量 +``` + +```sql ++-------------------------------------------+ +| vec_elem_product(Utf8("[1.0, 2.0, 3.0]")) | ++-------------------------------------------+ +| 6 | ++-------------------------------------------+ +``` + +### `vec_norm` + +归一化向量。将向量中的每个元素除以向量的 L2 范数,返回新的向量。 + +等价于 `vec_scalar_mul(1.0 / sqrt(vec_elem_sum(vec_mul(vec, vec))), vec)`。 + +示例: + +```sql +SELECT vec_to_string(vec_norm(parse_vec('[1.0, 2.0, 3.0]'))); +``` + +```sql ++-------------------------------------------------------------+ +| vec_to_string(vec_norm(parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++-------------------------------------------------------------+ +| [0.26726124,0.5345225,0.8017837] | ++-------------------------------------------------------------+ + +-- 等价于 +-- SELECT vec_to_string(vec_scalar_mul(1.0 / sqrt(vec_elem_sum(vec_mul(vec, vec))), vec)) +-- FROM (SELECT '[1.0, 2.0, 3.0]' AS vec); +-- +--------------------------------------------------------------------------------------+ +-- | vec_to_string(vec_scalar_mul(Float64(1) / sqrt(vec_elem_sum(vec_mul(vec,vec))),vec)) | +-- +--------------------------------------------------------------------------------------+ +-- | [0.26726124,0.5345225,0.8017837] | +-- +--------------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_norm('[1.0, 2.0, 3.0]')); -- 隐式转换字符串为向量 +``` + +```sql ++--------------------------------------------------+ +| vec_to_string(vec_norm(Utf8("[1.0, 2.0, 3.0]"))) | ++--------------------------------------------------+ +| [0.26726124,0.5345225,0.8017837] | ++--------------------------------------------------+ +``` + +## 聚合函数 + +### `vec_sum` + +将向量列中的所有向量按元素相加,返回一个新的向量。 + +示例: + +```sql +CREATE TABLE vectors ( + ts TIMESTAMP TIME INDEX, + vec_col VECTOR(3), +); + +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:01', '[1.0, 2.0, 3.0]'); +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:02', '[2.0, 1.0, 4.0]'); +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:03', '[3.0, 3.0, 3.0]'); + +SELECT vec_to_string(vec_sum(vec_col)) FROM vectors; +``` + +```sql ++-----------------------------------------+ +| vec_to_string(vec_sum(vectors.vec_col)) | ++-----------------------------------------+ +| [6,6,10] | ++-----------------------------------------+ +``` + +### `vec_product` + +将向量列中的所有向量按元素相乘,返回一个新的向量。 + +示例: + +```sql +CREATE TABLE vectors ( + ts TIMESTAMP TIME INDEX, + vec_col VECTOR(3), +); + +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:01', '[1.0, 2.0, 3.0]'); +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:02', '[2.0, 1.0, 4.0]'); +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:03', '[3.0, 3.0, 3.0]'); + +SELECT vec_to_string(vec_product(vec_col)) FROM vectors; +``` + +```sql ++---------------------------------------------+ +| vec_to_string(vec_product(vectors.vec_col)) | ++---------------------------------------------+ +| [6,6,36] | ++---------------------------------------------+ +``` + +## 距离计算 + +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-1.0/reference/sql/greptime-private/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/greptime-private/overview.md new file mode 100644 index 0000000000..d5b672f55d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/greptime-private/overview.md @@ -0,0 +1,15 @@ +--- +keywords: [系统表, greptime private, pipelines, 慢查询] +description: greptime_private 数据库中系统表的概述。 +--- + +# Greptime Private + +GreptimeDB 将一些重要的内部信息以系统表的形式存储在 `greptime_private` 数据库中。与普通表类似,系统表也会持久化存储。你可以通过系统表获取系统配置和统计信息。 + +## 表 + +| 表名 | 描述 | +| ----------------------------------- | -------------------------------------------------------- | +| [`slow_queries`](./slow_queries.md) | 包含 GreptimeDB 的慢查询信息,包括查询语句、执行时间等。 | +| [`pipelines`](./pipelines.md) | 包含 GreptimeDB 的 Pipeline 信息。 | diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/greptime-private/pipelines.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/greptime-private/pipelines.md new file mode 100644 index 0000000000..3e6f973109 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/greptime-private/pipelines.md @@ -0,0 +1,39 @@ +--- +keywords: [pipelines, greptime private] +description: greptime_private 数据库中 pipelines 表。 +--- + +# pipelines + +`pipelines` 表包含 GreptimeDB 的 Pipeline 信息。 + +```sql +USE greptime_private; + +SELECT * FROM pipelines; +``` + +输出如下: + +```sql ++----------------+--------+--------------+----------------------------------------------------------------------------------------------------------------------------------+----------------------------+ +| name | schema | content_type | pipeline | created_at | ++----------------+--------+--------------+----------------------------------------------------------------------------------------------------------------------------------+----------------------------+ +| nginx_pipeline | | yaml | transform: | 2025-07-03 07:23:15.227539 | + - fields: + - response_size + type: int32 + - fields: + - timestamp + type: time + index: timestamp ++----------------+--------+--------------+----------------------------------------------------------------------------------------------------------------------------------+----------------------------+ +``` + +- `name`: pipeline 名称; +- `schema`: 已废弃。如果你在 `v0.15` 之后创建 pipeline,这个字段会是一个空字符串。 +- `content_type`: pipeline 的类型; +- `pipeline`: pipeline 的具体内容; +- `created_at`: pipeline 的创建时间; + +更多详情可参考 [管理 Pipelines](/user-guide/logs/manage-pipelines.md) 文档。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/greptime-private/slow_queries.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/greptime-private/slow_queries.md new file mode 100644 index 0000000000..7e50b47db7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/greptime-private/slow_queries.md @@ -0,0 +1,37 @@ +--- +keywords: [慢查询, greptime private] +description: greptime_private 数据库中的慢查询表。 +--- + +# slow_queries + +`slow_queries` 表包含 GreptimeDB 的慢查询信息: + +```sql +USE greptime_private; + +SELECT * FROM slow_queries; +``` + +输出如下: + +```sql ++------+-----------+---------------------------------------------+-----------+----------------------------+--------------+-------------+---------------------+---------------------+ +| cost | threshold | query | is_promql | timestamp | promql_range | promql_step | promql_start | promql_end | ++------+-----------+---------------------------------------------+-----------+----------------------------+--------------+-------------+---------------------+---------------------+ +| 2 | 0 | irate(process_cpu_seconds_total[1h]) | 1 | 2025-05-14 13:59:36.368575 | 86400000 | 3600000 | 2024-11-24 00:00:00 | 2024-11-25 00:00:00 | +| 22 | 0 | SELECT * FROM greptime_private.slow_queries | 0 | 2025-05-14 13:59:44.844201 | 0 | 0 | 1970-01-01 00:00:00 | 1970-01-01 00:00:00 | ++------+-----------+---------------------------------------------+-----------+----------------------------+--------------+-------------+---------------------+---------------------+ +``` + +- `cost`:查询的耗时(毫秒)。 +- `threshold`:查询的阈值(毫秒)。 +- `query`:查询语句,可以是 SQL 或 PromQL。 +- `is_promql`:是否为 PromQL 查询。 +- `timestamp`:查询的时间戳。 +- `promql_range`:查询的范围,仅在 is_promql 为 true 时使用。 +- `promql_step`:查询的步长,仅在 is_promql 为 true 时使用。 +- `promql_start`:查询的起始时间,仅在 is_promql 为 true 时使用。 +- `promql_end`:查询的结束时间,仅在 is_promql 为 true 时使用。 + +更多详情可参考 [慢查询](/user-guide/deployments-administration/monitoring/slow-query.md) 文档。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/group_by.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/group_by.md new file mode 100644 index 0000000000..c7b5cfc0f1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/group_by.md @@ -0,0 +1,73 @@ +--- +keywords: [SQL GROUP BY 子句, 数据分组, 聚合函数, 数据汇总, SQL 示例] +description: GROUP BY 语句用于对具有相同值的行进行分组,通常与聚合函数一起使用。 +--- + +# GROUP BY + +SQL 中的 `GROUP BY` 语句用于对具有一个或多个列中的相同值的行进行分组。 +该子句通常与聚合函数(如 `COUNT`、`SUM`、`AVG` 等)一起使用,以生成汇总报表。 + +## Syntax + +`GROUP BY` 的基本语法如下: + +```sql +SELECT column1, column2, ..., aggregate_function(column_name) +FROM table_name +GROUP BY column1, column2, ...; +``` + +`GROUP BY` 语句根据子句中指定的列对结果集进行分组。 +聚合函数应用于具有相同值的组。 + +## 示例 + +假设有如下名为 `system_metrics` 的表: + +```sql ++-------+-------+----------+-------------+-----------+---------------------+ +| host | idc | cpu_util | memory_util | disk_util | ts | ++-------+-------+----------+-------------+-----------+---------------------+ +| host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 | +| host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 | +| host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 | ++-------+-------+----------+-------------+-----------+---------------------+ +``` + +### 根据 Tags 聚合 + +要获取每个 `idc` 中的 memory_util 平均值,可以使用以下 SQL: + +```sql +SELECT idc, AVG(memory_util) +FROM system_metrics +GROUP BY idc; +``` + +结果如下: + +```sql ++-------+---------------------------------+ +| idc | AVG(system_metrics.memory_util) | ++-------+---------------------------------+ +| idc_b | 66.7 | +| idc_c | 66.8 | +| idc_e | 66.7 | +| idc_a | 40.3 | ++-------+---------------------------------+ +``` + +### 根据 Time Interval 聚合 + +要获取 memory_util 的日均值,SQL 如下: + +```sql +SELECT date_trunc('day', ts) as dt, avg(memory_util) +FROM system_metrics +GROUP BY dt +``` + +请参考 [date_trunc](./functions/overview.md#date_trunc) 获取更多信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/having.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/having.md new file mode 100644 index 0000000000..c23aa5d6d5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/having.md @@ -0,0 +1,39 @@ +--- + +keywords: [SQL HAVING 子句, 数据检索, 过滤聚合函数行] +description: 描述 SQL 中的 HAVING 子句,该子句用于过滤聚合函数的行。 +--- + +# HAVING + +`HAVING` 子句允许你过滤分组(聚合)结果——它的作用类似于 `WHERE`,但是在分组发生之后才起作用。 `HAVING` 子句被添加到 SQL 中,是因为 `WHERE` 子句不能与聚合函数一起使用。 + +## 例子 + +查找平均 CPU 利用率超过 80% 的日期窗口: +```sql +SELECT + date_trunc('day', ts) AS day, + AVG(cpu_util) AS avg_cpu_util +FROM + system_metrics +GROUP BY + day +HAVING + avg_cpu_util > 80; +``` + +查找错误日志数量大于 100 的小时窗口: +```sql +SELECT + DATE_TRUNC('hour', log_time) AS hour, + COUNT(*) AS error_count +FROM + application_logs +WHERE + log_level = 'ERROR' +GROUP BY + hour +HAVING + error_count > 100; +``` \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/build-info.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/build-info.md new file mode 100644 index 0000000000..e889ab537d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/build-info.md @@ -0,0 +1,32 @@ +--- +keywords: [BUILD_INFO 表, 构建信息, 版本信息, SQL查询, 数据库构建] +description: 提供了 GreptimeDB 构建信息的相关内容,包括版本信息、构建时间和相关的 SQL 查询示例。 +--- + +# BUILD_INFO + +`BUILD_INFO` 表提供了系统的构建信息: + +```sql +USE INFORMATION_SCHEMA; + +SELECT * FROM BUILD_INFO; +``` + +结果如下: + +```sql ++------------+------------------------------------------+------------------+-----------+-------------+ +| git_branch | git_commit | git_commit_short | git_clean | pkg_version | ++------------+------------------------------------------+------------------+-----------+-------------+ +| | c595a56ac89bef78b19a76aa60d8c6bcac7354a5 | c595a56a | true | 0.9.0 | ++------------+------------------------------------------+------------------+-----------+-------------+ +``` + +结果中的列: + +* `branch`:构建的 git 分支名称。 +* `git_commit`:提交构建的 `commit`。 +* `git_commit_short`:提交构建的 `commit` 缩写。 +* `git_clean`:如果构建源目录包含了所有提交的更改,则为 `true`。 +* `pkg_version`:GreptimeDB 版本。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/character-sets.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/character-sets.md new file mode 100644 index 0000000000..779d06d616 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/character-sets.md @@ -0,0 +1,31 @@ +--- +keywords: [CHARACTER_SETS 表, 字符集, SQL 查询, 数据库字符集, 字符集信息] +description: 介绍了 GreptimeDB 中的字符集,包括字符集的定义、使用方法和相关的 SQL 查询示例。 +--- + +# CHARACTER_SETS + +`CHARACTER_SETS` 提供了 GreptimeDB 支持的可用字符集。 + +```sql +USE INFORMATION_SCHEMA; + +SELECT * FROM CHARACTER_SETS; +``` + +结果如下: + +```sql ++--------------------+----------------------+---------------+--------+ +| character_set_name | default_collate_name | description | maxlen | ++--------------------+----------------------+---------------+--------+ +| utf8 | utf8_bin | UTF-8 Unicode | 4 | ++--------------------+----------------------+---------------+--------+ +``` + +结果中的列: + +* `character_set_name`:字符集的名称。 +* `default_collate_name`:字符集的默认排序规则名称。 +* `description`:字符集的描述。 +* `MAXLEN`:存储一个字符所需的最大字节数。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/cluster-info.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/cluster-info.md new file mode 100644 index 0000000000..4beb13cdf1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/cluster-info.md @@ -0,0 +1,88 @@ +--- +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 | +| peer_hostname | String | | YES | | FIELD | +| total_cpu_millicores | Int64 | | NO | | FIELD | +| total_memory_bytes | Int64 | | NO | | FIELD | +| cpu_usage_millicores | Int64 | | NO | | FIELD | +| memory_usage_bytes | Int64 | | NO | | FIELD | +| version | String | | NO | | FIELD | +| git_commit | String | | NO | | FIELD | +| start_time | TimestampMillisecond | | YES | | FIELD | +| uptime | String | | YES | | FIELD | +| active_time | String | | YES | | FIELD | +| node_status | String | | YES | | FIELD | ++-----------------------+----------------------+------+------+---------+---------------+ +``` + + +每个列的含义: + +* `peer_id`: 节点的服务器 ID。对于 standalone 来讲,该字段总是为 `0`,对于集群模式下的 frontend 该字段总为 `-1`。因为在这两种情况下,该字段没有实际含义。 +* `peer_type`: 节点类型,分布式集群里可能是 `METASRV`、`FRONTEND` 或者 `DATANODE`。单机模式显示为 `STANDALONE`。 +* `peer_addr`: 节点的 gRPC 服务地址。对于单机部署,该字段总为空。 +* `peer_hostname`: 节点的主机名。 +* `total_cpu_millicores`: 节点的总 CPU 毫核数。 +* `total_memory_bytes`: 节点的总内存字节数。 +* `cpu_usage_millicores`: 节点的 CPU 使用毫核数。此功能仅在容器化环境 (cgroup v2) 中有效。 +* `memory_usage_bytes`: 节点的内存使用字节数。此功能仅在容器化环境 (cgroup v2) 中有效。 +* `version`: 节点的版本号,形如 `0.7.2` 的字符串。 +* `git_commit`: 节点编译的 git 版本号。 +* `start_time`: 节点的启动时间。 +* `uptime`: 节点的持续运行时间,形如 `24h 10m 59s 150ms` 的字符串。 +* `active_time`: 距离节点上一次活跃(也就是发送心跳请求)过去的时间,形如 `24h 10m 59s 150ms` 的字符串。单机模式下该字段总为空。 +* `node_status`: 节点的状态信息。 + +尝试查询下这张表: + +```sql +SELECT * FROM CLUSTER_INFO; +``` + +一个单机模式的样例输出: + +```sql ++---------+------------+-----------+---------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+--------+-------------+-------------+ +| peer_id | peer_type | peer_addr | peer_hostname | total_cpu_millicores | total_memory_bytes | cpu_usage_millicores | memory_usage_bytes | version | git_commit| start_time | uptime | active_time | node_status | ++---------+------------+-----------+---------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+--------+-------------+-------------+ +| 0 | STANDALONE | | | 16000 | 17179869184 | 0 | 0 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:02.074 | 18ms | | NULL | ++---------+------------+-----------+---------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+--------+-------------+-------------+ +``` + +另一个输出来自一个分布式集群,它有三个 Datanode、一个 Frontend 和一个 Metasrv: + +```sql ++---------+-----------+----------------+-------------------------------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+----------+-------------+-------------------------------------------------------------------+ +| peer_id | peer_type | peer_addr | peer_hostname | total_cpu_millicores | total_memory_bytes | cpu_usage_millicores | memory_usage_bytes | version | git_commit| start_time | uptime | active_time | node_status | ++---------+-----------+----------------+-------------------------------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+----------+-------------+-------------------------------------------------------------------+ +| 1 | DATANODE | 127.0.0.1:4101 | mycluster-datanode-0 | 1000 | 1073741824 | 1 | 34570240 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:04.791 | 4s 478ms | 1s 467ms | {"workloads":["hybrid"],"leader_regions":46,"follower_regions":0} | +| 2 | DATANODE | 127.0.0.1:4102 | mycluster-datanode-1 | 1000 | 1073741824 | 1 | 38170624 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:06.098 | 3s 171ms | 162ms | {"workloads":["hybrid"],"leader_regions":46,"follower_regions":0} | +| 3 | DATANODE | 127.0.0.1:4103 | mycluster-datanode-2 | 1000 | 1073741824 | 1 | 37085184 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:07.425 | 1s 844ms | 1s 839ms | {"workloads":["hybrid"],"leader_regions":46,"follower_regions":0} | +| -1 | FRONTEND | 127.0.0.1:4001 | mycluster-frontend-6c5d4bcf78-m7jtx | 1000 | 1073741824 | 1 | 45465600 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:08.815 | 454ms | 47ms | NULL | +| 0 | METASRV | 127.0.0.1:3002 | mycluster-meta-54bd44bd94-g8dzm | 1000 | 1073741824 | 0 | 28368896 | unknown | unknown | | | | {"is_leader":true} | ++---------+-----------+----------------+-------------------------------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+----------+-------------+-------------------------------------------------------------------+ +``` + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/collation-character-set-applicability.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/collation-character-set-applicability.md new file mode 100644 index 0000000000..40254eaf5f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/collation-character-set-applicability.md @@ -0,0 +1,29 @@ +--- +keywords: [COLLATION_CHARACTER_SET_APPLICABILITY 表, 排序规则, 字符集, SQL 查询, 数据库适用性] +description: 介绍了 GreptimeDB 中排序规则与字符集的适用性,包括如何在 SQL 查询中使用这些规则和字符集。 +--- + +# COLLATION_CHARACTER_SET_APPLICABILITY + +`COLLATION_CHARACTER_SET_APPLICABILITY` 表示了每个排序规则适用的字符集。 + +```sql +USE INFORMATION_SCHEMA; + +SELECT * FROM COLLATION_CHARACTER_SET_APPLICABILITY; +``` + +结果如下: + +```sql ++----------------+--------------------+ +| collation_name | character_set_name | ++----------------+--------------------+ +| utf8_bin | utf8 | ++----------------+--------------------+ +``` + +结果中的列: + +* `collation_name`:排序规则名称。 +* `character_set_name`:与排序规则关联的字符集名称。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/collations.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/collations.md new file mode 100644 index 0000000000..8b68d4ae67 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/collations.md @@ -0,0 +1,33 @@ +--- +keywords: [COLLATIONS 表, 排序规则, 字符集, SQL 查询, 数据库排序] +description: 介绍了 GreptimeDB 中字符集的排序规则,包括排序规则的定义、使用方法和相关的 SQL 查询示例。 +--- + +# COLLATIONS + +`COLLATIONS` 提供了每个字符集的排序规则信息。 + +```sql +USE INFORMATION_SCHEMA; + +SELECT * FROM COLLATIONS; +``` + +结果如下: + +```sql ++----------------+--------------------+------+------------+-------------+---------+ +| collation_name | character_set_name | id | is_default | is_compiled | sortlen | ++----------------+--------------------+------+------------+-------------+---------+ +| utf8_bin | utf8 | 1 | Yes | Yes | 1 | ++----------------+--------------------+------+------------+-------------+---------+ +``` + +表中有这些列: + +* `collation_name`:排序规则名称。 +* `character_set_name`:字符集名称。 +* `id`:排序规则 ID。 +* `is_default`:是否为字符集的默认排序规则。 +* `is_compiled`:字符集是否已编译到系统中。 +* `sortlen`:以字符集表示的字符串排序所需的最小内存量。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/columns.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/columns.md new file mode 100644 index 0000000000..0b2f1f0bb2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/columns.md @@ -0,0 +1,181 @@ +--- +keywords: [COLUMNS 表, 列信息, SQL查询, 数据库列, 表结构] +description: COLUMNS 表提供关于表中每列的详细信息。 +--- + +# COLUMNS + +`COLUMNS` 提供了关于表中每列的详细信息。 + +```sql +USE INFORMATION_SCHEMA; +DESC COLUMNS; +``` + +结果如下: + +```sql ++--------------------------+--------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------------+--------+------+------+---------+---------------+ +| table_catalog | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| column_name | String | | NO | | FIELD | +| ordinal_position | Int64 | | NO | | FIELD | +| character_maximum_length | Int64 | | YES | | FIELD | +| character_octet_length | Int64 | | YES | | FIELD | +| numeric_precision | Int64 | | YES | | FIELD | +| numeric_scale | Int64 | | YES | | FIELD | +| datetime_precision | Int64 | | YES | | FIELD | +| character_set_name | String | | YES | | FIELD | +| collation_name | String | | YES | | FIELD | +| column_key | String | | NO | | FIELD | +| extra | String | | NO | | FIELD | +| privileges | String | | NO | | FIELD | +| generation_expression | String | | NO | | FIELD | +| greptime_data_type | String | | NO | | FIELD | +| data_type | String | | NO | | FIELD | +| semantic_type | String | | NO | | FIELD | +| column_default | String | | YES | | FIELD | +| is_nullable | String | | NO | | FIELD | +| column_type | String | | NO | | FIELD | +| column_comment | String | | YES | | FIELD | +| srs_id | Int64 | | YES | | FIELD | ++--------------------------+--------+------+------+---------+---------------+ +24 rows in set (0.00 sec) +``` + +创建表 `public.t1` 并查询其在 `COLUMNS` 中的信息: + +```sql +CREATE TABLE public.t1 (h STRING, v FLOAT64, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, PRIMARY KEY(h)); +SELECT * FROM COLUMNS WHERE table_schema='public' AND TABLE_NAME='t1'\G +``` + +结果如下: + +```sql +*************************** 1. row *************************** + table_catalog: greptime + table_schema: public + table_name: t1 + column_name: h + ordinal_position: 1 +character_maximum_length: 2147483647 + character_octet_length: 2147483647 + numeric_precision: NULL + numeric_scale: NULL + datetime_precision: NULL + character_set_name: utf8 + collation_name: utf8_bin + column_key: PRI + extra: + privileges: select,insert + generation_expression: + greptime_data_type: String + data_type: string + semantic_type: TAG + column_default: NULL + is_nullable: Yes + column_type: string + column_comment: NULL + srs_id: NULL +*************************** 2. row *************************** + table_catalog: greptime + table_schema: public + table_name: t1 + column_name: v + ordinal_position: 2 +character_maximum_length: NULL + character_octet_length: NULL + numeric_precision: 22 + numeric_scale: NULL + datetime_precision: NULL + character_set_name: NULL + collation_name: NULL + column_key: + extra: + privileges: select,insert + generation_expression: + greptime_data_type: Float64 + data_type: double + semantic_type: FIELD + column_default: NULL + is_nullable: Yes + column_type: double + column_comment: NULL + srs_id: NULL +*************************** 3. row *************************** + table_catalog: greptime + table_schema: public + table_name: t1 + column_name: ts + ordinal_position: 3 +character_maximum_length: NULL + character_octet_length: NULL + numeric_precision: NULL + numeric_scale: NULL + datetime_precision: 3 + character_set_name: NULL + collation_name: NULL + column_key: TIME INDEX + extra: + privileges: select,insert + generation_expression: + greptime_data_type: TimestampMillisecond + data_type: timestamp(3) + semantic_type: TIMESTAMP + column_default: current_timestamp() + is_nullable: No + column_type: timestamp(3) + column_comment: NULL + srs_id: NULL +3 rows in set (0.03 sec) +``` + +`COLUMNS` 表中列的描述如下: + +- `table_catalog`:列所属的目录的名称。在 OSS 项目中该值始终为 `greptime`。 +- `table_schema`:包含列的表所属的数据库的名称。 +- `table_name`:包含列的表的名称。 +- `column_name`:列的名称。 +- `ordinal_position`:列在表中的位置。 +- `character_maximum_length`:对于字符串列,以字符为单位的最大长度。 +- `character_octet_length`:对于字符串列,以字节为单位的最大长度。 +- `numeric_precision`:对于数值数据类型,列的精度。 +- `numeric_scale`:对于数值数据类型,列的标度。 +- `datetime_precision`:对于日期时间数据类型,列的小数秒精度。 +- `character_set_name`:字符串列的字符集的名称。 +- `collation_name`:字符串列的排序规则的名称。 +- `column_key`:列的键类型。可以是以下之一:`PRI`、`TIME INDEX` 或空字符串。 +- `extra`:关于列的附加信息。 +- `privileges`:当前用户对该列的权限。 +- `generation_expression`:对于生成的列,此值显示用于计算列值的表达式。对于非生成的列,该值为空。 +- `greptime_data_type`:列的 GreptimeDB [数据类型](/reference/sql/data-types.md)。 +- `data_type`:列中的数据类型。 +- `semantic_type`:列的类型。可以是以下之一:`TAG`、`FIELD` 或 `TIMESTAMP`。 +- `column_default`:列的默认值。如果默认值被明确设定为 `NULL`,或者列定义中不包含 `default` 子句,则该值为 `NULL`。 +- `is_nullable`:列是否可为空。如果列可以存储空值,则该值为 `YES`;否则,为 `NO`。 +- `column_type`:列的数据类型。与 `DATA_TYPE` 列相同。 +- `column_comment`:列定义中包含的注释。 +- `srs_id`:列的空间参考系统(SRS)的 ID。 + +相应的 `SHOW` 语句如下: + +```sql +SHOW COLUMNS FROM t1 FROM public; +``` + +结果如下: + +```sql ++-------+--------------+------+------------+---------------------+-------+----------------------+ +| Field | Type | Null | Key | Default | Extra | Greptime_type | ++-------+--------------+------+------------+---------------------+-------+----------------------+ +| h | string | Yes | PRI | NULL | | String | +| ts | timestamp(3) | No | TIME INDEX | current_timestamp() | | TimestampMillisecond | +| v | double | Yes | | NULL | | Float64 | ++-------+--------------+------+------------+---------------------+-------+----------------------+ +3 rows in set (0.01 sec) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/engines.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/engines.md new file mode 100644 index 0000000000..382a006642 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/engines.md @@ -0,0 +1,51 @@ +--- +keywords: [存储引擎信息, ENGINES 表, 支持级别, 默认存储引擎, 事务支持] +description: ENGINES 表提供关于存储引擎的信息,检查 GreptimeDB 是否支持某个存储引擎或查看默认的存储引擎。 +--- + +# ENGINES + +`ENGINES`表提供了关于存储引擎的信息。当你需要检查 GreptimeDB 是否支持某个存储引擎或者查看默认的存储引擎时,该表非常有用。 + +`ENGINES`表包含以下列: + +* `engine`:存储引擎名称。 +* `support`:存储引擎的支持级别: + +|值 | 含义| +| --- | --- | +| `YES` | 支持且在使用中 | +| `DEFAULT` | 支持且在使用中,且是默认的存储引擎 | +| `NO` | 不支持 | +| `DISABLED` | 支持但已被禁用 | + + +* `comment`:存储引擎的简要描述。 +* `transactions`:存储引擎是否支持事务。 +* `xa`:存储引擎是否支持 XA 事务。 +* `savepoints`:存储引擎是否支持保存点。 + +例如: + +```sql +SELECT * from INFORMATION_SCHEMA.ENGINES\G +``` + +结果如下: + +```sql +*************************** 1. row *************************** + engine: mito + support: DEFAULT + comment: Storage engine for time-series data +transactions: NO + xa: NO + savepoints: NO +*************************** 2. row *************************** + engine: metric + support: YES + comment: Storage engine for observability scenarios, which is adept at handling a large number of small tables, making it particularly suitable for cloud-native monitoring +transactions: NO + xa: NO + savepoints: NO +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/flows.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/flows.md new file mode 100644 index 0000000000..0fecad7244 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/reference/sql/information-schema/key-column-usage.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/key-column-usage.md new file mode 100644 index 0000000000..ccb594c517 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/key-column-usage.md @@ -0,0 +1,88 @@ +--- +keywords: [键约束, KEY_COLUMN_USAGE 表, 时间索引键, 外键约束, 列位置] +description: KEY_COLUMN_USAGE 表描述列的键约束,例如时间索引键的约束。 +--- + +# KEY_COLUMN_USAGE + +`KEY_COLUMN_USAGE` 表描述列的键约束,例如时间索引键的约束。 + +```sql +USE INFORMATION_SCHEMA; +DESC KEY_COLUMN_USAGE; +``` + +结果如下: + +```sql ++-------------------------------+--------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-------------------------------+--------+------+------+---------+---------------+ +| constraint_catalog | String | | NO | | FIELD | +| constraint_schema | String | | NO | | FIELD | +| constraint_name | String | | NO | | FIELD | +| table_catalog | String | | NO | | FIELD | +| real_table_catalog | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| column_name | String | | NO | | FIELD | +| ordinal_position | UInt32 | | NO | | FIELD | +| position_in_unique_constraint | UInt32 | | YES | | FIELD | +| referenced_table_schema | String | | YES | | FIELD | +| referenced_table_name | String | | YES | | FIELD | +| referenced_column_name | String | | YES | | FIELD | ++-------------------------------+--------+------+------+---------+---------------+ +``` + +```sql +SELECT * FROM key_column_usage WHERE table_schema='public' and table_name='monitor'\G +``` + +```sql +*************************** 1. row *************************** + constraint_catalog: def + constraint_schema: public + constraint_name: TIME INDEX + table_catalog: def + real_table_catalog: greptime + table_schema: public + table_name: monitor + column_name: ts + ordinal_position: 1 +position_in_unique_constraint: NULL + referenced_table_schema: NULL + referenced_table_name: NULL + referenced_column_name: NULL +*************************** 2. row *************************** + constraint_catalog: def + constraint_schema: public + constraint_name: PRIMARY + table_catalog: def + real_table_catalog: greptime + table_schema: public + table_name: monitor + column_name: host + ordinal_position: 1 +position_in_unique_constraint: NULL + referenced_table_schema: NULL + referenced_table_name: NULL + referenced_column_name: NULL +2 rows in set (0.02 sec) +``` + +`KEY_COLUMN_USAGE` 表中列的描述如下: + +- `constraint_catalog`:约束所属的目录名称。该值始终为 `def`。 +- `constraint_schema`:约束所属的数据库名称。 +- `constraint_name`:约束的名称。 +- `table_catalog`:表所属目录的名称。该值始终为 `def`。 +- `real_table_catalog`:表所属目录的真实名称。该值始终为 `greptime`。 +- `table_schema`:表所属的数据库名称。 +- `table_name`:具有约束的表的名称。 +- `column_name`:具有约束的列的名称。 +- `ordinal_position`:列在约束中的位置,而不是在表中的位置。位置编号从 `1` 开始。 +- `position_in_unique_constraint`:唯一约束和主键约束为空。对于外键约束,此列是引用表键的位置。 +- `referenced_table_schema`:约束引用的数据库名称。目前在 GreptimeDB 中,除外键约束外,所有约束中此列的值均为 `NULL`。 +- `referenced_table_name`:约束引用的表名称。目前在 GreptimeDB 中,除外键约束外,所有约束中此列的值均为 `NULL`。 +- `referenced_column_name`:约束引用的列名称。目前在 GreptimeDB 中,除外键约束外,所有约束中此列的值均为 `NULL`。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/overview.md new file mode 100644 index 0000000000..1adf0395b7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/overview.md @@ -0,0 +1,66 @@ +--- +keywords: [系统元数据, INFORMATION_SCHEMA, MySQL 兼容性, 自定义表, 集群信息] +description: INFORMATION_SCHEMA 提供对系统元数据的访问,例如数据库或表的名称、列的数据类型等。 +--- + +# INFORMATION_SCHEMA + +`INFORMATION_SCHEMA` 提供了对系统元数据的访问,例如数据库或表的名称、列的数据类型等。GreptimeDB 还提供了一些自定义的 `INFORMATION_SCHEMA` 表,用于查询有关 GreptimeDB 系统本身、集群信息和运行时指标等元数据。很多 `INFORMATION_SCHEMA` 表都有对应的 `SHOW` 命令,查询 `INFORMATION_SCHEMA` 的好处是可以在表之间进行连接。 + +`INFORMATION_SCHEMA` 依然有很多工作要做,请跟踪 `INFORMATION_SCHEMA` 的 [issue](https://github.com/GreptimeTeam/greptimedb/issues/2931)。 + +## MySQL 兼容性 + +|表名 | 描述| +| --- | --- | +| [`CHARACTER_SETS`](./character-sets.md) | 提供了可用字符集的信息。 | +| `CHECK_CONSTRAINTS`| 未实现。返回零行。 | +| [`COLLATIONS`](./collations.md) | 提供了服务器支持的排序规则列表。 | +| [`COLLATION_CHARACTER_SET_APPLICABILITY`](./collation-character-set-applicability.md) | 解释了哪些排序规则适用于哪些字符集。 | +| [`COLUMNS`](./columns.md) | 提供了所有表的列列表。 | +| `COLUMN_PRIVILEGES` | 未实现。返回零行。 | +| `COLUMN_STATISTICS` | 不支持。 | +| [`ENGINES`](./engines.md) | 提供了支持的存储引擎列表。 | +| `EVENTS` | 未实现。返回零行。 | +| `FILES` | 未实现。返回零行。 | +| `GLOBAL_STATUS` | 未实现。返回零行。 | +| `GLOBAL_VARIABLES` | 不支持。 | +| [`KEY_COLUMN_USAGE`](./key-column-usage.md) | 描述了列的关键约束,例如主键和时间索引约束。 | +| `OPTIMIZER_TRACE` | 未实现。返回零行。 | +| `PARAMETERS` | 未实现。返回零行。 | +| [`PARTITIONS`](./partitions.md) | 提供了表分区的列表。 | +| `PLUGINS` | 不支持。| +| `PROCESSLIST` | 不支持,请使用 `PROCESS_LIST` 表 | +| `PROFILING` | 未实现。返回零行。 | +| `REFERENTIAL_CONSTRAINTS` | 未实现。返回零行。 | +| `ROUTINES` | 未实现。返回零行。 | +| [`SCHEMATA`](./schemata.md) | 提供了类似于 `SHOW DATABASES` 的信息。 | +| `SCHEMA_PRIVILEGES` | 未实现。返回零行。 | +| `SESSION_STATUS` | 未实现。返回零行。 | +| `SESSION_VARIABLES` | 不支持。 | +| `STATISTICS` | 不支持。 | +| [`TABLES`](./tables.md) | 提供了当前用户可见的表列表。类似于 `SHOW TABLES`。 | +| `TABLESPACES` | 不支持。 | +| `TABLE_PRIVILEGES` | 未实现。返回零行。 | +| `TRIGGERS` | 未实现。返回零行。 | +| `USER_ATTRIBUTES` | 不支持。 | +| `USER_PRIVILEGES` | 不支持。| +| `VARIABLES_INFO` | 不支持。 | +| [`VIEWS`](./views.md)| 提供了当前用户可见的视图(View)列表及相关信息。 | +| [`TABLE_CONSTRAINTS`](./table-constraints.md) | 提供了主键、唯一索引和外键的信息。 | + +## GreptimeDB 提供的表 + +|表名 | 描述| +| --- | --- | +| [`BUILD_INFO`](./build-info.md) | 提供了系统构建的信息。 | +| [`REGION_PEERS`](./region-peers.md) | 提供了表的 Region 存储的详细信息。 | +| [`REGION_STATISTICS`](./region-statistics.md) | 提供 Region 的详细统计信息,例如行数等。 | +| [`RUNTIME_METRICS`](./runtime-metrics.md)| 提供了系统运行时指标。| +| [`CLUSTER_INFO`](./cluster-info.md)| 提供了集群的节点拓扑信息。| +| [`FLOWS`](./flows.md) | 提供 Flow 相关信息。| +| [`PROCEDURE_INFO`](./procedure-info.md) | 提供 Procedure 相关信息。| +| [`PROCESS_LIST`](./process-list.md) | 提供集群内正在执行的查询信息| +| [`SSTS_INDEX_META`](./ssts-index-meta.md) | 提供 SST 索引元数据,包括倒排索引、全文索引和布隆过滤器。| +| [`SSTS_MANIFEST`](./ssts-manifest.md) | 提供从 manifest 获取的 SST 文件信息,包括文件路径、大小、时间范围和行数。| +| [`SSTS_STORAGE`](./ssts-storage.md) | 提供从存储层获取的 SST 文件信息,用于验证和调试。| diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/partitions.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/partitions.md new file mode 100644 index 0000000000..16a9f68eb8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/partitions.md @@ -0,0 +1,164 @@ +--- +keywords: [分区表信息, PARTITIONS 表, 分区方法, 分区表达式, Region Id] +description: PARTITIONS 表提供关于分区表的信息。 +--- + +# PARTITIONS + +`PARTITIONS` 表提供了关于分区表的信息。 + +```sql +USE INFORMATION_SCHEMA; +DESC PARTITIONS; +``` + +结果如下: + +```sql ++-------------------------------+----------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-------------------------------+----------+------+------+---------+---------------+ +| table_catalog | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| partition_name | String | | NO | | FIELD | +| subpartition_name | String | | YES | | FIELD | +| partition_ordinal_position | Int64 | | YES | | FIELD | +| subpartition_ordinal_position | Int64 | | YES | | FIELD | +| partition_method | String | | YES | | FIELD | +| subpartition_method | String | | YES | | FIELD | +| partition_expression | String | | YES | | FIELD | +| subpartition_expression | String | | YES | | FIELD | +| partition_description | String | | YES | | FIELD | +| table_rows | Int64 | | YES | | FIELD | +| avg_row_length | Int64 | | YES | | FIELD | +| data_length | Int64 | | YES | | FIELD | +| max_data_length | Int64 | | YES | | FIELD | +| index_length | Int64 | | YES | | FIELD | +| data_free | Int64 | | YES | | FIELD | +| create_time | TimestampSecond | | YES | | FIELD | +| update_time | TimestampSecond | | YES | | FIELD | +| check_time | TimestampSecond | | YES | | FIELD | +| checksum | Int64 | | YES | | FIELD | +| partition_comment | String | | YES | | FIELD | +| nodegroup | String | | YES | | FIELD | +| tablespace_name | String | | YES | | FIELD | +| greptime_partition_id | UInt64 | | YES | | FIELD | ++-------------------------------+----------+------+------+---------+---------------+ +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, + b STRING, + ts TIMESTAMP TIME INDEX, +) +PARTITION ON COLUMNS (a) ( + a < 10, + 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 + table_schema: public + table_name: test_p + partition_name: p0 + subpartition_name: NULL + partition_ordinal_position: 1 +subpartition_ordinal_position: NULL + partition_method: RANGE + subpartition_method: NULL + partition_expression: (a) VALUES LESS THAN (PartitionExpr { lhs: Column("a"), op: Lt, rhs: Value(Int32(10)) }) + subpartition_expression: NULL + partition_description: NULL + table_rows: NULL + avg_row_length: NULL + data_length: NULL + max_data_length: NULL + index_length: NULL + data_free: NULL + create_time: 2024-04-01 10:49:49.468000 + update_time: NULL + check_time: NULL + checksum: NULL + partition_comment: NULL + nodegroup: NULL + tablespace_name: NULL + greptime_partition_id: 4453881085952 +*************************** 2. row *************************** + table_catalog: greptime + table_schema: public + table_name: test_p + partition_name: p1 + subpartition_name: NULL + partition_ordinal_position: 2 +subpartition_ordinal_position: NULL + partition_method: RANGE + subpartition_method: NULL + partition_expression: (a) VALUES LESS THAN (PartitionExpr { lhs: Column("a"), op: GtEq, rhs: Value(Int32(20)) }) + subpartition_expression: NULL + partition_description: NULL + table_rows: NULL + avg_row_length: NULL + data_length: NULL + max_data_length: NULL + index_length: NULL + data_free: NULL + create_time: 2024-04-01 10:49:49.468000 + update_time: NULL + check_time: NULL + checksum: NULL + partition_comment: NULL + nodegroup: NULL + tablespace_name: NULL + greptime_partition_id: 4453881085954 +*************************** 3. row *************************** + table_catalog: greptime + table_schema: public + table_name: test_p + partition_name: p2 + subpartition_name: NULL + partition_ordinal_position: 3 +subpartition_ordinal_position: NULL + partition_method: RANGE + subpartition_method: NULL + partition_expression: (a) VALUES LESS THAN (PartitionExpr { lhs: Expr(PartitionExpr { lhs: Column("a"), op: Gt, rhs: Value(Int32(10)) }), op: And, rhs: Expr(PartitionExpr { lhs: Column("a"), op: Lt, rhs: Value(Int32(20)) }) }) + subpartition_expression: NULL + partition_description: NULL + table_rows: NULL + avg_row_length: NULL + data_length: NULL + max_data_length: NULL + index_length: NULL + data_free: NULL + create_time: 2024-04-01 10:49:49.468000 + update_time: NULL + check_time: NULL + checksum: NULL + partition_comment: NULL + nodegroup: NULL + tablespace_name: NULL + greptime_partition_id: 4453881085953 +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/procedure-info.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/procedure-info.md new file mode 100644 index 0000000000..484589fa3f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/reference/sql/information-schema/process-list.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/process-list.md new file mode 100644 index 0000000000..b022213728 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/process-list.md @@ -0,0 +1,66 @@ +--- +keywords: [查询, process_list, processlist, 查询管理] +description: 提供当前正在运行的查询列表的内部表。 +--- + +# PROCESS_LIST + +`PROCESS_LIST` 表提供了 GreptimeDB 集群中所有正在运行的查询的视图。 + +:::tip NOTE +`PROCESS_LIST`表特意选择了一个与 MySQL 的 `PROCESSLIST` 不同的名称,因为它们的列并不相通。 +::: + +```sql +USE INFORMATION_SCHEMA; +DESC PROCESS_LIST; +``` + +输出如下: + +```sql ++-----------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-----------------+----------------------+------+------+---------+---------------+ +| id | String | | NO | | FIELD | +| catalog | String | | NO | | FIELD | +| schemas | String | | NO | | FIELD | +| query | String | | NO | | FIELD | +| client | String | | NO | | FIELD | +| frontend | String | | NO | | FIELD | +| start_timestamp | TimestampMillisecond | | NO | | FIELD | +| elapsed_time | DurationMillisecond | | NO | | FIELD | ++-----------------+----------------------+------+------+---------+---------------+ +``` + +`PROCESS_LIST` 表中的字段描述如下: + +- `id`: 查询的 ID。 +- `catalog`: 查询的 catalog 名称。 +- `schemas`: 客户端发出查询时所处的 schema 名称。 +- `query`: 查询语句。 +- `client`: 客户端信息,包括客户端地址和使用的协议。 +- `frontend`: 查询正在运行的 frontend 实例。 +- `start_timestamp`: 查询的开始时间戳。 +- `elapsed_time`: 查询已运行多长时间。 + +:::tip NOTE +你还可以使用 `SHOW [FULL] PROCESSLIST` 语句作为直接查询 `INFORMATION_SCHEMA.PROCESS_LIST` 表的替代方法。 +::: + + +# 终止一个查询 + +当从 `PROCESS_LIST` 表中识别到正在运行的查询时,你可以使用 `KILL ` 语句终止该查询,其中 `` 是 `PROCESS_LIST` 表中的 `id` 字段。 + +```sql +mysql> select * from process_list; ++-----------------------+----------+--------------------+----------------------------+------------------------+---------------------+----------------------------+-----------------+ +| id | catalog | schemas | query | client | frontend | start_timestamp | elapsed_time | ++-----------------------+----------+--------------------+----------------------------+------------------------+---------------------+----------------------------+-----------------+ +| 112.40.36.208/7 | greptime | public | SELECT * FROM some_very_large_table | mysql[127.0.0.1:34692] | 112.40.36.208:4001 | 2025-06-30 07:04:11.118000 | 00:00:12.002000 | ++-----------------------+----------+--------------------+----------------------------+------------------------+---------------------+----------------------------+-----------------+ + +KILL '112.40.36.208/7'; +Query OK, 1 row affected (0.00 sec) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/region-peers.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/region-peers.md new file mode 100644 index 0000000000..699d60f3bd --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/region-peers.md @@ -0,0 +1,50 @@ +--- +keywords: [Region 节点信息, REGION_PEERS 表, 节点状态, leader, learner] +description: REGION_PEERS 表显示 GreptimeDB 中单个 Region 节点的详细信息,例如它是 learner 还是 leader。 +--- + +# REGION_PEERS + +`REGION_PEERS` 表显示了 GreptimeDB 中单个 Region 节点的详细信息,例如它是 learner 还是 leader。 + +:::tip 注意 +该表在 [GreptimeCloud](https://greptime.cloud/) 中不可用。 +::: + +```sql +USE INFORMATION_SCHEMA; +DESC REGION_PEERS; +``` + +结果如下: + +```sql ++--------------+--------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++---------------+--------+------+------+---------+---------------+ +| table_catalog | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| region_id | UInt64 | | NO | | FIELD | +| peer_id | UInt64 | | YES | | FIELD | +| peer_addr | String | | YES | | FIELD | +| is_leader | String | | YES | | FIELD | +| status | String | | YES | | FIELD | +| down_seconds | Int64 | | YES | | FIELD | ++---------------+--------+------+------+---------+---------------+ +6 rows in set (0.00 sec) +``` + +`REGION_PEERS` 表中的字段描述如下: + +- `table_catalog`:表所属的目录。 +- `table_schema`:表所属的数据库。 +- `table_name`:表的名称。 +- `region_id`:Region 的 ID。 +- `peer_id`:Region peer 的 ID。 +- `peer_addr`:peer 的地址。 +- `is_leader`:peer 是否为 leader。 +- `status`:peer 的状态,`ALIVE` 或 `DOWNGRADED`。 + - `ALIVE`:peer 在线。 + - `DOWNGRADED`:Region peer 不可用(例如,已崩溃、网络断开),或者计划将 Region peer 迁移到另一个 peer。 +- `down_seconds`:离线时长,单位为秒。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/region-statistics.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/region-statistics.md new file mode 100644 index 0000000000..7c4790d926 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/region-statistics.md @@ -0,0 +1,71 @@ +--- +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 | +| written_bytes_since_open | UInt64 | | YES | | FIELD | +| disk_size | UInt64 | | YES | | FIELD | +| memtable_size | UInt64 | | YES | | FIELD | +| manifest_size | UInt64 | | YES | | FIELD | +| sst_size | UInt64 | | YES | | FIELD | +| sst_num | 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 中的记录行数。 +- `written_bytes_since_open`: Region 自打开以来写入的字节数。 +- `disk_size`: Region 中数据文件的总大小,包括数据、索引及元信息等。 +- `memtable_size`: Region 中内存 memtables 的总大小。 +- `manifest_size`: Region 中元信息 manifest 文件的总大小。 +- `sst_num`: Region 中 SST 文件的总数量。 +- `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 | written_bytes_since_open | disk_size | memtable_size | manifest_size | sst_size | sst_num | index_size | engine | region_role | ++---------------+----------+---------------+-------------+--------------------------+-----------+---------------+---------------+----------+---------+------------+--------+-------------+ +| 4398046511104 | 1024 | 0 | 8 | 0 | 4922 | 0 | 1338 | 3249 | 1 | 335 | mito | Leader | ++---------------+----------+---------------+-------------+--------------------------+-----------+---------------+---------------+----------+---------+------------+--------+-------------+ +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/runtime-metrics.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/runtime-metrics.md new file mode 100644 index 0000000000..de74a3f02b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/runtime-metrics.md @@ -0,0 +1,58 @@ +--- +keywords: [运行时指标, RUNTIME_METRICS 表, 系统指标, 集群指标, HTTP 端点] +description: RUNTIME_METRICS 表提供系统运行时指标,包括集群中 `/metrics` HTTP 端点输出的所有指标。 +--- + +# RUNTIME_METRICS + +`RUNTIME_METRICS`表提供系统运行时指标。它包括集群中`/metrics` HTTP 端点输出的所有指标。 + +```sql +USE INFORMATION_SCHEMA; + +SELECT * FROM RUNTIME_METRICS; +``` + +结果如下: + +```sql ++------------------------------------------------------+------------------------+--------------------------------------------------------+---------+-----------+----------------------------+ +| metric_name | value | labels | node | node_type | timestamp | ++------------------------------------------------------+------------------------+--------------------------------------------------------+---------+-----------+----------------------------+ +| greptime_app_version | 1 | short_version=0.7.1, version=greptimedb-main-92a8e86 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_catalog_catalog_count | 1 | | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_catalog_schema_count | 2 | | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.005 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.01 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.025 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.05 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.1 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.25 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.5 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=1 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=2.5 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=5 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=10 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=+Inf | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_sum | 0.000290333 | | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_count | 1 | | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_counter | 1 | | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.005 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.01 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.025 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.05 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.1 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.25 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.5 | unknown | unknown | 2024-03-27 22:43:12.898000 | + +... +``` + +结果中的列: + +* `metric_name`:指标名称。 +* `value`:指标值。 +* `labels`:指标标签和值,用`,`分隔。 +* `node:` 指标来自哪个节点 +* `node_type`:节点类型,如`datanode`、`frontend`等。 +* `timestamp`:指标时间戳 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/schemata.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/schemata.md new file mode 100644 index 0000000000..a2aaf6d0e3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/schemata.md @@ -0,0 +1,52 @@ +--- +keywords: [数据库信息, SCHEMATA 表, SHOW DATABASES, 字段描述, 数据库目录] +description: SCHEMATA 表提供数据库的相关信息及其字段描述。 +--- + +# SCHEMATA + +`SCHEMATA` 表提供数据库的相关信息。表数据等同于 `SHOW DATABASES` 语句的结果。 + +```sql +USE INFORMATION_SCHEMA; +DESC SCHEMATA; +``` + +结果如下: + +```sql ++----------------------------+--------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++----------------------------+--------+------+------+---------+---------------+ +| catalog_name | String | | NO | | FIELD | +| schema_name | String | | NO | | FIELD | +| default_character_set_name | String | | NO | | FIELD | +| default_collation_name | String | | NO | | FIELD | +| sql_path | String | | YES | | FIELD | +| options | String | | YES | | FIELD | ++----------------------------+--------+------+------+---------+---------------+ +``` + +```sql +SELECT * FROM SCHEMATA; +``` + +```sql ++--------------+--------------------+----------------------------+------------------------+----------+-------------+ +| 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` 表中的字段描述如下: + +- `catalog_name`:数据库所属的目录。 +- `schema_name`:数据库的名称。 +- `default_character_set_name`:数据库的默认字符集。 +- `default_collation_name`:数据库的默认排序规则。 +- `sql_path`:该项的值始终为 `NULL`。 +- `options`: GreptimeDB 扩展字段,数据库的配置参数。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/ssts-index-meta.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/ssts-index-meta.md new file mode 100644 index 0000000000..d63ba80ea6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/ssts-index-meta.md @@ -0,0 +1,124 @@ +--- +keywords: [SST 索引元数据, Puffin 索引, 倒排索引, 全文索引, 布隆过滤器, 索引元数据] +description: 提供对 SST(排序字符串表)索引元数据的访问,包括以 Puffin 格式存储的倒排索引、全文索引和布隆过滤器的信息。 +--- + +# SSTS_INDEX_META + +`SSTS_INDEX_META` 表提供对从清单中收集的 SST(排序字符串表)索引元数据的访问。该表显示 Puffin 索引元数据的信息,包括倒排索引、全文索引和布隆过滤器。 + +:::tip 注意 +此表在 [GreptimeCloud](https://greptime.cloud/) 上不可用。 +::: + +```sql +USE INFORMATION_SCHEMA; +DESC SSTS_INDEX_META; +``` + +输出如下: + +```sql ++-----------------+--------+-----+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-----------------+--------+-----+------+---------+---------------+ +| table_dir | String | | NO | | FIELD | +| index_file_path | String | | NO | | FIELD | +| region_id | UInt64 | | NO | | FIELD | +| table_id | UInt32 | | NO | | FIELD | +| region_number | UInt32 | | NO | | FIELD | +| region_group | UInt8 | | NO | | FIELD | +| region_sequence | UInt32 | | NO | | FIELD | +| file_id | String | | NO | | FIELD | +| index_file_size | UInt64 | | YES | | FIELD | +| index_type | String | | NO | | FIELD | +| target_type | String | | NO | | FIELD | +| target_key | String | | NO | | FIELD | +| target_json | String | | NO | | FIELD | +| blob_size | UInt64 | | NO | | FIELD | +| meta_json | String | | YES | | FIELD | +| node_id | UInt64 | | YES | | FIELD | ++-----------------+--------+-----+------+---------+---------------+ +``` + +`SSTS_INDEX_META` 表中的字段描述如下: + +- `table_dir`:表的目录路径。 +- `index_file_path`:Puffin 索引文件的完整路径。 +- `region_id`:Region 的 ID。 +- `table_id`:表的 ID。 +- `region_number`:表中的 Region 编号。 +- `region_group`:Region 的组标识符。 +- `region_sequence`:Region 的序列号。 +- `file_id`:索引文件的唯一标识符(UUID)。 +- `index_file_size`:索引文件的大小(字节)。 +- `index_type`:索引的类型。可能的值包括: + - `inverted`:用于快速词条查找的倒排索引 + - `fulltext_bloom`:全文索引和布隆过滤器的组合索引 + - `bloom_filter`:用于快速成员测试的布隆过滤器 +- `target_type`:被索引目标的类型。通常是 `column`,表示基于列的索引。 +- `target_key`:标识目标的键(例如,列 ID)。 +- `target_json`:目标配置的 JSON 表示,例如 `{"column":0}`。 +- `blob_size`:blob 数据的大小(字节)。 +- `meta_json`:包含索引特定信息的 JSON 元数据,例如: + - 对于倒排索引:FST 大小、位图类型、段行数等 + - 对于布隆过滤器:布隆过滤器大小、行数、段数 + - 对于全文索引:分析器类型、大小写敏感设置 +- `node_id`:索引所在数据节点的 ID。 + +## 示例 + +查询所有索引元数据: + +```sql +SELECT * FROM INFORMATION_SCHEMA.SSTS_INDEX_META; +``` + +通过与 `TABLES` 表连接查询特定表的索引元数据: + +```sql +SELECT s.* +FROM INFORMATION_SCHEMA.SSTS_INDEX_META s +JOIN INFORMATION_SCHEMA.TABLES t ON s.table_id = t.table_id +WHERE t.table_name = 'my_table'; +``` + +仅查询倒排索引元数据: + +```sql +SELECT table_dir, index_file_path, index_type, target_json, meta_json +FROM INFORMATION_SCHEMA.SSTS_INDEX_META +WHERE index_type = 'inverted'; +``` + +按索引类型分组查询索引元数据: + +```sql +SELECT index_type, COUNT(*) as count, SUM(index_file_size) as total_size +FROM INFORMATION_SCHEMA.SSTS_INDEX_META +GROUP BY index_type; +``` + +输出样例: + +```sql +mysql> SELECT * FROM INFORMATION_SCHEMA.SSTS_INDEX_META LIMIT 1\G; +*************************** 1. row *************************** + table_dir: data/greptime/public/1814/ +index_file_path: data/greptime/public/1814/1814_0000000000/data/index/aba4af59-1247-4bfb-a20b-69242cdd9374.puffin + region_id: 7791070674944 + table_id: 1814 + region_number: 0 + region_group: 0 +region_sequence: 0 + file_id: aba4af59-1247-4bfb-a20b-69242cdd9374 +index_file_size: 838 + index_type: bloom_filter + target_type: column + target_key: 2147483652 + target_json: {"column":2147483652} + blob_size: 688 + meta_json: {"bloom":{"bloom_filter_size":640,"row_count":2242,"rows_per_segment":1024,"segment_count":3}} + node_id: 0 +1 row in set (0.02 sec) +``` \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/ssts-manifest.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/ssts-manifest.md new file mode 100644 index 0000000000..53dadebada --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/ssts-manifest.md @@ -0,0 +1,139 @@ +--- +keywords: [SST manifest, SST 文件, region 文件, 文件元数据, 表数据文件] +description: 提供从 manifest 中获取的 SST(排序字符串表)文件信息,包括文件路径、大小、时间范围和行数。 +--- + +# SSTS_MANIFEST + +`SSTS_MANIFEST` 表提供从清单中收集的 SST(排序字符串表)文件信息。此表显示每个 SST 文件的详细信息,包括文件路径、大小、级别、时间范围和行数。 + +:::tip 注意 +此表在 [GreptimeCloud](https://greptime.cloud/) 上不可用。 +::: + +```sql +USE INFORMATION_SCHEMA; +DESC SSTS_MANIFEST; +``` + +输出如下: + +```sql ++------------------+---------------------+-----+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++------------------+---------------------+-----+------+---------+---------------+ +| table_dir | String | | NO | | FIELD | +| region_id | UInt64 | | NO | | FIELD | +| table_id | UInt32 | | NO | | FIELD | +| region_number | UInt32 | | NO | | FIELD | +| region_group | UInt8 | | NO | | FIELD | +| region_sequence | UInt32 | | NO | | FIELD | +| file_id | String | | NO | | FIELD | +| level | UInt8 | | NO | | FIELD | +| file_path | String | | NO | | FIELD | +| file_size | UInt64 | | NO | | FIELD | +| index_file_path | String | | YES | | FIELD | +| index_file_size | UInt64 | | YES | | FIELD | +| num_rows | UInt64 | | NO | | FIELD | +| num_row_groups | UInt64 | | NO | | FIELD | +| min_ts | TimestampNanosecond | | YES | | FIELD | +| max_ts | TimestampNanosecond | | YES | | FIELD | +| sequence | UInt64 | | YES | | FIELD | +| origin_region_id | UInt64 | | NO | | FIELD | +| node_id | UInt64 | | YES | | FIELD | +| visible | Boolean | | NO | | FIELD | ++------------------+---------------------+-----+------+---------+---------------+ +``` + +`SSTS_MANIFEST` 表中的字段描述如下: + +- `table_dir`:表的目录路径。 +- `region_id`:引用该文件的 Region ID。 +- `table_id`:表的 ID。 +- `region_number`:表中的 Region 编号。 +- `region_group`:Region 的组标识符。 +- `region_sequence`:Region 的序列号。 +- `file_id`:SST 文件的唯一标识符(UUID)。 +- `level`:LSM 树中的 SST 级别(0 表示未压缩,1 表示已压缩)。 +- `file_path`:对象存储中 SST 文件的完整路径。 +- `file_size`:SST 文件的大小(字节)。 +- `index_file_path`:对象存储中索引文件的完整路径(如果存在)。 +- `index_file_size`:索引文件的大小(字节,如果存在)。 +- `num_rows`:SST 文件中的行数。 +- `num_row_groups`:SST 文件中的行组数。 +- `min_ts`:SST 文件中的最小时间戳。 +- `max_ts`:SST 文件中的最大时间戳。 +- `sequence`:与此文件关联的序列号。 +- `origin_region_id`:创建该文件的 Region ID。 +- `node_id`:文件所在的数据节点 ID。 +- `visible`:该文件在当前版本中是否可见。 + +## 示例 + +查询清单中的所有 SST 文件: + +```sql +SELECT * FROM INFORMATION_SCHEMA.SSTS_MANIFEST; +``` + +通过与 `TABLES` 表连接查询特定表的 SST 文件: + +```sql +SELECT s.* +FROM INFORMATION_SCHEMA.SSTS_MANIFEST s +JOIN INFORMATION_SCHEMA.TABLES t ON s.table_id = t.table_id +WHERE t.table_name = 'my_table'; +``` + +仅查询已压缩的 SST 文件(级别 1): + +```sql +SELECT file_path, file_size, num_rows, level +FROM INFORMATION_SCHEMA.SSTS_MANIFEST +WHERE level = 1; +``` + +查询 SST 文件及其时间范围: + +```sql +SELECT table_id, file_path, num_rows, min_ts, max_ts +FROM INFORMATION_SCHEMA.SSTS_MANIFEST +ORDER BY table_id, min_ts; +``` + +计算每个表的 SST 文件总大小: + +```sql +SELECT table_id, COUNT(*) as sst_count, SUM(file_size) as total_size +FROM INFORMATION_SCHEMA.SSTS_MANIFEST +GROUP BY table_id; +``` + + +输出样例: + +```sql +mysql> SELECT * FROM INFORMATION_SCHEMA.SSTS_MANIFEST LIMIT 1\G; +*************************** 1. row *************************** + table_dir: data/greptime/public/1024/ + region_id: 4398046511104 + table_id: 1024 + region_number: 0 + region_group: 0 + region_sequence: 0 + file_id: 01234567-89ab-cdef-0123-456789abcdef + level: 0 + file_path: data/greptime/public/1024/4398046511104_0/01234567-89ab-cdef-0123-456789abcdef.parquet + file_size: 1234 + index_file_path: data/greptime/public/1024/4398046511104_0/index/01234567-89ab-cdef-0123-456789abcdef.puffin + index_file_size: 256 + num_rows: 100 + num_row_groups: 1 + min_ts: 2025-01-01 00:00:00.000000000 + max_ts: 2025-01-01 00:01:00.000000000 + sequence: 1 +origin_region_id: 4398046511104 + node_id: 0 + visible: true +1 row in set (0.02 sec) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/ssts-storage.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/ssts-storage.md new file mode 100644 index 0000000000..2fe29286fa --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/ssts-storage.md @@ -0,0 +1,104 @@ +--- +keywords: [SST storage, SST 文件, 文件列表, 存储层, 对象存储] +description: 提供从存储层直接获取的 SST(排序字符串表)文件信息,包括文件路径、大小和最后修改时间戳。 +--- + +# SSTS_STORAGE + +`SSTS_STORAGE` 表提供直接从存储层列出的 SST(排序字符串表)文件信息。此表显示来自对象存储的原始文件元数据,可能包括尚未反映在清单中的文件或已孤立的文件。 + +:::tip 注意 +此表在 [GreptimeCloud](https://greptime.cloud/) 上不可用。 +::: + +```sql +USE INFORMATION_SCHEMA; +DESC SSTS_STORAGE; +``` + +输出如下: + +```sql ++------------------+----------------------+-----+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++------------------+----------------------+-----+------+---------+---------------+ +| file_path | String | | NO | | FIELD | +| file_size | UInt64 | | YES | | FIELD | +| last_modified_ms | TimestampMillisecond | | YES | | FIELD | +| node_id | UInt64 | | YES | | FIELD | ++------------------+----------------------+-----+------+---------+---------------+ +``` + +`SSTS_STORAGE` 表中的字段描述如下: + +- `file_path`:对象存储中文件的完整路径。 +- `file_size`:文件的大小(字节,如果存储中可用)。 +- `last_modified_ms`:最后修改时间(毫秒,如果存储中可用)。 +- `node_id`:文件所在的数据节点 ID。 + +## 使用场景 + +`SSTS_STORAGE` 表适用于: + +- **存储验证**:将存储中的文件与清单进行比较,以检测孤立文件或不一致性。 +- **存储调试**:识别存在于存储中但可能未在清单中正确跟踪的文件。 +- **清理操作**:查找并删除不再被引用的孤立 SST 文件。 +- **存储审计**:获取存储层中所有 SST 文件的完整视图。 + +## 示例 + +查询存储中的所有 SST 文件: + +```sql +SELECT * FROM INFORMATION_SCHEMA.SSTS_STORAGE; +``` + +查找存储中但不在清单中的文件(潜在的孤立文件): + +```sql +SELECT s.file_path, s.file_size, s.last_modified_ms +FROM INFORMATION_SCHEMA.SSTS_STORAGE s +LEFT JOIN INFORMATION_SCHEMA.SSTS_MANIFEST m ON s.file_path = m.file_path +WHERE m.file_path IS NULL; +``` + +查找存储中最大的 SST 文件: + +```sql +SELECT file_path, file_size +FROM INFORMATION_SCHEMA.SSTS_STORAGE +WHERE file_size IS NOT NULL +ORDER BY file_size DESC +LIMIT 10; +``` + +计算 SST 文件的总存储使用量: + +```sql +SELECT COUNT(*) as file_count, SUM(file_size) as total_size +FROM INFORMATION_SCHEMA.SSTS_STORAGE +WHERE file_size IS NOT NULL; +``` + + +输出样例: + +```sql +mysql> SELECT * FROM INFORMATION_SCHEMA.SSTS_STORAGE LIMIT 1\G; +*************************** 1. row *************************** + file_path: data/greptime/public/1024/4398046511104_0/01234567-89ab-cdef-0123-456789abcdef.parquet + file_size: 1234 +last_modified_ms: 2025-01-01 00:00:00.000 + node_id: 0 +1 row in set (0.02 sec) +``` + +## 与 SSTS_MANIFEST 的区别 + +| 方面 | SSTS_MANIFEST | SSTS_STORAGE | +|------|---------------|--------------| +| **数据源** | 清单元数据 | 直接从存储层 | +| **信息** | 详细的 SST 元数据(行数、时间范围等) | 仅基本文件元数据 | +| **文件覆盖** | 仅清单中跟踪的文件 | 存储中的所有文件 | +| **使用场景** | 查询 SST 元数据进行分析 | 验证存储、查找孤立文件 | +| **性能** | 快速(从清单读取) | 较慢(扫描存储) | diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/table-constraints.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/table-constraints.md new file mode 100644 index 0000000000..f549079056 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/reference/sql/information-schema/tables.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/tables.md new file mode 100644 index 0000000000..e5242b9fba --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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 | TimestampSecond | | YES | | FIELD | +| update_time | TimestampSecond | | YES | | FIELD | +| check_time | TimestampSecond | | 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-1.0/reference/sql/information-schema/views.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/information-schema/views.md new file mode 100644 index 0000000000..7789bbd64e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/reference/sql/insert.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/insert.md new file mode 100644 index 0000000000..243e0bbfb4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/insert.md @@ -0,0 +1,134 @@ +--- +keywords: [SQL INSERT 语句, 插入数据, 多条记录插入, 默认值插入, 二进制数据插入, 特殊数值插入] +description: INSERT 用于将一条或多条记录插入到 GreptimeDB 中的表中,支持指定列名和使用默认值。 +--- + +# INSERT + +`INSERT` 用于将一条或多条记录插入到 GreptimeDB 中的表中。 + +## `INSERT INTO` Statement + +### Syntax + +`INSERT INTO` 语法如下: + +```sql +INSERT INTO table_name (column1, column2, column3, ...) +VALUES (value1, value2, value3, ...); +``` + +在上述语法中,`table_name` 是要插入数据的表名,`column1`、`column2`、`column3` 等是表中的列名。 +如果你想要插入数据到指定的列中,可以在 `INSERT INTO` 语句中指定列名。 +如果你不指定列名,数据将会插入到表中的所有列中。 + +`VALUES` 关键字后面跟着的是一个值列表,这个值列表的顺序必须和 `INSERT INTO` 语句中的列顺序一致。 + +VALUES 值支持以下数据类型: + +- `DEFAULT` 关键字指定该列的默认值。 +这在你不想在插入记录时显式指定某些列的值时非常有用。 +它允许使用表 schema 中定义的列默认值来替代需要显示指定的值。 +如果该列没有定义默认值,将会使用数据库的默认值(通常是 NULL)。 +- 使用十六进制字面值插入二进制字面值。 +- 使用 `{Value}::{Type}` 语法将特殊的数值 `Infinity`、`-Infinity` 和 `NaN` 转换为指定的数值类型。 + +### 示例 + +#### 插入数据 + +使用 `INSERT INTO` 语句将一条记录插入到名为 `system_metrics` 的表中: + +```sql +INSERT INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES + ("host1", "idc_b", 50.0, 66.7, 40.6, 1667446797462); +``` + +上述语句将一条记录插入到 `system_metrics` 表中,该记录的 host 为 "host1",idc 为 "idc_b",cpu_util 为 50.0,memory_util 为 66.7, + +你还可以使用 `INSERT INTO` 语句一次向表中插入多条记录,例如向 `system_metrics` 表中插入多条记录: + +```sql +INSERT INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES + ("host1", "idc_a", 11.8, 10.3, 10.3, 1667446797460), + ("host2", "idc_a", 80.1, 70.3, 90.0, 1667446797461), + ("host1", "idc_c", 50.1, 66.8, 40.8, 1667446797463); +``` + +此语句将三条记录插入到 `system_metrics` 表中,每列都有指定的值。 + +#### 使用默认值插入数据 + +下面的 SQL 语句使用 `DEFAULT` 关键字为 `cpu_util` 列插入默认值: + +```sql +INSERT INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES ("host1", "idc_a", DEFAULT, 10.3, 10.3, 1667446797460); +``` + +#### 插入二进制数据 + +当我们想要插入二进制数据时,其列的数据类型为 `blob` 或 `bytea`: + +```sql +CREATE TABLE test(b BLOB, ts TIMESTAMP TIME INDEX); +``` + +推荐使用预编译语句,例如 JDBC: + +```java + PreparedStatement pstmt = conn.prepareStatement("insert into test values(?,?)"); + pstmt.setBytes(1, "hello".getBytes()); + pstmt.setInt(2, 1687867163); + pstmt.addBatch(); + ...... + pstmt.executeBatch(); +``` + +如果我们想要插入字面值的二进制数据,可以使用十六进制字面值: + +```sql +INSERT INTO test VALUES(X'9fad5e9eefdfb449', 1687867163); +-- or -- +INSERT INTO test VALUES(0x9fad5e9eefdfb449', 1687867163); +``` + +#### 插入特殊数字值 + +使用 `{Value}::{Type}` 将特殊的数值 `Infinity`、`-Infinity` 和 `NaN` 转换为指定的数值类型: + +```sql +INSERT INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES ("host1", "idc_a", 66.6, 'NaN'::double, 'Infinity'::double, 1667446797460); +``` + +## `INSERT INTO SELECT` Statement + +`INSERT INTO SELECT` 语句用于将一张表中的数据复制到另一张表中。 + +### Syntax + +`INSERT INTO SELECT` 的语法如下: + +```sql +INSERT INTO table2 (column1, column2, ...) +SELECT column1, column2, ... +FROM table1; +``` + +在上述语法中,`table1` 是你想要从中复制数据的源表,`table2` 是你想要将数据插入的目标表。 +`table1` 和 `table2` 需要有用于复制数据的拥有同样名称和数据类型的列。 +`SELECT` 语句从源表中选择要插入的列。 +如果在`INSERT INTO`语句中没有指定列名,那么数据将被插入到目标表的所有列中。 + +当你想要从一个表中复制数据到另一个表时,`INSERT INTO SELECT` 语句非常有用。例如归档或备份数据时,比起备份整个数据库并恢复,这种方式更加高效。 + +### 示例 + +```sql +INSERT INTO system_metrics2 (host, idc, cpu_util, memory_util, disk_util, ts) +SELECT host, idc, cpu_util, memory_util, disk_util, ts +FROM system_metrics; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/join.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/join.md new file mode 100644 index 0000000000..457c540ac6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/join.md @@ -0,0 +1,40 @@ +--- +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` 用于组合两个或多个表中基于相关列的行。 +它允许你从多个表中提取数据,并将其呈现为单个结果集。 + +JOIN 语法有以下类型: + +- INNER JOIN:仅返回两个表中具有匹配值的行。 +- LEFT JOIN:返回左表中的所有行和右表中的匹配行。 +- RIGHT JOIN:返回右表中的所有行和左表中的匹配行。 +- FULL OUTER JOIN:返回两个表中的所有行。 + +## 示例 + +下面是使用 JOIN 子句的一些示例: + +```sql +-- Select all rows from the system_metrics table and idc_info table where the idc_id matches +SELECT a.* +FROM system_metrics a +JOIN idc_info b +ON a.idc = b.idc_id; + +-- Select all rows from the idc_info table and system_metrics table where the idc_id matches, and include null values for idc_info without any matching system_metrics +SELECT a.* +FROM idc_info a +LEFT JOIN system_metrics b +ON a.idc_id = b.idc; + +-- Select all rows from the system_metrics table and idc_info table where the idc_id matches, and include null values for idc_info without any matching system_metrics +SELECT b.* +FROM system_metrics a +RIGHT JOIN idc_info b +ON a.idc = b.idc_id; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/limit.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/limit.md new file mode 100644 index 0000000000..9b48d03258 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/limit.md @@ -0,0 +1,86 @@ +--- +keywords: [SQL LIMIT 子句, 查询行数限制, SQL 性能优化, 数据库查询优化, SQL 示例] +description: 介绍了 `LIMIT` 子句的用法,通过示例展示了如何限制查询返回的行数。 +--- + +# LIMIT + +`LIMIT` 用于限制查询返回的行数。当处理大数据集时该子句特别有用,因为它通过减少需要处理的数据量来提高查询性能。 + +## Syntax + +`LIMIT` 的基本语法如下: + +```sql +SELECT column1, column2, ... +FROM table_name +LIMIT number_of_rows; +``` + +`number_of_rows` 参数用于指定要返回的最大行数。如果该参数的值为负数,则不返回任何行。 + +## 示例 + +假如我们有一个名为 `system_metrics` 的表: + +```sql ++-------+-------+----------+-------------+-----------+---------------------+ +| host | idc | cpu_util | memory_util | disk_util | ts | ++-------+-------+----------+-------------+-----------+---------------------+ +| host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 | +| host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 | +| host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 | ++-------+-------+----------+-------------+-----------+---------------------+ +``` + +使用 `LIMIT` 获取 `memory_util` 列中的前 3 个值: + +```sql +SELECT host, idc, memory_util +FROM system_metrics +ORDER BY memory_util DESC +LIMIT 3; +``` + +结果为: + +```sql ++-------+-------+-------------+ +| host | idc | memory_util | ++-------+-------+-------------+ +| host2 | idc_a | 70.3 | +| host1 | idc_c | 66.8 | +| host1 | idc_b | 66.7 | ++-------+-------+-------------+ +``` + +`LIMIT n, m` 允许在跳过前 n 行后从结果中选择 m 行,等价于`LIMIT m OFFSET n` 语法。 + +```sql +SELECT host, idc, memory_util +FROM system_metrics +ORDER BY memory_util DESC +LIMIT 2 OFFSET 1; +``` + +或 + +```sql +SELECT host, idc, memory_util +FROM system_metrics +ORDER BY memory_util DESC +LIMIT 1, 2; +``` + +结果如下: + +```sql ++-------+-------+-------------+ +| host | idc | memory_util | ++-------+-------+-------------+ +| host1 | idc_c | 66.8 | +| host1 | idc_b | 66.7 | ++-------+-------+-------------+ +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/offset.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/offset.md new file mode 100644 index 0000000000..b302b70cba --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/offset.md @@ -0,0 +1,46 @@ +--- + +keywords: [SQL OFFSET 子句, 数据检索, 跳过行] +description: 描述 SQL 中的 OFFSET 子句,该子句指定在开始从查询返回行之前要跳过的行数。 +--- + +# OFFSET + +`OFFSET` 子句指定在开始从查询返回行之前要跳过的行数。它通常与 LIMIT 结合使用,用于对大型结果集进行分页。 + +例如: +```sql +SELECT * +FROM system_metrics +ORDER BY cpu_util DESC +LIMIT 10 +OFFSET 10; +``` + +它从 `system_metrics` 表中选择按降序 `cpu_util` 排序的第 11 到 20 行的所有列。 + +虽然将 `OFFSET` 和 `LIMIT` 与 `ORDER BY` 子句结合使用可以实现分页,但这种方法效率不高。我们建议记录每页返回的最后一条记录的时间索引(时间戳),并使用该值来过滤和限制后续页面的数据。这种方法提供了更好的分页性能。 + +## 使用时间戳的高效分页 +假设您的 `system_metrics` 表有一个作为时间索引(时间戳)的 `ts` 列。您可以使用上一页最后一条记录的时间戳来高效地获取下一页。 + +第一页(最新的 10 条记录): +```sql +SELECT * +FROM system_metrics +ORDER BY ts DESC +LIMIT 10; +``` + +第二页(使用上一页的最后一个时间戳),如果第一页的最后一条记录的 `ts` 值为 `'2024-07-01 16:03:00'`,您可以这样获取下一页: + +```sql +SELECT * +FROM system_metrics +WHERE ts < '2024-07-01 16:03:00' +ORDER BY ts DESC +LIMIT 10; +``` + +每次查询后,记录最后一行的 `ts` 值并将其用于下一个查询的过滤器。 +这种方法消除了扫描和跳过行(如使用 OFFSET)的需要,从而使分页效率更高,尤其是在大型表中。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/order_by.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/order_by.md new file mode 100644 index 0000000000..f7b06609a6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/order_by.md @@ -0,0 +1,78 @@ +--- +keywords: [ORDER BY 语法, 数据排序, 升序排序, 降序排序, SQL 示例] +description: 介绍了 `ORDER BY` 语法的基本用法,通过示例展示了如何对数据进行升序或降序排序。 +--- + +# ORDER BY + +`ORDER BY` 语法用于根据 `SELECT` 语句中的一个或多个列对数据进行升序或降序排序。 + +# Syntax + +`ORDER BY` 的基本语法如下: + +```sql +SELECT column1, column2, ... +FROM table_name +ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...; +``` + +`ORDER BY` 可以用于一个或多个列。ASC 关键字用于升序排序(默认),DESC 关键字用于降序排序。 + +# 示例 + +假如我们有一个名为 `system_metrics` 的表: + +```sql ++-------+-------+----------+-------------+-----------+---------------------+ +| host | idc | cpu_util | memory_util | disk_util | ts | ++-------+-------+----------+-------------+-----------+---------------------+ +| host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 | +| host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 | +| host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 | ++-------+-------+----------+-------------+-----------+---------------------+ +``` + +要根据 `memory_util` 列对数据进行升序排序,可以使用以下 SQL 语句: + +```sql +SELECT * FROM system_metrics +ORDER BY memory_util ASC; +``` + +结果为: + +```sql ++-------+-------+----------+-------------+-----------+---------------------+ +| host | idc | cpu_util | memory_util | disk_util | ts | ++-------+-------+----------+-------------+-----------+---------------------+ +| host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 | +| host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 | +| host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 | ++-------+-------+----------+-------------+-----------+---------------------+ +``` + +要根据 `disk_util` 列对数据进行降序排序,可以使用以下 SQL 语句: + +```sql +SELECT * FROM system_metrics +ORDER BY disk_util DESC; +``` + +结果为: + +```sql ++-------+-------+----------+-------------+-----------+---------------------+ +| host | idc | cpu_util | memory_util | disk_util | ts | ++-------+-------+----------+-------------+-----------+---------------------+ +| host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 | +| host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 | +| host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 | ++-------+-------+----------+-------------+-----------+---------------------+ +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/overview.md new file mode 100644 index 0000000000..f5ae4ee38d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/overview.md @@ -0,0 +1,51 @@ +--- +keywords: [SQL 语法, SQL 示例] +description: GreptimeDB SQL 语句. +--- + +# SQL + +## 数据类型 + +* [数据类型](data-types.md) + +## 语句和子句 + +* [ADMIN](./admin.md) +* [ALTER](./alter.md) +* [ANSI Compatibility](./compatibility.md) +* [CASE](./case.md) +* [CAST](./cast.md) +* [COPY](./copy.md) +* [CREATE](./create.md) +* [DELETE](./delete.md) +* [DESCRIBE TABLE](./describe_table.md) +* [DISTINCT](./distinct.md) +* [DROP](./drop.md) +* [EXPLAIN](./explain.md) +* [GROUP BY](./group_by.md) +* [HAVING](./having.md) +* [INSERT](./insert.md) +* [JOIN](./join.md) +* [LIMIT](./limit.md) +* [OFFSET](./offset.md) +* [ORDER BY](./order_by.md) +* [RANGE](./range.md) +* [REPLACE](./replace.md) +* [SELECT](./select.md) +* [SHOW](./show.md) +* [TQL](./tql.md) +* [TRUNCATE](./truncate.md) +* [WHERE](./where.md) +* [WITH](./with.md) + +## 函数 +* [Functions](./functions/overview.md) + +## 系统表 + +* [INFORMATION_SCHEMA](./information-schema/overview.md) + +## Greptime Private 内的系统表 + +* [Greptime Private](./greptime-private/overview.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/range.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/range.md new file mode 100644 index 0000000000..728648c0a1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/range.md @@ -0,0 +1,729 @@ +--- +keywords: [Range 查询, 时间范围查询, 聚合查询, SQL 示例, FILL 选项] +description: 介绍了 Range 查询的语法和用法,包括 `FILL`、`TO` 和 `BY` 选项的详细说明和示例。 +--- + +# RANGE QUERY + +查询并聚合一个给定长度的时间范围的数据是时序数据常见的一种查询模式,例如 `PromQL` 中的 `Range selector`。而 GreptimeDB 在 SQL 中支持了 Range 查询,用于将时序数据汇总为时间块,并在时间块上进行数据的聚合。Range 查询作为 `SELECT` 语句的一部分,可与 SQL 灵活结合,从而在 SQL 中提供更强大的时序数据查询能力。 + +## Syntax + +Range query 使用 `Time Index` 列作为聚合的时间线。 +一个合法的 Range 查询语法结构如下所示: + +```sql +SELECT + AGGR_FUNCTION(column1, column2,..) RANGE INTERVAL [FILL FILL_OPTION], + ... +FROM table_name + [ WHERE ] +ALIGN INTERVAL [ TO TO_OPTION ] [BY (columna, columnb,..)] [FILL FILL_OPTION] + [ ORDER BY ] +[ LIMIT ]; + +INTERVAL := TIME_INTERVAL | ( INTERVAL expr ) +``` + +- 关键字 `ALIGN`,必选字段,后接参数 `INTERVAL` ,`ALIGN` 指明了 Range 查询的步长。 + - 子关键字 `TO` ,可选字段,指定 Range 查询对齐到的时间点,合法的 `TO_OPTION` 参数见[TO Option](#to-选项) 。 + - 子关键字 `BY` ,可选字段,后接参数 `(columna, columnb,..)` ,描述了聚合键。详情请见[BY OPTION](#by-选项)。 +- 参数 `INTERVAL` ,主要用于给出一段时间长度,有两种参数形式: + - 基于 `PromQL Time Durations` 格式的字符串(例如:`3h`、`1h30m`)。访问 [Prometheus 文档](https://prometheus.io/docs/prometheus/latest/querying/basics/#float-literals-and-time-durations) 获取该格式更详细的说明。 + - `Interval` 类型,使用 `Interval` 类型需要携带括号,(例如:`('1 year 3 hours 20 minutes'::INTERVAL)`)。访问 [Interval](./data-types.md#interval-type) 获取该格式更详细的说明。 +- `AGGR_FUNCTION(column1, column2,..) RANGE INTERVAL [FILL FILL_OPTION]` 称为一个 Range 表达式。 + - `AGGR_FUNCTION(column1, column2,..)` 是一个聚合函数,代表需要聚合的表达式。 + - 关键字 `RANGE`,必选字段,后接参数 `INTERVAL` 指定了每次数据聚合的时间范围, + - 关键字 `FILL`,可选字段,详情请见 [`FILL` Option](#fill-选项)。 + - Range 表达式可与其他运算结合,实现更复杂的查询。具体见[嵌套使用 Range 表达式](#嵌套使用-range-表达式) 。 +- 关键字 `FILL`,可以跟在一个 Range 表达式后,详情请见[FILL Option](#fill-选项) 。 + + +## `FILL` 选项 + +`FILL` 选项指定了在某个聚合的时间片上没有数据,或者聚合字段的值为空时的数据填充方法。 + +它可以跟在一个 Range 表达式后,作为这个 Range 表达式的数据填充方法;也可以放在 `ALIGN` 后面作为所有未指定 `FILL` 选项的 Range 表达式的填充方法。 + +例如,在下面的 SQL 代码中, +`max(val) RANGE '10s'` 范围表达式使用 `FILL` 选项 `LINEAR`,而 `min(val) RANGE '10s'` 没有指定 `FILL` 选项,它将使用在 `ALIGN`关键字之后指定的选项`PREV`。 + +```sql +SELECT + ts, + host, + min(val) RANGE '10s', + max(val) RANGE '10s' FILL LINEAR +FROM host_cpu +ALIGN '5s' BY (host) FILL PREV; +``` +`FILL` 有以下几种选项: + +| FILL | 描述 | +| :------: | :------------------------------------------------------------------------------------------------------------: | +| `NULL` | 直接使用 `NULL` 填充 | +| `PREV` | 使用前一个点的数据填充 | +| `LINEAR` | 使用线性插值法填充数据,如果一个整数类型使用 `LINEAR` 填充,则该列的变量类型会在计算的时候被隐式转换为浮点类型 | +| `X` | 填充一个常量,该常量的数据类型必须和 Range 表达式的变量类型一致 | + +以下面这张表为例 + +```sql +DROP TABLE IF EXISTS host_val; +CREATE TABLE host_val ( + ts TIMESTAMP TIME INDEX, + host STRING, + val DOUBLE, + PRIMARY KEY (host) +); + +INSERT INTO host_val VALUES + ('1970-01-01 00:00:00', 'host1', 0), + ('1970-01-01 00:00:15', 'host1', 6), + ('1970-01-01 00:00:00', 'host2', 6), + ('1970-01-01 00:00:15', 'host2', 12); +``` + +```sql ++---------------------+-------+------+ +| ts | host | val | ++---------------------+-------+------+ +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:15 | host1 | 6 | +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:15 | host2 | 12 | ++---------------------+-------+------+ +``` + +不同 `FILL` 选项的结果如下: + + + + + +```sql +SELECT ts, host, min(val) RANGE '5s' FROM host_val ALIGN '5s'; +``` + +```sql ++---------------------+-------+----------------------------+ +| ts | host | min(host_val.val) RANGE 5s | ++---------------------+-------+----------------------------+ +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:15 | host1 | 6 | +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:15 | host2 | 12 | ++---------------------+-------+----------------------------+ +``` + + + + + +```sql +SELECT ts, host, min(val) RANGE '5s' FILL NULL FROM host_val ALIGN '5s'; +``` + +```sql ++---------------------+-------+--------------------------------------+ +| ts | host | min(host_val.val) RANGE 5s FILL NULL | ++---------------------+-------+--------------------------------------+ +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:05 | host2 | NULL | +| 1970-01-01 00:00:10 | host2 | NULL | +| 1970-01-01 00:00:15 | host2 | 12 | +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:05 | host1 | NULL | +| 1970-01-01 00:00:10 | host1 | NULL | +| 1970-01-01 00:00:15 | host1 | 6 | ++---------------------+-------+--------------------------------------+ + +``` + + + + + +```sql +SELECT ts, host, min(val) RANGE '5s' FILL PREV FROM host_val ALIGN '5s'; +``` + +```sql ++---------------------+-------+--------------------------------------+ +| ts | host | min(host_val.val) RANGE 5s FILL PREV | ++---------------------+-------+--------------------------------------+ +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:05 | host1 | 0 | +| 1970-01-01 00:00:10 | host1 | 0 | +| 1970-01-01 00:00:15 | host1 | 6 | +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:05 | host2 | 6 | +| 1970-01-01 00:00:10 | host2 | 6 | +| 1970-01-01 00:00:15 | host2 | 12 | ++---------------------+-------+--------------------------------------+ +``` + + + + + +```sql +SELECT ts, host, min(val) RANGE '5s' FILL LINEAR FROM host_val ALIGN '5s'; +``` + +```sql ++---------------------+-------+----------------------------------------+ +| ts | host | min(host_val.val) RANGE 5s FILL LINEAR | ++---------------------+-------+----------------------------------------+ +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:05 | host2 | 8 | +| 1970-01-01 00:00:10 | host2 | 10 | +| 1970-01-01 00:00:15 | host2 | 12 | +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:05 | host1 | 2 | +| 1970-01-01 00:00:10 | host1 | 4 | +| 1970-01-01 00:00:15 | host1 | 6 | ++---------------------+-------+----------------------------------------+ +``` + + + + + +```sql [FILL Constant Value 6.0] +SELECT ts, host, min(val) RANGE '5s' FILL 6 FROM host_val ALIGN '5s'; +``` + +```sql ++---------------------+-------+-----------------------------------+ +| ts | host | min(host_val.val) RANGE 5s FILL 6 | ++---------------------+-------+-----------------------------------+ +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:05 | host2 | 6 | +| 1970-01-01 00:00:10 | host2 | 6 | +| 1970-01-01 00:00:15 | host2 | 12 | +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:05 | host1 | 6 | +| 1970-01-01 00:00:10 | host1 | 6 | +| 1970-01-01 00:00:15 | host1 | 6 | ++---------------------+-------+-----------------------------------+ +``` + + + + + +注意,如果存在多个 Range 表达式,只对其中的一个表达式使用了 FILL 方法的话,为了保持 SQL 输出行数的统一,其他 Range 表达式会被使用 FILL NULL 方法来填充缺失的时间片段。 +所以下面两句 SQL 在输出上是等价的: + +```sql +SELECT + ts, + host, + min(val) RANGE '10s', + max(val) RANGE '10s' FILL LINEAR +FROM host_val +ALIGN '5s'; +``` + +```sql +SELECT + ts, + host, + min(val) RANGE '10s' FILL NULL, + max(val) RANGE '10s' FILL LINEAR +FROM host_val +ALIGN '5s'; +``` + +上述 SQL 的结果如下: + +```sql ++---------------------+-------+---------------------------------------+-----------------------------------------+ +| ts | host | min(host_val.val) RANGE 10s FILL NULL | max(host_val.val) RANGE 10s FILL LINEAR | ++---------------------+-------+---------------------------------------+-----------------------------------------+ +| 1969-12-31 23:59:55 | host1 | 0 | 0 | +| 1970-01-01 00:00:00 | host1 | 0 | 0 | +| 1970-01-01 00:00:05 | host1 | NULL | 2.9999999999999996 | +| 1970-01-01 00:00:10 | host1 | 6 | 6 | +| 1970-01-01 00:00:15 | host1 | 6 | 6 | +| 1969-12-31 23:59:55 | host2 | 6 | 6 | +| 1970-01-01 00:00:00 | host2 | 6 | 6 | +| 1970-01-01 00:00:05 | host2 | NULL | 9 | +| 1970-01-01 00:00:10 | host2 | 12 | 12 | +| 1970-01-01 00:00:15 | host2 | 12 | 12 | ++---------------------+-------+---------------------------------------+-----------------------------------------+ +``` + +## `TO` 选项 + +`TO` 选项的值用于组确定范围查询的初始时间点。 +`TO` 选项、`RANGE` 选项和 `ALIGN INTERVAL` 共同决定了范围查询的时间窗口。 +请参考[时间范围窗口](/user-guide/query-data/sql.md#时间范围窗口)。 + +`TO` 选项的默认值为当前查询客户端的时区。如果想要设置时区,请参考 [MySQL 客户端](/user-guide/protocols/mysql.md#时区) 或 [PostgreSQL 客户端](/user-guide/protocols/postgresql.md#时区)文档中的时区设置。其他可用的 `TO` 选项有: + +| TO | 描述 | +| :---------: | :----------------------------------------------------------------: | +| `NOW` | 对齐到当前查询时间 | +| `Timestamp` | 对齐到一个用户指定的时间戳上,支持时间戳格式 `RFC3339` / `ISO8601` | + +假设我们有一个名为 `host_val` 的表有下面这些数据: + +```sql +DROP TABLE IF EXISTS host_val; +CREATE TABLE host_val ( + ts TIMESTAMP TIME INDEX, + host STRING, + val DOUBLE, + PRIMARY KEY (host) +); + +INSERT INTO host_val VALUES + ('2023-01-01 23:00:00', 'host1', 0), + ('2023-01-02 01:00:00', 'host1', 1), + ('2023-01-01 23:00:00', 'host2', 2), + ('2023-01-02 01:00:00', 'host2', 3); +``` + +```sql ++---------------------+-------+------+ +| ts | host | val | ++---------------------+-------+------+ +| 2023-01-01 23:00:00 | host1 | 0 | +| 2023-01-02 01:00:00 | host1 | 1 | +| 2023-01-01 23:00:00 | host2 | 2 | +| 2023-01-02 01:00:00 | host2 | 3 | ++---------------------+-------+------+ +``` + +对不同的 `TO` 选项的查询结果如下: + + + + + +```sql +-- 使用 mysql 协议查询数据库时区,当前处于 UTC 时区 +SELECT @@time_zone; +``` + +```sql ++-------------+ +| @@time_zone | ++-------------+ +| UTC | ++-------------+ +``` + +```sql +-- 如果没有指定 `TO` 选项 +-- 会使用当前查询指定的时区作为初始的对齐时间 +SELECT ts, host, min(val) RANGE '1d' FROM host_val ALIGN '1d'; +``` + +```sql ++---------------------+-------+----------------------------+ +| ts | host | min(host_val.val) RANGE 1d | ++---------------------+-------+----------------------------+ +| 2023-01-01 00:00:00 | host1 | 0 | +| 2023-01-02 00:00:00 | host1 | 1 | +| 2023-01-01 00:00:00 | host2 | 2 | +| 2023-01-02 00:00:00 | host2 | 3 | ++---------------------+-------+----------------------------+ +``` + + + + + +```sql +-- 如果你想要将查询范围的初始时间对齐到当前时间, +-- 可以使用 `NOW` 关键字。 +-- 假如当前的时间为 `2023-01-02T09:16:40.503000`。 +SELECT ts, host, min(val) RANGE '1d' FROM host_val ALIGN '1d' TO NOW; +``` + +```sql ++----------------------------+-------+----------------------------+ +| ts | host | min(host_val.val) RANGE 1d | ++----------------------------+-------+----------------------------+ +| 2023-01-01 09:54:55.456000 | host1 | 0 | +| 2023-01-01 09:54:55.456000 | host2 | 2 | ++----------------------------+-------+----------------------------+ + +``` + + + + + +```sql +-- 如果你想要将查询范围的初始时间对其到特定的时间戳, +-- 例如北京时间 2023 年 12 月 1 日, +-- 你可以将 `TO` 选项的值设定为特定的时间戳 '2023-01-01T00:00:00+08:00'。 +SELECT ts, host, min(val) RANGE '1d' FROM host_val ALIGN '1d' TO '2023-01-01T00:00:00+08:00'; +``` + +```sql ++---------------------+-------+----------------------------+ +| ts | host | min(host_val.val) RANGE 1d | ++---------------------+-------+----------------------------+ +| 2023-01-01 16:00:00 | host1 | 0 | +| 2023-01-01 16:00:00 | host2 | 2 | ++---------------------+-------+----------------------------+ +``` + + + + + +如果要查询特定时间范围内的数据,也可以使用 `TO` 关键字指定时间戳达到目的。 +例如,要查询 `val` 在 `00:45` 和 `06:45` 之间的每日最小值, +你可以使用 `2023-01-01T00:45:00` 作为 `TO` 选项以及指定 `6h` 的查询范围。 + +```sql +SELECT ts, host, min(val) RANGE '6h' FROM host_val ALIGN '1d' TO '2023-01-01T00:45:00'; +``` + +```sql ++---------------------+-------+----------------------------+ +| ts | host | min(host_val.val) RANGE 6h | ++---------------------+-------+----------------------------+ +| 2023-01-02 00:45:00 | host2 | 3 | +| 2023-01-02 00:45:00 | host1 | 1 | ++---------------------+-------+----------------------------+ +``` + +## `BY` 选项 + +`BY` 选项描述聚合键。如果不指定该字段,则默认使用表的主键作为聚合键。如果表没有指定主键,则不能省略 `BY` 关键字。 + +假设我们有一个名为 `host_val` 的表有以下数据: + +```sql +DROP TABLE IF EXISTS host_val; +CREATE TABLE host_val ( + ts TIMESTAMP TIME INDEX, + host STRING, + val DOUBLE, + PRIMARY KEY (host) +); + +INSERT INTO host_val VALUES + ('2023-01-01 23:00:00', 'host1', 0), + ('2023-01-02 01:00:00', 'host1', 1), + ('2023-01-01 23:00:00', 'host2', 2), + ('2023-01-02 01:00:00', 'host2', 3); +``` + +```sql ++---------------------+-------+------+ +| ts | host | val | ++---------------------+-------+------+ +| 2023-01-01 23:00:00 | host1 | 0 | +| 2023-01-02 01:00:00 | host1 | 1 | +| 2023-01-01 23:00:00 | host2 | 2 | +| 2023-01-02 01:00:00 | host2 | 3 | ++---------------------+-------+------+ +``` + +下面的 SQL 使用 `host` 作为聚合键: + +```sql +SELECT + ts, + host, + min(val) RANGE '10s' +FROM host_val ALIGN '5s' BY (host); +``` + +```sql ++---------------------+-------+-----------------------------+ +| ts | host | min(host_val.val) RANGE 10s | ++---------------------+-------+-----------------------------+ +| 2023-01-01 22:59:55 | host1 | 0 | +| 2023-01-01 23:00:00 | host1 | 0 | +| 2023-01-02 00:59:55 | host1 | 1 | +| 2023-01-02 01:00:00 | host1 | 1 | +| 2023-01-01 22:59:55 | host2 | 2 | +| 2023-01-01 23:00:00 | host2 | 2 | +| 2023-01-02 00:59:55 | host2 | 3 | +| 2023-01-02 01:00:00 | host2 | 3 | ++---------------------+-------+-----------------------------+ +``` + +你还可以使用 `BY` 关键字 + +你还可以使用 `BY` 关键字声明其他列作为数据聚合的依据。比如下面这个 RANGE 查询,使用 `host` 列的字符串长度 `length(host)` 作为数据聚合的依据。 + +```sql +SELECT + ts, + length(host), + min(val) RANGE '10s' +FROM host_val ALIGN '5s' BY (length(host)); +``` + +得到的结果如下: + +```sql ++---------------------+---------------------------------+-----------------------------+ +| ts | character_length(host_val.host) | min(host_val.val) RANGE 10s | ++---------------------+---------------------------------+-----------------------------+ +| 2023-01-01 22:59:55 | 5 | 0 | +| 2023-01-01 23:00:00 | 5 | 0 | +| 2023-01-02 00:59:55 | 5 | 1 | +| 2023-01-02 01:00:00 | 5 | 1 | ++---------------------+---------------------------------+-----------------------------+ +``` + +你也可以显式通过 `BY ()` 声明不需要使用聚合键,将所有数据全部聚合到一个 group 里。**但如果直接将 `BY` 关键字省略,则代表着使用数据表的主键来作为数据的聚合键。** + +```sql +SELECT + ts, + min(val) RANGE '10s' +FROM host_val ALIGN '5s' BY (); +``` + +得到的结果如下: + +```sql ++---------------------+-----------------------------+ +| ts | min(host_val.val) RANGE 10s | ++---------------------+-----------------------------+ +| 2023-01-01 22:59:55 | 0 | +| 2023-01-01 23:00:00 | 0 | +| 2023-01-02 00:59:55 | 1 | +| 2023-01-02 01:00:00 | 1 | ++---------------------+-----------------------------+ +``` + +## 聚合函数中的 `ORDER BY` 选项 + +Range 查询支持在聚合函数 `first_value` 和 `last_value` 中使用 `order by` 表达式,默认情况下,聚合函数使用时间索引列升序排列数据。 + +以该数据表为例: + +```sql +DROP TABLE IF EXISTS host_val; +CREATE TABLE host_val ( + ts TIMESTAMP TIME INDEX, + host STRING, + val DOUBLE, + addon DOUBLE, + PRIMARY KEY (host) +); + +INSERT INTO host_val VALUES + ('1970-01-01 00:00:00', 'host1', 0, 3), + ('1970-01-01 00:00:01', 'host1', 1, 2), + ('1970-01-01 00:00:02', 'host1', 2, 1); +``` + +```sql ++---------------------+-------+------+-------+ +| ts | host | val | addon | ++---------------------+-------+------+-------+ +| 1970-01-01 00:00:00 | host1 | 0 | 3 | +| 1970-01-01 00:00:01 | host1 | 1 | 2 | +| 1970-01-01 00:00:02 | host1 | 2 | 1 | ++---------------------+-------+------+-------+ +``` + +如果不指定 `order by` 表达式,默认使用时间索引 `ts` 列升序排列。 +以下两个 SQL 是等价的: + +```sql +SELECT ts, first_value(val) RANGE '5s', last_value(val) RANGE '5s' FROM host_val ALIGN '5s'; +``` + +```sql +SELECT ts, first_value(val order by ts ASC) RANGE '5s', last_value(val order by ts ASC) RANGE '5s' FROM host_val ALIGN '5s'; +``` + +查询后得到 + +```sql ++---------------------+------------------------------------+-----------------------------------+ +| ts | first_value(host_val.val) RANGE 5s | last_value(host_val.val) RANGE 5s | ++---------------------+------------------------------------+-----------------------------------+ +| 1970-01-01 00:00:00 | 0 | 2 | ++---------------------+------------------------------------+-----------------------------------+ +``` + +也可以自定义排序规则,比如使用 `addon` 排序: + +```sql +SELECT ts, first_value(val ORDER BY addon ASC) RANGE '5s', last_value(val ORDER BY addon ASC) RANGE '5s' FROM host_val ALIGN '5s'; +``` + +查询后得到 + +```sql ++---------------------+-----------------------------------------------------------------------------+----------------------------------------------------------------------------+ +| ts | first_value(host_val.val) ORDER BY [host_val.addon ASC NULLS LAST] RANGE 5s | last_value(host_val.val) ORDER BY [host_val.addon ASC NULLS LAST] RANGE 5s | ++---------------------+-----------------------------------------------------------------------------+----------------------------------------------------------------------------+ +| 1970-01-01 00:00:00 | 2 | 0 | ++---------------------+-----------------------------------------------------------------------------+----------------------------------------------------------------------------+ +``` + +## 嵌套使用 Range 表达式 + +Range 表达式支持灵活的嵌套,可以将 Range 表达式结合各种运算,提供更强大的查询能力。 + +以下面这张表为例: + +```sql +DROP TABLE IF EXISTS host_val; +CREATE TABLE host_val ( + ts TIMESTAMP TIME INDEX, + host STRING, + val DOUBLE, + PRIMARY KEY (host) +); + +INSERT INTO host_val VALUES + ('2023-01-01 08:00:00', 'host1', 1.1), + ('2023-01-01 08:00:05', 'host1', 2.2), + ('2023-01-01 08:00:00', 'host2', 3.3), + ('2023-01-01 08:00:05', 'host2', 4.4); +``` + +```sql ++---------------------+-------+------+ +| ts | host | val | ++---------------------+-------+------+ +| 2023-01-01 08:00:00 | host1 | 1.1 | +| 2023-01-01 08:00:05 | host1 | 2.2 | +| 2023-01-01 08:00:00 | host2 | 3.3 | +| 2023-01-01 08:00:05 | host2 | 4.4 | ++---------------------+-------+------+ +``` + +1. 聚合函数内部和外部都支持计算: + +```sql +SELECT ts, host, 2.0 * min(val * 2.0) RANGE '10s' FROM host_val ALIGN '5s'; +``` + +运行后得到 + +```sql ++---------------------+-------+-------------------------------------------------------+ +| ts | host | Float64(2) * min(host_val.val * Float64(2)) RANGE 10s | ++---------------------+-------+-------------------------------------------------------+ +| 2023-01-01 07:59:55 | host1 | 4.4 | +| 2023-01-01 08:00:00 | host1 | 4.4 | +| 2023-01-01 08:00:05 | host1 | 8.8 | +| 2023-01-01 07:59:55 | host2 | 13.2 | +| 2023-01-01 08:00:00 | host2 | 13.2 | +| 2023-01-01 08:00:05 | host2 | 17.6 | ++---------------------+-------+-------------------------------------------------------+ +``` + + +2. 聚合函数内部和外部都支持使用 Scalar 函数: + - `min(round(val)) RANGE '10s'` 表示对每个值先使用 `round` 函数四舍五入后再进行聚合 + - `round(min(val) RANGE '10s')` 表示对每个聚合完成的结果使用 `round` 函数四舍五入 + +```sql +SELECT ts, host, min(round(val)) RANGE '10s' FROM host_val ALIGN '5s'; +``` +运行后得到 + +```sql ++---------------------+-------+------------------------------------+ +| ts | host | min(round(host_val.val)) RANGE 10s | ++---------------------+-------+------------------------------------+ +| 2023-01-01 07:59:55 | host1 | 1 | +| 2023-01-01 08:00:00 | host1 | 1 | +| 2023-01-01 08:00:05 | host1 | 2 | +| 2023-01-01 07:59:55 | host2 | 3 | +| 2023-01-01 08:00:00 | host2 | 3 | +| 2023-01-01 08:00:05 | host2 | 4 | ++---------------------+-------+------------------------------------+ +``` + + +```sql +SELECT ts, host, round(min(val) RANGE '10s') FROM host_val ALIGN '5s'; +``` + +运行后得到 + +```sql ++---------------------+-------+------------------------------------+ +| ts | host | round(min(host_val.val) RANGE 10s) | ++---------------------+-------+------------------------------------+ +| 2023-01-01 07:59:55 | host2 | 3 | +| 2023-01-01 08:00:00 | host2 | 3 | +| 2023-01-01 08:00:05 | host2 | 4 | +| 2023-01-01 07:59:55 | host1 | 1 | +| 2023-01-01 08:00:00 | host1 | 1 | +| 2023-01-01 08:00:05 | host1 | 2 | ++---------------------+-------+------------------------------------+ +``` + +3. 多个 Range 表达式也可以相互计算,并且 Range 表达式支持分配律,下面两个表达式都是合法且等价的: + +```sql +SELECT ts, host, max(val) RANGE '10s' - min(val) RANGE '10s' FROM host_val ALIGN '5s'; +``` + +```sql +SELECT ts, host, (max(val) - min(val)) RANGE '10s' FROM host_val ALIGN '5s'; +``` + +运行后得到 + +```sql ++---------------------+-------+-----------------------------------------------------------+ +| ts | host | max(host_val.val) RANGE 10s - min(host_val.val) RANGE 10s | ++---------------------+-------+-----------------------------------------------------------+ +| 2023-01-01 07:59:55 | host2 | 0 | +| 2023-01-01 08:00:00 | host2 | 1.1000000000000005 | +| 2023-01-01 08:00:05 | host2 | 0 | +| 2023-01-01 07:59:55 | host1 | 0 | +| 2023-01-01 08:00:00 | host1 | 1.1 | +| 2023-01-01 08:00:05 | host1 | 0 | ++---------------------+-------+-----------------------------------------------------------+ +``` + +但注意,Range 表达式修饰的范围是位于 `RANGE` 关键字的前一个表达式,下面的 Range 查询是不合法的,因为 `RANGE` 关键字修饰的是表达式 `2.0`,并不是表达式 `min(val * 2.0) * 2.0` + +```sql +SELECT ts, host, min(val * 2.0) * 2.0 RANGE '10s' FROM host_val ALIGN '5s'; + +ERROR 1815 (HY000): sql parser error: Can't use the RANGE keyword in Expr 2.0 without function +``` + +可以为表达式加上括号,`RANGE` 关键字会自动应用到括号中包含的所有聚合函数: + +```sql +SELECT ts, host, (min(val * 2.0) * 2.0) RANGE '10s' FROM host_val ALIGN '5s'; +``` + +运行后得到: + +```sql ++---------------------+-------+-------------------------------------------------------+ +| ts | host | min(host_val.val * Float64(2)) RANGE 10s * Float64(2) | ++---------------------+-------+-------------------------------------------------------+ +| 2023-01-01 07:59:55 | host2 | 13.2 | +| 2023-01-01 08:00:00 | host2 | 13.2 | +| 2023-01-01 08:00:05 | host2 | 17.6 | +| 2023-01-01 07:59:55 | host1 | 4.4 | +| 2023-01-01 08:00:00 | host1 | 4.4 | +| 2023-01-01 08:00:05 | host1 | 8.8 | ++---------------------+-------+-------------------------------------------------------+ +``` + +Range 表达式不允许嵌套,嵌套的 Range 查询是不合法的: + +```sql +SELECT ts, host, max(min(val) RANGE '10s') RANGE '10s' FROM host_cpu ALIGN '5s'; + +ERROR 1815 (HY000): Range Query: Nest Range Query is not allowed +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/replace.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/replace.md new file mode 100644 index 0000000000..31ca919e83 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/replace.md @@ -0,0 +1,39 @@ +--- +keywords: [SQL REPLACE 语句, SQL 语法, SQL 示例, 插入记录, SQL 数据操作] +description: 描述在 GreptimeDB 中使用 SQL REPLACE 语句向表中添加记录的方法,包括语法和插入单条及多条记录的示例。 +--- + +# REPLACE + +`REPLACE` 语句用于向表中插入新记录。在 GreptimeDB 中,这个语句与 `INSERT` 语句完全相同。更多详情请参考 [`INSERT`](/reference/sql/insert.md)。 + +## `REPLACE INTO` 语句 + +### 语法 + +REPLACE INTO 语句的语法如下: + +```sql +REPLACE INTO table_name (column1, column2, column3, ...) +VALUES (value1, value2, value3, ...); +``` + +### 示例 + +以下是使用 `REPLACE INTO` 语句向名为 `system_metrics` 的表中插入一条记录的示例: + +```sql +REPLACE INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES + ("host1", "idc_b", 50.0, 66.7, 40.6, 1667446797462); +``` + +以下是使用 `REPLACE INTO` 语句向 `system_metrics` 表中插入多条记录的示例: + +```sql +REPLACE INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES + ("host1", "idc_a", 11.8, 10.3, 10.3, 1667446797460), + ("host2", "idc_a", 80.1, 70.3, 90.0, 1667446797461), + ("host1", "idc_c", 50.1, 66.8, 40.8, 1667446797463); +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/select.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/select.md new file mode 100644 index 0000000000..c98d19f0f9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/select.md @@ -0,0 +1,205 @@ +--- +keywords: [SELECT 语句, SQL 查询, WHERE 子句, LIMIT 子句, JOIN 子句, GROUP BY 子句] +description: 介绍了 `SELECT` 语句的基本语法和用法,包括 `WHERE`、`LIMIT`、`JOIN` 和 `GROUP BY` 子句的示例。 +--- + +# SELECT + +`SELECT` 语句是 SQL 和 GreptimeDB 中数据检索的基础。它允许你从一个或多个表中提取特定的列或表达式: + +## Basic Syntax + +`SELECT` 的基本语法如下: + +```sql +SELECT column1, column2, ... +FROM table_name +[WHERE condition] +[GROUP BY column] +[HAVING condition] +[ORDER BY column] +[LIMIT number] [OFFSET number] +``` + +column1, column2 是要从中获取数据的列的名称,table_name 是要从中获取数据的表的名称。 + +该语句从 `FROM` 子句中指定的表中选择列。如果要从表中选择所有列,可以使用星号(*)通配符字符,而不是列出单个列名。 + +```sql +SELECT * +FROM table_name; +``` + +## 条件过滤 (WHERE 子句) + +`WHERE` 子句用于根据指定条件过滤 `SELECT` 语句的结果,其语法如下: + +```sql +SELECT column1, column2, ..., columnN +FROM table_name +WHERE condition; +``` + +其中 `condition` 是一个表达式,它的值为 `true` 或 `false`。只有满足条件的行才会包含在结果集中。 + +支持的比较运算包括: +* 逻辑运算符:`AND`、`OR`、`NOT` +* 比较运算符:`=`、`!=`、`>`、`<`、`>=`、`<=` +* 模式匹配:`LIKE`、`IN`、`BETWEEN` + +```sql +-- 从 system_metrics 表中选择所有 idc 为 'idc0' 的行 +SELECT * +FROM system_metrics +WHERE idc = 'idc0'; + +-- 从 system_metrics 表中选择所有 idc 为 'idc0' 或 'idc0' 的行 +SELECT * +FROM system_metrics +WHERE idc IN ('idc0', 'idc1'); + +-- 从 system_metrics 表中选择所有idc为'idc0'或'idc0'且CPU利用率大于60%的行 +SELECT * +FROM system_metrics +WHERE idc IN ('idc0', 'idc1') AND cpu_util > 0.6; +``` + +请参考 [WHERE](where.md) 获取更多信息。 + +## 排序结果(ORDER BY 子句) + +`ORDER BY` 子句用于根据 SELECT 语句中的一个或多个列,以升序或降序对数据进行排序。 + +例如: + +```sql +-- 按 cpu_util 升序排序结果 +SELECT * +FROM system_metrics ORDER BY cpu_util ASC; + +-- 按 cpu_util 降序排序结果 +SELECT * +FROM system_metrics ORDER BY cpu_util DESC; +``` + +更多信息请参阅 [ORDER](order_by.md)。 + +## 限制结果(LIMIT 子句) + +`LIMIT` 用于限制查询返回的行数。当处理大数据集时该子句特别有用,因为它通过减少需要处理的数据量来提高查询性能。 + +```sql +SELECT column1, column2, ... +FROM table_name +LIMIT number_of_rows; +``` + +这里 `number_of_rows` 参数用于指定要返回的最大行数。 + +```sql +-- 从 system_metrics 表中选择 CPU 使用率最高的 10 行。 +SELECT * +FROM system_metrics +ORDER BY cpu_util DESC +LIMIT 10; +``` + + +## 分页结果 (LIMIT 和 OFFSET) + +`OFFSET` 子句指定在开始返回查询结果行之前要跳过多少行。它通常与 `LIMIT` 一起使用,用于对大型结果集进行分页。 + +例如: +```sql +SELECT * +FROM system_metrics +ORDER BY cpu_util DESC +LIMIT 10 +OFFSET 10; +``` + +它从 `system_metrics` 表中选择按 `cpu_util` 降序排列的第 11 行到第 20 行的所有列。 + +虽然将 `OFFSET` 和 `LIMIT` 与 `ORDER BY` 子句结合使用可以实现分页,但这种方法效率不高。 我们建议记录每页返回的最后一条记录的时间索引(时间戳),并使用此值来过滤和限制后续页面的数据。 请参阅 [OFFSET](offset.md) 以获取更多信息。 + +## 连接表(JOIN) + +`JOIN` 用于组合两个或多个表中基于相关列的行,使用 `JOIN` 的语法如下: + +```sql +SELECT column1, column2, ... +FROM table1 +JOIN table2 +ON table1.column = table2.column; +``` + +table1 和 table2 是要连接的表的名称,column 是两个表之间的相关列,请参考[JOIN](join.md) 获取更多信息。 + +## 分组和聚合 (GROUP BY 和聚合函数) + +使用 `GROUP BY` 可以根据一个或多个列对数据进行分组,并在这些组内执行诸如计数或求平均值之类的计算,其基本语法如下: + +```sql +SELECT column1, column2, ..., aggregate_function(column) +FROM table_name +GROUP BY column1, column2, ...; +``` + +常见支持的聚合函数: +* COUNT +* SUM +* AVG +* MAX +* MIN + +更多函数,请参阅 [聚合函数](/reference/sql/functions/df-functions.md#aggregate-functions) 和 [窗口函数](/reference/sql/functions/df-functions.md#window-functions)。 + +示例: +```sql +-- 查询每个 idc 的 idc 总数 +SELECT idc, COUNT(host) as host_num +FROM system_metrics +GROUP BY idc; + +-- 查询每个 idc 的平均 cpu 利用率 +SELECT idc, AVG(cpu_util) as cpu_avg +FROM system_metrics +GROUP BY idc; +``` + +请参考 [GROUP BY](group_by.md) 获取更多信息。 + +## 过滤分组 (HAVING 子句) + +`HAVING` 子句允许您过滤分组(聚合)后的结果——它的作用类似于 `WHERE`,但发生在分组之后。 + +示例: +```sql +SELECT + DATE_TRUNC('day', event_time) AS log_date, + COUNT(*) AS error_count +FROM application_logs +WHERE log_level = 'ERROR' +GROUP BY log_date +HAVING error_count > 10; +``` + +解释如下: +* 按日期分组日志,并统计日志级别为 `'ERROR'` 的事件数量。 +* 仅返回错误数量超过 10 的日期。 + +请参考 [HAVING](having.md) 获取更多信息。 + +## RANGE 查询示例 + +```sql +SELECT + ts, + host, + min(cpu) RANGE '10s', + max(cpu) RANGE '10s' FILL LINEAR +FROM host_cpu +ALIGN '5s' BY (host) FILL PREV; +``` + +请参考 [RANGE QUERY](range.md) 获取更多信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/show.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/show.md new file mode 100644 index 0000000000..f6a88a9a8a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/show.md @@ -0,0 +1,447 @@ +--- +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 PROCESSLIST +列出当前所有正在执行的查询列表,本质上是 `SELECT id, catalog, query, elapsed_time FROM INFORMATION_SCHEMA.PROCESS_LIST` 的别名: + +```sql +SHOW PROCESSLIST; +``` + +输出如下: +``` ++-----------------------+----------+------------------+-----------------+ +| Id | Catalog | Query | Elapsed Time | ++-----------------------+----------+------------------+-----------------+ +| 192.168.50.164:4001/0 | greptime | SHOW PROCESSLIST | 00:00:00.002000 | ++-----------------------+----------+------------------+-----------------+ +1 row in set (0.00 sec) +``` + +同时可以指定 `FULL` 参数用于输出 `INFORMATION_SCHEMA.PROCESS_LIST` 表的所有列: +```sql +SHOW FULL PROCESSLIST; +``` + +输出如下: +```sql ++-----------------------+----------+--------------------+------------------------+---------------------+----------------------------+-----------------+-----------------------+ +| Id | Catalog | Schema | Client | Frontend | Start Time | Elapsed Time | Query | ++-----------------------+----------+--------------------+------------------------+---------------------+----------------------------+-----------------+-----------------------+ +| 192.168.50.164:4001/0 | greptime | information_schema | mysql[127.0.0.1:34692] | 192.168.50.164:4001 | 2025-06-30 07:17:46.423000 | 00:00:00.003000 | SHOW FULL PROCESSLIST | ++-----------------------+----------+--------------------+------------------------+---------------------+----------------------------+-----------------+-----------------------+ +``` + +## SHOW TRIGGERS + +请参考 [Trigger 语法](/reference/sql/trigger-syntax.md#show-triggers)文档。 + +## SHOW CREATE TRIGGER + +请参考 [Trigger 语法](/reference/sql/trigger-syntax.md#show-create-trigger)文档。 + +## 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 | ++-------+--------+------+------+---------+-------+---------------+ +``` + +列出表中的所有 Region: + +```sql +SHOW REGION FROM monitor; +``` + +```sql ++----------------+---------------+------+--------+ +| Table | Region | Peer | Leader | ++----------------+---------------+------+--------+ +| monitor | 4398046511104 | 0 | Yes | ++----------------+---------------+------+--------+ +``` + +这是 `INFORMATION_SCHEMA.REGION_PEERS` 的扩展,并且支持 `WHERE` 子句。 + +语法是: +```sql +SHOW REGION FROM [table] [IN database] [WHERE where] +``` + +其他 `SHOW` 扩展语句: +* `SHOW STATUS` 和 `SHOW VARIABLES` 不支持,仅返回空结果。 +* `SHOW TABLE STATUS` 是 `INFORMATION_SCHEMA.TABLES` 的扩展。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/tql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/tql.md new file mode 100644 index 0000000000..c5c25161b2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/tql.md @@ -0,0 +1,185 @@ +--- +keywords: [TQL 关键字, EVAL, EXPLAIN, ANALYZE, 时间序列查询] +description: 介绍了 `TQL` 关键字及其在 GreptimeDB 中的用法,包括 `EVAL`、`EXPLAIN` 和 `ANALYZE` 的语法和示例。 +--- + +# TQL + +`TQL` 关键字在 SQL 中执行 TQL 语言。TQL 是 Telemetry Query Language 的缩写,是 GreptimeDB 中对 Prometheus 的 [PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/) 的扩展。 + +## EVAL + +### Syntax + +```sql +TQL [EVAL | EVALUATE] (start, end, step, [lookback]) expr [AS alias] +``` + +`start`, `end` 和 `step` 是查询参数,就像 [Prometheus Query API](https://prometheus.io/docs/prometheus/latest/querying/api/) 一样: + +- `start`: ``: 查询的起始时间戳,范围中包含该值。 +- `end`: ``: 查询的截止时间戳,范围中包含该值。 +- `step`: ``: 查询分辨率步长,采用 `duration` 格式或浮点秒数。 +- `lookback`: ``: 查询评估的最大过去持续时间,默认 5 分钟,可选参数。 + +`expr` 是 TQL (PromQL) 的查询字符串。 + +可选的 `AS alias` 子句允许你为结果中的值列指定自定义名称。这对以下场景很有用: +- 为查询结果提供有意义的名称 +- 在 SQL 查询中使用 TQL 结果(例如 CTE、JOIN) +- 提高复杂查询的可读性 + +**注意**:值别名目前仅支持单值列结果。 + +### 示例 + +返回过去 5 分钟内 `http_requests_total` 指标的所有时间序列的每秒值: + +```sql +TQL EVAL (1677057993, 1677058993, '1m') + rate(prometheus_http_requests_total{job="prometheus"}[5m]); +``` + +其查询结果和 SQL 查询结果类似。 + +使用值别名为结果提供自定义名称: + +```sql +TQL EVAL (0, 30, '10s') http_requests_total AS requests; +``` + +这将返回值列名为 `requests` 而不是默认字段名的结果。 + +值别名与聚合: + +```sql +TQL EVAL (0, 10, '5s') count by (k) (test) AS count_value; +``` + +此查询按 `k` 分组计数值,并将结果列命名为 `count_value`。 + +`start` 和 `end` 还可以是可以被求值为常量的时间表达式,例如查询过去 3 个小时: + +```sql +TQL EVAL (now() - interval '3' hours, now(), '1m') + sum by (namespace, pod) ( + increase(kube_pod_container_status_restarts_total[10m:30s]) + ); +``` + +查询过去一天的数据: +```sql +TQL EVAL ( + date_trunc('day', now() - interval '1' day), + date_trunc('day', now()), + '1m' +) + sum by (namespace) ( + rate(http_requests_total[5m:30s]) + ); +``` + +### 在 CTE 中使用 TQL + +TQL `EVAL` 可以在公共表表达式(CTE)中使用,以便将 PromQL 风格的查询与 SQL 处理相结合。有关详细示例和使用指南,请参阅[在 CTE 中使用 TQL](/user-guide/query-data/cte.md#在-cte-中使用-tql)。 + +## EXPLAIN + +`EXPLAIN` 展示特定 PromQL 查询的逻辑计划和执行计划,其语法如下: + +``` +TQL EXPLAIN [VERBOSE] [FORMAT format] [(start, end, step, [lookback])] expr [AS alias]; +``` + +例如,我们可以使用下方示例解释 PromQL `sum by (instance) (rate(node_disk_written_bytes_total[2m])) > 50`: + +``` +TQL EXPLAIN sum by (instance) (rate(node_disk_written_bytes_total[2m])) > 50; +``` + +注意该查询实际上没有被执行,所以 `(start, end, step, [lookback])` 不是必需的,但你仍然可以像在 `TQL EVAL` 中一样提供这些参数: + +``` +TQL EXPLAIN (0, 100, '10s') sum by (instance) (rate(node_disk_written_bytes_total[2m])) > 50; +``` + +你也可以在 EXPLAIN 中使用值别名: + +``` +TQL EXPLAIN (0, 10, '5s') test AS series; +``` + +结果如下: + +```txt ++---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Sort: node_disk_written_bytes_total.instance ASC NULLS LAST, node_disk_written_bytes_total.ts ASC NULLS LAST + Filter: SUM(prom_rate(ts_range,field,ts)) > Float64(50) + Aggregate: groupBy=[[node_disk_written_bytes_total.instance, node_disk_written_bytes_total.ts]], aggr=[[SUM(prom_rate(ts_range,field,ts))]] + Projection: node_disk_written_bytes_total.ts, prom_rate(ts_range, field, node_disk_written_bytes_total.ts) AS prom_rate(ts_range,field,ts), node_disk_written_bytes_total.instance + Filter: prom_rate(ts_range, field, node_disk_written_bytes_total.ts) IS NOT NULL + Projection: node_disk_written_bytes_total.ts, node_disk_written_bytes_total.instance, field, ts_range + PromRangeManipulate: req range=[0..0], interval=[300000], eval range=[120000], time index=[ts], values=["field"] + PromSeriesNormalize: offset=[0], time index=[ts], filter NaN: [true] + PromSeriesDivide: tags=["instance"] + Sort: node_disk_written_bytes_total.instance DESC NULLS LAST, node_disk_written_bytes_total.ts DESC NULLS LAST + TableScan: node_disk_written_bytes_total projection=[ts, instance, field], partial_filters=[ts >= TimestampMillisecond(-420000, None), ts <= TimestampMillisecond(300000, None)] | +| physical_plan | SortPreservingMergeExec: [instance@0 ASC NULLS LAST,ts@1 ASC NULLS LAST] + SortExec: expr=[instance@0 ASC NULLS LAST,ts@1 ASC NULLS LAST] + CoalesceBatchesExec: target_batch_size=8192 + FilterExec: SUM(prom_rate(ts_range,field,ts))@2 > 50 + AggregateExec: mode=FinalPartitioned, gby=[instance@0 as instance, ts@1 as ts], aggr=[SUM(prom_rate(ts_range,field,ts))] + CoalesceBatchesExec: target_batch_size=8192 + RepartitionExec: partitioning=Hash([Column { name: "instance", index: 0 }, Column { name: "ts", index: 1 }], 32), input_partitions=32 + AggregateExec: mode=Partial, gby=[instance@2 as instance, ts@0 as ts], aggr=[SUM(prom_rate(ts_range,field,ts))] + ProjectionExec: expr=[ts@0 as ts, prom_rate(ts_range@3, field@2, ts@0) as prom_rate(ts_range,field,ts), instance@1 as instance] + CoalesceBatchesExec: target_batch_size=8192 + FilterExec: prom_rate(ts_range@3, field@2, ts@0) IS NOT NULL + ProjectionExec: expr=[ts@0 as ts, instance@1 as instance, field@2 as field, ts_range@3 as ts_range] + PromInstantManipulateExec: req range=[0..0], interval=[300000], eval range=[120000], time index=[ts] + PromSeriesNormalizeExec: offset=[0], time index=[ts], filter NaN: [true] + PromSeriesDivideExec: tags=["instance"] + RepartitionExec: partitioning=RoundRobinBatch(32), input_partitions=1 + ExecutionPlan(PlaceHolder) + | ++---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## ANALYZE + +TQL 同样支持 `ANALYZE` 关键词来分析给定 PromQL 查询的执行,其语法如下: + +``` +TQL ANALYZE [VERBOSE] [FORMAT format] (start, end, step, [lookback]) expr [AS alias]; +``` + +例如: + +``` +TQL ANALYZE (0, 10, '5s') test; +``` + +得到结果: + +``` ++-------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++-------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Plan with Metrics | CoalescePartitionsExec, metrics=[output_rows=0, elapsed_compute=14.99µs] + PromInstantManipulateExec: range=[0..10000], lookback=[300000], interval=[5000], time index=[j], metrics=[output_rows=0, elapsed_compute=1.08µs] + PromSeriesNormalizeExec: offset=[0], time index=[j], filter NaN: [false], metrics=[output_rows=0, elapsed_compute=1.11µs] + PromSeriesDivideExec: tags=["k"], metrics=[output_rows=0, elapsed_compute=1.3µs] + RepartitionExec: partitioning=RoundRobinBatch(32), input_partitions=32, metrics=[send_time=32ns, repart_time=32ns, fetch_time=11.578016ms] + RepartitionExec: partitioning=RoundRobinBatch(32), input_partitions=1, metrics=[send_time=1ns, repart_time=1ns, fetch_time=21.07µs] + ExecutionPlan(PlaceHolder), metrics=[] + | ++-------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +使用 `TQL ANALYZE VERBOSE` 可以拿到查询执行时更详细的信息. + +``` +TQL ANALYZE VERBOSE (0, 10, '5s') test; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/trigger-syntax.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/trigger-syntax.md new file mode 100644 index 0000000000..9d7b3d2d65 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/trigger-syntax.md @@ -0,0 +1,178 @@ +--- +keywords: [Trigger, 触发器, 告警, GreptimeDB 企业版, 语法] +description: 本文档系统描述了 GreptimeDB Trigger 的完整语法规范。 +--- + +# Trigger 语法 + +:::tip 注意 + +本功能仅在 GreptimeDB 企业版中可用。 + +::: + +## CREATE TRIGGER + +创建 Trigger 的语法: + +```sql +CREATE TRIGGER [IF NOT EXISTS] + ON () EVERY + [LABELS (=, ...)] + [ANNOTATIONS (=, ...)] + NOTIFY ( + WEBHOOK URL '' [WITH (=, ...)], + WEBHOOK URL '' [WITH (=, ...)] + ); +``` + +- Trigger name:Trigger 在 catalog 级别的唯一标识符。 +- IF NOT EXISTS:阻止 Trigger 已经存在时的报错。 + +### On 子句 + +#### Query expression + +指定的 SQL 查询会被定期执行。若查询结果非空,则触发通知;若查询结果包含多行,则 +每一行都会触发一条独立通知。 + +此外,Trigger 会从查询结果中提取 labels 与 annotations,并与 `LABELS` 和 `ANNOTATIONS` +子句中指定的键值对一起附加到通知消息中。 + +提取规则如下: + +- 若列名(或别名)以 `label_` 开头,则将该列提取到 LABELS 中,键名为去掉 `label_` + 前缀后的列名(或别名)。 +- 其余所有列均提取到 ANNOTATIONS 中,键名即为列名(或别名)。 + +例如,查询表达式如下: + +```sql +SELECT collect as label_collector, host as label_host, val + FROM host_load1 + WHERE val > 10 and ts >= now() - '1 minutes'::INTERVAL +``` + +假设查询结果非空,且如下所示: + +| label_collector | label_host | val | +|------------------|------------|-----| +| collector1 | host1 | 12 | +| collector2 | host2 | 15 | + +这将产生两条通知。 + +第一条通知的 labels 与 annotations 如下: +- Labels: + - collector: collector1 + - host: host1 + - 以及 `LABELS` 子句中定义的 labels +- Annotations: + - val: 12 + - 以及 `ANNOTATIONS` 子句中定义的 annotations + +第二条通知的 labels 与 annotations 如下: +- Labels: + - collector: collector2 + - host: host2 + - 以及 `LABELS` 子句中定义的 labels +- Annotations: + - val: 15 + - 以及 `ANNOTATIONS` 子句中定义的 annotations + +#### Interval expression + +指定查询的执行间隔。它表示查询的执行频率。例如,`INTERVAL '1 minute'`、 +`INTERVAL '1 hour'` 等。 + +- INTERVAL 表达式中**禁止**使用 `years` 和 `months`。月和年的时长是可变的,取决于具体的月份或年份,因此不适合用来定义固定的间隔。 +- 最小间隔为 1 秒。任何小于 1 秒的间隔都会被自动向上取整为 1 秒。 + +有关 INTERVA L表达式的更多语法细节,请参见 [interval-type](/reference/sql/data-types.md#interval-type)。 + +### Labels 和 Annotations 子句 + +LABELS 和 ANNOTATIONS 子句用于在 Trigger 发送的通知消息中附加静态的键值对,以提 +供有关该 Trigger 的额外上下文或元数据。 + +- LABELS:可用于 Alertmanager 的路由、分组与抑制规则等。 +- ANNOTATIONS:通常用于存放供人类阅读的描述信息。 + +### Notify 子句 + +NOTIFY 子句允许指定一个或多个通知通道。目前,GreptimeDB 支持以下通道类型: + +#### Webhook + +当 Trigger 触发时,Webhook 通道会向指定的 URL 发送 HTTP 请求。请求的 payload +与 [Prometheus Alertmanager](https://prometheus.io/docs/alerting/latest/alertmanager/) +兼容,因此我们可以复用 Alertmanager 的分组、抑制、静默和路由功能,而无需任何 +额外的胶水代码。 + +可选的 WITH 子句允许指定额外的参数: + +- timeout:HTTP 请求的超时时间,例如 `timeout='1m'`。 + +## SHOW TRIGGERS + +列出所有的 Triggers: + +```sql +SHOW TRIGGERS; +``` + +当然,它也支持 `LIKE` 查询: + +```sql +SHOW TRIGGERS LIKE ''; +``` + +例如: + +```sql +SHOW TRIGGERS LIKE 'load%'; +``` + +以及 `WHERE` 条件: + +```sql +SHOW TRIGGERS WHERE ; +``` + +例如: + +```sql +SHOW TRIGGERS WHERE name = 'load1_monitor'; +``` + +## SHOW CREATE TRIGGER + +用于显示 TRIGGER 的定义: + +```sql +SHOW CREATE TRIGGER ; +``` + +例如: + +```sql +SHOW CREATE TRIGGER load1_monitor; +``` + +## DROP TRIGGER + +请使用以下 `DROP TRIGGER` 语句删除 Trigger: + +```sql +DROP TRIGGER [IF EXISTS] ; +``` + +For example: + +```sql +DROP TRIGGER IF EXISTS load1_monitor; +``` + +## 示例 + +请参考企业版用户指南中的 [Trigger](/enterprise/trigger.md) 文档。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/truncate.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/truncate.md new file mode 100644 index 0000000000..3429db8d1c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/reference/sql/where.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/where.md new file mode 100644 index 0000000000..0293da10e7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/where.md @@ -0,0 +1,78 @@ +--- +keywords: [WHERE 子句, SQL 过滤, 逻辑运算符, 数字比较, 列表查找] +description: 介绍了 `WHERE` 子句的用法,包括逻辑运算符、数字比较和列表查找的示例。 +--- + +# WHERE + +`WHERE` 子句允许通过指定条件过滤数据。 + +## Syntax + +```sql +SELECT * +FROM table_name +WHERE condition; +``` + +如果有 `WHERE` 子句,则它必须为布尔类型的表达式,这通常是带有比较和逻辑运算符的表达式。此表达式计算结果为 false 的行将会从进一步的转换或结果中排除。 + +## 示例 + +### 逻辑运算符 + +支持 `AND`、`OR` 作为逻辑运算符,并可以使用括号()组合条件。 + +```sql +SELECT * FROM system_metrics +WHERE idc = 'idc0' AND (host = 'host1' OR host = 'host2'); +``` + +### 数字 + +支持 `=`, `!=`, `>`, `>=`, `<`, `<=` 作为比较运算符。 + +```sql +SELECT * FROM system_metrics WHERE cpu_util = 20.0; +SELECT * FROM system_metrics WHERE cpu_util != 20.0; +SELECT * FROM system_metrics WHERE cpu_util > 20.0; +SELECT * FROM system_metrics WHERE cpu_util >= 20.0; +SELECT * FROM system_metrics WHERE cpu_util < 20.0; +SELECT * FROM system_metrics WHERE cpu_util <= 20.0; +``` + +### List 查找 + +List 子元素的匹配或不匹配。 + +### List 匹配 + +```sql +SELECT * FROM system_metrics WHERE idc IN ('idc_a', 'idc_b'); +``` + +### List 不匹配 + +```sql +SELECT * FROM system_metrics WHERE idc NOT IN ('idc_a', 'idc_b'); +``` + +### 字符串 + +对于字符串列,我们可以使用 `LIKE` 运算符在列中搜索指定的模式。 有两个通配符经常与 LIKE 运算符一起使用: +* 百分号 `%` 代表零个、一个或多个字符 +* 下划线 `_` 代表单个字符 + +选择 `host` 列以字母 "a" 开头的所有记录: +```sql +SELECT * FROM system_metrics WHERE host LIKE 'a%'; +``` + +从 `go_info` 表中选择 instance 列匹配模式 `'localhost:____'` 的所有记录,这意味着 `'localhost:'` 后面跟着恰好四个字符: + +```sql +SELECT * FROM go_info +WHERE instance LIKE 'localhost:____'; +``` + +有关在日志中搜索关键字,请阅读[查询日志](/user-guide/logs/fulltext-search.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/with.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/sql/with.md new file mode 100644 index 0000000000..8a77d795cb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/reference/telemetry.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/telemetry.md new file mode 100644 index 0000000000..cc6a42bdc8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/telemetry.md @@ -0,0 +1,66 @@ +--- +keywords: [指标收集, 数据收集, 隐私保护, 配置管理, 禁用指标, 操作系统, 机器架构, 集群信息] +description: 介绍 GreptimeDB 的指标收集功能,包括收集的数据类型、如何禁用指标收集等内容。 +--- + +# 指标收集 + +为了提升我们的服务,GreptimeDB 会收集一些数据,包括 GreptimeDB 版本、节点数量、使用的操作系统、环境架构以及类似的技术细节等信息。但是我们尊重您的隐私,并确保不收集任何特定于用户的数据,其中包括数据库名称、表名称、查询内容等。 + +你的体验和隐私是我们的首要任务。你可以根据自己的喜好轻松管理此指标收集,通过配置选择启用或禁用它。 + +## 将会收集哪些数据 + +详细的数据信息可能会随着时间的推移而发生变化,这些更改(如果有)将在发行说明中公布。 + +启用指标收集后,GreptimeDB 将每半小时收集一次以下信息: + +- GreptimeDB 版本 +- GreptimeDB 的构建 git 哈希 +- 运行 GreptimeDB 的设备的操作系统(Linux、macOS 等) +- GreptimeDB 运行的机器架构(x86_64、arm64 等) +- GreptimeDB 运行模式(独立、分布式) +- 随机生成的安装 ID +- GreptimeDB 集群中的 datanode 数量 +- 系统运行时间,非精确数字,仅为 `hours`、`weeks` 等时间范围,并且不带数字 + +数据示例: +```json +{ + "os": "linux", + "version": "0.15.1", + "arch": "aarch64", + "mode": "Standalone", + "git_commit": "00d759e828f5e148ec18141904e20cb1cb7577b0", + "nodes": 1, + "uuid": "43717682-baa8-41e0-b126-67b797b66606", + "uptime": "hours" +} +``` + +## 如何禁用指标收集 + +从 GreptimeDB v0.4.0 开始,指标收集将默认启用。你可以通过更改配置来禁用它。 + +### 独立模式 + +将独立配置文件中的 `enable_telemetry` 设置为 `false`: + +```toml +# Whether to enable greptimedb telemetry, true by default. +enable_telemetry = false +``` + +或者在启动时通过环境变量 `GREPTIMEDB_STANDALONE__ENABLE_TELEMETRY=false` 进行配置。 + +### 分布式模式 + +将 metasrv 配置文件中的 `enable_telemetry` 设置为 `false`: + +```toml +# metasrv config file +# Whether to enable greptimedb telemetry, true by default. +enable_telemetry = false +``` + +或者在启动时设置环境变量 `GREPTIMEDB_METASRV__ENABLE_TELEMETRY=false`。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/time-durations.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/time-durations.md new file mode 100644 index 0000000000..d9ba4ab119 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/reference/time-durations.md @@ -0,0 +1,51 @@ +--- +keywords: [时间范围, 时间跨度, 时间单位] +description: 了解 GreptimeDB 中时间范围对象的表示方法,包括支持的时间单位和示例。 +--- + +# 时间范围对象 + +GreptimeDB 使用时间范围对象来表示各种上下文中的时间跨度, +包括 SQL 查询、配置文件和 API 请求。 +有关如何使用时间范围对象的信息, +请参阅: +- [ALTER](/reference/sql/alter.md) 语句中的 TTL 选项和 TWCS compaction 策略的时间窗口设置。 +- [CREATE](/reference/sql/create.md) 语句中的 TTL 选项。 + +时间范围对象表示为由连接的时间跨度组成的字符串, +每个时间跨度由一个十进制数字序列和一个单位后缀表示。 +这些后缀不区分大小写,并且支持单数和复数形式。例如,`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-1.0/tutorials/k8s-metrics-monitor.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/tutorials/k8s-metrics-monitor.md new file mode 100644 index 0000000000..7f61e542fc --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/tutorials/k8s-metrics-monitor.md @@ -0,0 +1,328 @@ +--- +keywords: [Kubernetes, Prometheus, 监控, 指标, 可观测性, GreptimeDB, Prometheus Operator, Grafana] +description: 使用 Prometheus 监控 Kubernetes 指标的指南,以 GreptimeDB 作为存储后端,包括架构概览、安装和使用 Grafana 进行可视化。 +--- + +# 使用 Prometheus 和 GreptimeDB 监控 Kubernetes 指标 + +本指南演示如何建立一个完整的 Kubernetes 监控解决方案, +该方案使用 Prometheus 收集指标, +使用 GreptimeDB 作为长期存储后端。 + +## 什么是 Kubernetes 监控 + +Kubernetes 监控指的是从 Kubernetes 集群中收集、分析和处理指标和日志。 +它是检查容器化应用程序和基础设施的健康状况、性能和资源利用率的关键。 + +Kubernetes 主要监控以下信息: + +- **资源指标**:节点、Pod 和容器的 CPU、内存、磁盘和网络使用情况 +- **集群健康**:集群组件如 kube-apiserver、etcd 和 controller-manager 的状态 +- **应用程序指标**:在集群中运行的应用程序指标 +- **事件和日志**:用于故障诊断的 Kubernetes 事件和容器日志 + +有效的监控可以帮助你: +- 在问题影响用户之前检测和诊断问题 +- 优化资源利用率并降低成本 +- 基于历史趋势进行容量规划 +- 确保 SLA 合规性 +- 排查性能瓶颈 + +## 架构概览 + +监控架构由以下组件组成: + +![Kubernetes 监控架构](/k8s-metrics-monitor-architecture.drawio.svg) + +**组件:** + +- **kube-state-metrics**:导出关于 Kubernetes 对象(部署、Pod、服务等)的集群级指标 +- **Node Exporter**:从每个 Kubernetes 节点导出硬件和操作系统级指标 +- **Prometheus Operator**:使用 Kubernetes 自定义资源自动化 Prometheus 部署和配置 +- **GreptimeDB**:Prometheus 指标的长期存储后端,具有高压缩率和查询性能 +- **Grafana**:为存储在 GreptimeDB 中的指标提供仪表板和可视化 + +## 前提条件 + +在开始之前,确保你拥有: + +- 一个运行中的 Kubernetes 集群(版本 >= 1.18) +- 已配置 `kubectl` 以访问你的集群 +- 已安装 [Helm](https://helm.sh/docs/intro/install/) v3.0.0 或更高版本 +- 足够的集群资源(至少 2 个 CPU 核心和 4GB 可用内存) + +## 安装 GreptimeDB + +GreptimeDB 被作为 Prometheus 指标的长期存储后端, +请参考[部署 GreptimeDB 集群](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md)文档了解如何部署。 + +### 验证 GreptimeDB 的部署 + +部署 GreptimeDB 后,验证集群是否正常运行中。 +在本指南中,我们假设 GreptimeDB 集群部署在 `greptime-cluster` 命名空间,名称为 `greptimedb`。 + +```bash +kubectl -n greptime-cluster get greptimedbclusters.greptime.io greptimedb +``` + +```bash +NAME FRONTEND DATANODE META FLOWNODE PHASE VERSION AGE +greptimedb 1 2 1 1 Running v0.17.2 33s +``` + +检查 Pod 状态: + +```bash +kubectl get pods -n greptime-cluster +``` + +```bash +NAME READY STATUS RESTARTS AGE +greptimedb-datanode-0 1/1 Running 0 71s +greptimedb-datanode-1 1/1 Running 0 97s +greptimedb-flownode-0 1/1 Running 0 64s +greptimedb-frontend-8bf9f558c-7wdmk 1/1 Running 0 90s +greptimedb-meta-fc4ddb78b-nv944 1/1 Running 0 87s +``` + +### 访问 GreptimeDB + +可以将 frontend 服务的端口转发到本地来连接 GreptimeDB。 +GreptimeDB 支持多种协议,其中 MySQL 协议默认使用端口 `4002`。 + +```bash +kubectl port-forward -n greptime-cluster svc/greptimedb-frontend 4002:4002 +``` + +使用 MySQL 客户端连接 GreptimeDB: + +```bash +mysql -h 127.0.0.1 -P 4002 +``` + +### 存储分区 + +为了提高查询性能并降低存储成本, +GreptimeDB 会基于 Prometheus 指标标签自动创建列,并将指标存储在物理表中,默认使用的物理表名为 `greptime_physical_table`。 +在上方我们部署了具有[多个 datanode 节点](#验证-greptimedb-的部署)的 GreptimeDB 集群, +你可以对表进行分区将数据分布到各个 datanode 节点上,以获得更好的可扩展性和性能。 + +在此 Kubernetes 监控场景中, +可以使用 `namespace` 标签作为分区键。 +例如,对于 `kube-public`、`kube-system`、`monitoring`、`default`、`greptime-cluster` 和 `etcd-cluster` 等命名空间, +你可以基于命名空间的首字母创建分区方案: + +```sql +CREATE TABLE greptime_physical_table ( + greptime_value DOUBLE NULL, + namespace STRING PRIMARY KEY, + greptime_timestamp TIMESTAMP TIME INDEX, +) +PARTITION ON COLUMNS (namespace) ( + namespace < 'f', + namespace >= 'f' AND namespace < 'g', + namespace >= 'g' AND namespace < 'k', + namespace >= 'k' +) +ENGINE = metric +WITH ( + "physical_metric_table" = "" +); +``` + +有关 Prometheus 指标存储和查询性能优化的更多信息, +请参阅[使用 metric engine 提高效率](/user-guide/ingest-data/for-observability/prometheus.md#通过使用-metric-engine-提高效率)指南。 + +### GreptimeDB 中的 Prometheus URL + +GreptimeDB 在 HTTP 上下文 `/v1/prometheus/` 下提供了[兼容 Prometheus 的 API](/user-guide/query-data/promql.md#prometheus-http-api), +使其能够与现有的 Prometheus 工作流程无缝集成。 + +你需要 GreptimeDB 服务地址来配置 Prometheus。 +由于 GreptimeDB 在 Kubernetes 集群内运行,所以使用内部集群地址。 + +GreptimeDB frontend 服务地址遵循以下模式: +``` +-frontend..svc.cluster.local: +``` + +在本指南中: +- GreptimeDB 集群名称:`greptimedb` +- 命名空间:`greptime-cluster` +- Frontend 端口:`4000` + +因此服务地址为: + +```bash +greptimedb-frontend.greptime-cluster.svc.cluster.local:4000 +``` + +Prometheus 的完整 [Remote Write URL](/user-guide/ingest-data/for-observability/prometheus.md#remote-write-configuration) 为: + +```bash +http://greptimedb-frontend.greptime-cluster.svc.cluster.local:4000/v1/prometheus/write +``` + +此 URL 包含: +- **服务端点**:`greptimedb-frontend.greptime-cluster.svc.cluster.local:4000` +- **API 路径**:`/v1/prometheus/write` + +## 安装 Prometheus + +现在 GreptimeDB 正常运行中, +我们将安装 Prometheus 收集指标并将其发送到 GreptimeDB。 + +### 添加 Prometheus Community Helm 仓库 + +```bash +helm repo add prometheus-community https://prometheus-community.github.io/helm-charts +helm repo update +``` + +### 安装 kube-prometheus-stack + +[`kube-prometheus-stack`](https://github.com/prometheus-operator/kube-prometheus) 是一个综合的监控解决方案,包括 +Prometheus、Grafana、kube-state-metrics 和 node-exporter 组件。 +此 stack 自动发现和监控所有 Kubernetes 命名空间, +收集来自集群组件、节点和工作负载的指标。 + +在此部署中, +我们将配置 Prometheus 使用 GreptimeDB 作为 Remote Write 目标长期存储指标数据, +并配置 Grafana 的默认 Prometheus 数据源使用 GreptimeDB。 + +创建一个 `kube-prometheus-values.yaml` 文件,包含以下配置: + +```yaml +# 配置 Prometheus 远程写入到 GreptimeDB +prometheus: + prometheusSpec: + remoteWrite: + - url: http://greptimedb-frontend.greptime-cluster.svc.cluster.local:4000/v1/prometheus/write + +# 配置 Grafana 使用 GreptimeDB 作为默认 Prometheus 数据源 +grafana: + datasources: + datasources.yaml: + apiVersion: 1 + datasources: + - name: Prometheus + type: prometheus + url: http://greptimedb-frontend.greptime-cluster.svc.cluster.local:4000/v1/prometheus + access: proxy + editable: true +``` + +此配置文件为以下用途指定了[GreptimeDB 服务地址](#greptimedb-中的-prometheus-url): + +- **Prometheus Remote Write**:将收集的指标发送到 GreptimeDB 进行长期存储 +- **Grafana 数据源**:将 GreptimeDB 配置为仪表板查询的默认 Prometheus 数据源 + +使用 Helm 和自定义配置文件安装 `kube-prometheus-stack`: + +```bash +helm install kube-prometheus prometheus-community/kube-prometheus-stack \ + --namespace monitoring \ + --create-namespace \ + --values kube-prometheus-values.yaml +``` + +### 验证安装 + +检查所有 Prometheus 组件是否正在运行: + +```bash +kubectl get pods -n monitoring +``` + +```bash +NAME READY STATUS RESTARTS AGE +alertmanager-kube-prometheus-kube-prome-alertmanager-0 2/2 Running 0 60s +kube-prometheus-grafana-78ccf96696-sghx4 3/3 Running 0 78s +kube-prometheus-kube-prome-operator-775fdbfd75-w88n7 1/1 Running 0 78s +kube-prometheus-kube-state-metrics-5bd5747f46-d2sxs 1/1 Running 0 78s +kube-prometheus-prometheus-node-exporter-ts9nn 1/1 Running 0 78s +prometheus-kube-prometheus-kube-prome-prometheus-0 2/2 Running 0 60s +``` + +### 验证监控状态 + +使用 [MySQL protocol](#访问-greptimedb) 查询 GreptimeDB,验证 Prometheus 指标是否已写入。 + +```sql +SHOW TABLES; +``` + +你应该能看到为各种 Prometheus 指标创建的表名。 + +```sql ++---------------------------------------------------------------------------------+ +| Tables | ++---------------------------------------------------------------------------------+ +| :node_memory_MemAvailable_bytes:sum | +| ALERTS | +| ALERTS_FOR_STATE | +| aggregator_discovery_aggregation_count_total | +| aggregator_unavailable_apiservice | +| alertmanager_alerts | +| alertmanager_alerts_invalid_total | +| alertmanager_alerts_received_total | +| alertmanager_build_info | +| ...... | ++---------------------------------------------------------------------------------+ +1553 rows in set (0.18 sec) +``` + +## 使用 Grafana 进行可视化 + +Grafana 包含在 kube-prometheus-stack 中, +并预配置了 Prometheus 作为数据源的仪表盘。 + +### 访问 Grafana + +将 Grafana 服务的端口转发到本地以访问 Web 界面: + +```bash +kubectl port-forward -n monitoring svc/kube-prometheus-grafana 3000:80 +``` + +### 获取管理员凭证 + +使用 kubectl 检索登录使用的 admin 密码: + +```bash +kubectl get secret --namespace monitoring kube-prometheus-grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo +``` + +### 登录 Grafana + +1. 打开浏览器并导航到 [http://localhost:3000](http://localhost:3000) +2. 使用以下凭证登录: + - **用户名**:`admin` + - **密码**:从上一步检索到的密码 + +### 查看预配置的仪表板 + +登录后,导航到**仪表板**以探索预配置的 Kubernetes 监控仪表板: + +- **Kubernetes / Compute Resources / Cluster**:集群范围的资源利用率概览 +- **Kubernetes / Compute Resources / Namespace (Pods)**:按命名空间分解的资源使用情况 +- **Kubernetes / Compute Resources / Node (Pods)**:节点级资源监控 +- **Node Exporter / Nodes**:详细的节点硬件和操作系统指标 + +![Grafana Dashboard](/k8s-prom-monitor-grafana.jpg) + +## 总结 + +你现在部署了完整的 Kubernetes 监控解决方案, +使用 Prometheus 收集指标,使用 GreptimeDB 提供高效的长期存储。 +该解决方案使你能够: + +- 实时监控集群和应用程序健康状况 +- 存储指标以进行历史分析和容量规划 +- 使用 Grafana 创建丰富的可视化和仪表板 +- 使用 PromQL 和 SQL 查询指标 + +有关 GreptimeDB 和 Prometheus 集成的更多信息,请参阅: + +- [Prometheus 集成](/user-guide/ingest-data/for-observability/prometheus.md) +- [在 GreptimeDB 中查询数据](/user-guide/query-data/overview.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/architecture.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/architecture.md new file mode 100644 index 0000000000..d3df2a731a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/architecture.md @@ -0,0 +1,32 @@ +--- +keywords: [基础架构, Metasrv, Frontend, Datanodes, 集群, 路由, 监测, 伸缩扩容, 数据存储, 读写请求] +description: 介绍 GreptimeDB 的基础架构,包括 Metasrv、Frontend 和 Datanodes 三个主要组成部分及其功能。 +--- + +# 基础架构 + +![architecture](/architecture-3.png) + +## 组件 + +为了形成一个强大的数据库集群,并控制其复杂性,GreptimeDB 架构中有三个主要组成部分:Metasrv,Frontend 和 Datanode。 + +- [**Metasrv**(元数据服务器)](/contributor-guide/metasrv/overview.md) 控制着 GreptimeDB 集群的核心命令。在典型的部署结构中,至少需要三个节点才能建立一个可靠的 Metasrv 小集群。Metasrv 管理着数据库和表的信息,包括数据如何在集群中传递、请求的转发地址等。它还负责监测 `Datanode` 的可用性和性能,以确保路由表的最新状态和有效性。 + +- [**Frontend**(前端服务)](/contributor-guide/frontend/overview.md) 作为无状态的组件,可以根据需求进行伸缩扩容。它负责接收请求并鉴权,将多种协议转化为 GreptimeDB 集群的内部 gRPC 协议,并根据 Metasrv 中的表的分片路由信息将请求转发到相应的 Datanode。 + +- [**Datanode**(数据节点)](/contributor-guide/datanode/overview.md) 负责 GreptimeDB 集群中的表的 `region` 数据存储,接收并执行从 Frontend 发来的读写请求,处理查询和写入,并返回对应的结果。 + +通过灵活的架构设计,以上三个组件既可以是集群分布式部署,也可以合并打包在一个二进制包内,支持本地部署下的单机模式,我们称之为 standalone 模式。 + +## 组件交互 + +![Interactions between components](/how-it-works.png) + +- 你可以通过多种协议与数据库交互,例如使用 InfluxDB line Protocol 插入数据,然后使用 SQL 或 PromQL 查询数据。Frontend 是客户端连接和操作数据库的组件,因此在其后面隐藏了 Datanode 和 Metasrv。 +- 假设客户端向 Frontend 实例发送了 HTTP 请求来插入数据。当 Frontend 接收到请求时,它会使用相应的协议解析器解析请求正文,并从 Metasrv 的 catalog 中找到要写入的表。 +- Frontend 依靠推拉结合的策略缓存来自 Metasrv 的元数据,因此它知道应将请求发送到哪个 Datanode,或者更准确地说,应该发送到哪个 Region。如果请求的内容需要存储在不同的 Region 中,则请求可能会被拆分并发送到多个 Region。 +- 当 Datanode 接收到请求时,它将数据写入 Region 中,然后将响应发送回 Frontend。写入 Region 也意味着将数据写入底层的存储引擎中,该引擎最终将数据放置在持久化存储中。 +- 当 Frontend 从目标 Datanode 接收到所有响应时,就会将结果返回给用户。 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/data-model.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/data-model.md new file mode 100644 index 0000000000..c4eabd7a14 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/data-model.md @@ -0,0 +1,89 @@ +--- +keywords: [数据模型, 表结构, 列类型, 设计考虑, 时序表, Tag 列, Timestamp 列, Field 列, Metric 表, Log 表,链路追踪,GreptimeDB 数据模型] +description: 介绍 GreptimeDB 的数据模型,包括表的结构、列类型和设计考虑,适用于指标、日志和链路追踪数据。 +--- + +# 数据模型 + +## 模型 + +GreptimeDB 使用时序表来进行数据的组织、压缩和过期管理。数据模型主要基于关系型数据库中的表模型,同时考虑到了指标(metrics)、日志(logs)及链路追踪(traces)数据的特点。 + +GreptimeDB 中的所有数据都被组织成具有名称的表,每个表中的数据项由三种语义类型的列组成:`Tag`、`Timestamp` 和 `Field`。 + +- 表名通常与指标、日志的名称相同。 +- `Tag` 列唯一标识时间序列。具有相同 `Tag` 值的行属于同一个时间序列。有些 TSDB 也可能称它们为 label。 +- `Timestamp` 是指标、日志和链路追踪数据库的基础。它表示数据生成的日期和时间。一个表只能有一个具有 `Timestamp` 语义类型的列,也称为时间索引(`Time Index`)列。 +- 其他列是 `Field` 列。字段包含收集的数据指标或日志内容。这些字段通常是数值或字符串,但也可能是其他类型的数据,例如地理位置或时间戳。 + +表按时间序列对行进行组织,并按 `Timestamp` 对同一时间序列的行进行排序。表还可以根据应用的需求对具有相同 `Tag` 和 `Timestamp` 值的行进行去重。GreptimeDB 按时间序列存储和处理数据。选择正确的表结构对于高效的数据存储和查询至关重要;请参阅[表设计指南](/user-guide/deployments-administration/performance-tuning/design-table.md)了解更多详情。 + +### 指标 + +假设我们有一个名为 `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) + +这与大家熟悉的表模型非常相似。不同之处在于 `TIME INDEX` 约束,它用于将 `ts` 列指定为此表的时间索引列。 + +- 表名为 `system_metrics`。 +- `PRIMARY KEY` 约束指定了表的 `Tag` 列。`host` 列表示收集的独立机器的主机名,`idc` 列显示机器所在的数据中心。 +- `Timestamp` 列 `ts` 表示收集数据的时间。 +- `Field` 列中的 `cpu_util`、`memory_util`、`disk_util` 列分别表示机器的 CPU 利用率、内存利用率和磁盘利用率。这些列包含实际的数据。 +- 表按 `host`、`idc`、`ts` 对行进行排序和去重。因此,查询 `select count(*) from system_metrics` 需要扫描所有的行做统计。 + +### 日志 + +另一个例子是创建一个用于日志(如 Server 访问日志)的表: + +```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, +) with ('append_mode'='true'); +``` + +- 时间索引列为 `access_time`。 +- 没有 tag 列。 +- `http_status`、`http_method`、`remote_addr`、`http_refer`、`user_agent` 和 `request` 是字段列。 +- 表按 `access_time` 对行进行排序。 +- 这个表是一个用于存储不需要去重的日志的[append-only 表](/reference/sql/create.md#创建-append-only-表)。 +- 查询 append-only 表一般会更快。例如,`select count(*) from access_logs` 可以直接使用统计信息作为结果而不需要考虑重复。 + +要了解如何指定 `Tag`、`Timestamp` 和 `Field` 列,请参见[表管理](/user-guide/deployments-administration/manage-data/basic-table-operations.md#创建表)和 [CREATE 语句](/reference/sql/create.md)。 + +### 链路追踪 + +GreptimeDB 支持通过 OTLP/HTTP 协议直接写入 OpenTelemetry 追踪数据,详细信息请参考 [OLTP 追踪数据模型](/user-guide/ingest-data/for-observability/opentelemetry.md#数据模型-2)。 + +## 设计考虑 + +GreptimeDB 基于表进行设计,原因如下: + +- 表格模型易于学习,具有广泛的用户群体,我们只需引入时间索引的概念即可实现对指标、日志和链路跟踪的统一处理。 +- Schema 是描述数据特征的元数据,对于用户来说更方便管理和维护。 +- Schema 通过其类型、长度等信息带来了巨大的优化存储和计算的好处,我们可以进行有针对性的优化。 +- 当我们有了表格 Schema 后,自然而然地引入了 SQL,并用它来处理各种表之间的关联分析和聚合查询,为用户抵消了学习和使用成本。 +- 比起 OpenTSDB 和 Prometheus 采用的单值模型,GreptimeDB 使用多值模型使其中一行数据可以具有多列数据。多值模型面向数据源建模,一个指标或者事件可以使用多个 field 表示值。多值模型的优势在于它可以一次性向数据库写入或读取多个值,从而减少传输流量并简化查询。相比之下,单值模型则需要将数据拆分成多个记录。阅读[博客](https://greptime.com/blogs/2024-05-09-prometheus)以获取更多详情。 + +GreptimeDB 使用 SQL 管理表 Schema。有关更多信息,请参见[表管理](/user-guide/deployments-administration/manage-data/basic-table-operations.md)。但是,我们对 Schema 的定义并不是强制性的,而是倾向于 **Schemaless** 的方式,类似于 MongoDB。有关更多详细信息,请参见[自动生成表结构](../ingest-data/overview.md#自动生成表结构)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/features-that-you-concern.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/features-that-you-concern.md new file mode 100644 index 0000000000..07fe7a0565 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/features-that-you-concern.md @@ -0,0 +1,80 @@ +--- +keywords: [关键特性, 日志处理, 链路追踪,数据更新, 数据删除, TTL 策略, 压缩率, 高基数问题, 持续聚合, 云存储, 性能对比, 灾难恢复, 地理空间索引, JSON 数据,时序数据库特性,可观测性数据库特性] +description: 介绍 GreptimeDB 的关键特性,并解答用户关心的常见问题,如日志处理、数据更新和删除、TTL 策略等。 +--- + +# 关键特性 + +## GreptimeDB 支持处理日志或事件吗? + +是的。从 v0.9.0 版本开始,GreptimeDB 将指标、日志和链路追踪视为带有时间戳的上下文“宽”事件(Wide Events),从而统一了指标、日志和链路追踪的处理。它支持使用 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 等性价比高的云存储服务中,请参考这里的存储[配置指南](/user-guide/deployments-administration/configuration.md#storage-options)。 + +GreptimeDB 还提供一个完全托管的云服务 [GreptimeCloud](https://greptime.cn/product/cloud) 来帮助您管理云中的数据。 + +## GreptimeDB 对比其他存储或时序数据库的性能如何? + +GreptimeDB 在 [ClickHouse 的 JSONBench 测试中 Cold Run 斩获第一](https://greptime.cn/blogs/2025-03-18-json-benchmark-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/2025-03-07-greptimedb-log-benchmark) +* [GreptimeDB vs. SQLite](https://greptime.cn/blogs/2024-08-30-sqlite) + +## GreptimeDB 有灾难恢复解决方案吗? + +有的,请参阅[灾难恢复文档](/user-guide/deployments-administration/disaster-recovery/overview.md)。 + +## GreptimeDB 有地理空间索引吗? + +我们提供 [内置函数](/reference/sql/functions/geo.md) 支持 Geohash, H3 and S2 索 +引。 + + +## GreptimeDB 支持 JSON 数据吗? + +我们提供 [内置函数](/reference/sql/functions/overview.md#json-functions) 支持访问 JSON 数据类型。 + +## 更多问题? + +有关 GreptimeDB 的更多常见问题解答,包括部署选项、迁移指南、性能对比和最佳实践等,请访问我们的[常见问题页面](/faq-and-others/faq.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/key-concepts.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/key-concepts.md new file mode 100644 index 0000000000..82dbd5a201 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/key-concepts.md @@ -0,0 +1,55 @@ +--- +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 Engine + +表引擎(也称为存储引擎)决定了数据在数据库中的存储、管理和处理方式。每种引擎提供不同的功能特性、性能表现和权衡取舍。GreptimeDB 提供了 `mito` 和 `metric` 引擎,有关更多信息,请参阅[表引擎](/reference/about-greptimedb-engines.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-1.0/user-guide/concepts/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/overview.md new file mode 100644 index 0000000000..a79689f752 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/overview.md @@ -0,0 +1,23 @@ +--- +keywords: [特点, 优势, 数据模型, 基础架构, 存储位置, 核心概念, 关键特性] +description: 概述 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 用户较为关心的指标(metrics)、日志(logs)和事件(events)数据库的特性。 +- [常见问题](/faq-and-others/faq.md): 全面的 FAQ,涵盖关于 GreptimeDB 能力、部署和使用的常见问题。 + +## 阅读更多 + +从我们的博客文章中获取 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-1.0/user-guide/concepts/storage-location.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/storage-location.md new file mode 100644 index 0000000000..e116039f80 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/storage-location.md @@ -0,0 +1,47 @@ +--- +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 +├── cache +├── logs +├── index_intermediate +│   └── staging +└── wal + ├── raftlog + ├── rewrite + └── LOCK +``` + +- `metadata`: 内部元数据目录,保存 catalog、数据库以及表的元信息、procedure 状态等内部状态。在集群模式下,此目录不存在,因为所有这些状态(包括区域路由信息)都保存在 `Metasrv` 中。 +- `data`: 存储 GreptimeDB 的实际的时间序列数据和索引文件。如果要自定义此路径,请参阅 [存储选项](/user-guide/deployments-administration/configuration.md#storage-options)。该目录按照 catalog 和 schema 的两级结构组织。 +- `cache`: 内部的数据缓存目录,比如对象存储的本地缓存等。 +- `logs`: GreptimeDB 日志文件目录。 +- `wal`: 预写日志文件目录。 +- `index_intermediate`: 索引构建和查询相关的的临时中间数据目录。 + +## 云存储 + +文件结构中的 `data` 目录可以存储在云存储中。请参考[存储选项](/user-guide/deployments-administration/configuration.md#storage-options)了解更多细节。 + +请注意,仅将 `data` 目录存储在对象存储中不足以确保数据可靠性和灾难恢复,`wal` 和 `metadata` 也需要考虑灾难恢复,更详细地请参阅[灾难恢复文档](/user-guide/deployments-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-1.0/user-guide/concepts/why-greptimedb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/why-greptimedb.md new file mode 100644 index 0000000000..e2896e7b06 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/concepts/why-greptimedb.md @@ -0,0 +1,99 @@ +--- +keywords: [时序数据库, 可观测性数据库,云原生, 分布式, 高性能, 用户友好, 存算分离, PromQL, SQL, Python,Rust 数据库] +description: 介绍 GreptimeDB 的特点、设计原则和优势,包括统一指标、日志和链路追踪,云原生架构,高性能和用户友好等。 +--- + +# 为什么选择 GreptimeDB + +GreptimeDB 是一款为云原生环境设计的开源可观测性数据库。我们的核心开发者在构建可观测性平台方面拥有丰富的经验,GreptimeDB 在以下关键领域体现了他们的最佳实践: + +## 统一处理可观测数据 + +GreptimeDB 通过以下方式统一处理指标、日志和链路追踪: +- 一致的[数据模型](./data-model.md),将所有可观测数据视为带有上下文的时间戳“宽”事件(Wide Events) +- 原生支持 [SQL](/user-guide/query-data/sql.md) 和 [PromQL](/user-guide/query-data/promql.md) 查询 +- 内置流处理功能 ([Flow](/user-guide/flow-computation/overview.md)),用于实时聚合和分析等 +- 跨不同类型的可观测数据进行无缝关联分析(阅读 [SQL 示例](/getting-started/quick-start.md#指标和日志的关联查询) 了解详细信息) + +它用高性能的单一解决方案取代了复杂的传统数据栈。 + +

单一解决方案替代复杂技术栈

+ +## 基于对象存储的成本优势 + +GreptimeDB 采用云对象存储(如 AWS S3、阿里云 OSS 和 Azure Blob Storage 等)作为存储层,与传统存储方案相比显著降低了成本。通过优化的列式存储和先进的压缩算法,实现了高达 50 倍的成本效率,而按需付费模式的 [GreptimeCloud](https://greptime.com/product/cloud) 确保您只需为实际使用的资源付费。 + +## 高性能 + +在性能优化方面,GreptimeDB 运用了多种技术,如 LSM Tree、数据分片和灵活的 WAL 选项(本地磁盘或 Kafka 等分布式服务),以处理大规模可观测数据的写入。 + +GreptimeDB 使用纯 Rust 编写,具有卓越的性能和可靠性。强大而快速的查询引擎由向量化执行和分布式并行处理(感谢 [Apache DataFusion](https://datafusion.apache.org/))驱动,并结合了丰富的[索引选项](/user-guide/manage-data/data-index.md),例如倒排索引、跳数索引和全文索引等。GreptimeDB将智能索引和大规模并行处理 (MPP) 结合在一起,以提升查询过程中数据剪枝和过滤的效率。 + +GreptimeDB 在[ClickHouse 的 JSONBench 测试中 Cold Run 斩获第一!](https://greptime.cn/blogs/2025-03-18-json-benchmark-greptimedb),更多报告请参阅[性能测试报告](https://greptime.cn/blogs/2024-09-09-report-summary)。 + +## 基于 Kubernetes 的弹性扩展 + +GreptimeDB 从底层就是为 Kubernetes 设计的,基于先进的存储计算分离的架构,实现真正的弹性扩展: + +- 存储和计算资源可独立扩展 +- 通过 Kubernetes 实现无限水平扩展 +- 不同工作负载(数据写入、查询、压缩、索引)之间的资源隔离 +- 自动故障转移和高可用性 + +![存储计算分离,计算资源隔离](/storage-compute-disaggregation-compute-compute-separation.png)。 + +## 灵活架构:从边缘到云端 + +![GreptimeDB 的架构](/architecture-2.png) + +GreptimeDB的模块化架构允许不同的组件根据需要独立运行或协同运行。其灵活的设计支持各种部署场景,从边缘设备到云环境,同时仍然使用一致的API进行操作。 例如: +- Frontend、Datanode 和 Metasrv 可以合并到一个独立的二进制文件中 +- 可以为每个表启用或禁用 WAL 或索引等组件 + +这种灵活性确保了 GreptimeDB 能够满足从边缘到云的解决方案的部署要求,了解[边云一体化解决方案](https://greptime.cn/carcloud)。 + +从嵌入式、单机部署到云原生集群,GreptimeDB 可以轻松适应各种环境。 + +## 易于迁移和使用 + +### 易于部署和维护 + +GreptimeDB 通过以下工具简化了部署和维护: +- [K8s Operator](https://github.com/GreptimeTeam/greptimedb-operator) +- [命令行工具](https://github.com/GreptimeTeam/gtctl) +- 内嵌[仪表盘](https://github.com/GreptimeTeam/dashboard) + +为了获得更简便的体验,请查看完全托管的 [GreptimeCloud](https://greptime.cn/product/cloud)。 + +### 易于集成 + +GreptimeDB 支持多种数据摄入协议,从而实现与现有可观测性技术栈的无缝集成: +- **数据库协议**:MySQL、PostgreSQL +- **时序数据协议**:InfluxDB、OpenTSDB、Prometheus RemoteStorage +- **可观测数据协议**:OpenTelemetry、Loki、ElasticSearch +- **高性能 gRPC 协议及客户端 SDK**(Java、Go、Erlang 等) + +在数据查询方面,GreptimeDB 提供: +- **SQL**:用于实时查询、复杂分析和数据库管理 +- **PromQL**:原生支持实时指标查询和 Grafana 集成 + +GreptimeDB 与您的现有可观测性技术栈无缝集成,同时保持高性能和灵活性。 + +![Greptime Ecosystem](/greptime-ecosystem.png) + +### 简单的数据模型与自动创建表 + +GreptimeDB 引入了一种新的数据模型,该模型结合了时序和关系模型: +- 数据以表格(Table)形式表示,包含行(Row)和列(Column) +- 指标、日志和链路追踪信息映射到列,时间索引(Time Index)用于时间戳列 +- Schema 是动态创建的,并且在数据写入时会自动添加新列 + +![时序表](/time-series-table.png) + +然而,我们对 schema 的定义不是强制性的,而是更倾向于 MongoDB 等数据库的无 schema 方法。 +表将在数据写入时动态自动创建,并自动添加新出现的列(Tag 和 Field)。更详细的说明,请阅读[数据模型](./data-model.md)。 + +要了解更多关于我们的方法和架构,请查看博客文章: +* [《什么是可观测性 2.0?什么是可观测性 2.0 原生数据库?》](https://greptime.cn/blogs/2025-04-24-observability2.0-greptimedb.html) +* [《专为实时而生》](https://greptime.cn/blogs/2022-11-16-github) +* [《GreptimeDB 统一存储架构》](https://greptime.cn/blogs/2024-12-24-observability) \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/authentication/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/authentication/overview.md new file mode 100644 index 0000000000..72214650bf --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/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-administration/authentication.md):**企业版功能**,使用外部 LDAP 服务进行用户身份验证。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/authentication/static.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/authentication/static.md new file mode 100644 index 0000000000..9427d1d85e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/authentication/static.md @@ -0,0 +1,90 @@ +--- +keywords: [静态用户配置, 身份验证, 用户帐户, 配置文件, 固定帐户] +description: 介绍了 GreptimeDB 的静态用户配置,允许通过配置文件设置固定帐户进行身份验证。 +--- + +# Static User Provider + +GreptimeDB 提供了简单的内置身份验证机制,允许你配置一个固定的帐户以方便使用,或者配置一个帐户文件以支持多个用户帐户。通过传入文件,GreptimeDB 会加载其中的所有用户。 + +## 单机模式 + +GreptimeDB 从配置文件中读取用户配置,每行定义一个用户及其密码和可选的权限模式。 + +### 基本配置 + +基本格式使用 `=` 作为用户名和密码之间的分隔符: + +``` +greptime_user=greptime_pwd +alice=aaa +bob=bbb +``` + +以这种方式配置的用户默认拥有完整的读写权限。 + +### 权限模式 + +你可以选择性地指定权限模式来控制用户的访问级别。格式为: + +``` +username:permission_mode=password +``` + +可用的权限模式: +- `rw` 或 `readwrite` - 完整的读写权限(未指定时的默认值) +- `ro` 或 `readonly` - 只读权限 +- `wo` 或 `writeonly` - 只写权限 + +混合权限模式的配置示例: + +``` +admin=admin_pwd +alice:readonly=aaa +bob:writeonly=bbb +viewer:ro=viewer_pwd +editor:rw=editor_pwd +``` + +在此配置中: +- `admin` 拥有完整的读写权限(默认) +- `alice` 拥有只读权限 +- `bob` 拥有只写权限 +- `viewer` 拥有只读权限 +- `editor` 明确设置了读写权限 + +### 启动服务器 + +在启动服务端时,需添加 `--user-provider` 参数,并将其设置为 `static_user_provider:file:`(请将 `` 替换为你的用户配置文件路径): + +```shell +./greptime standalone start --user-provider=static_user_provider:file: +``` + +用户及其权限将被载入 GreptimeDB 的内存。使用这些用户账户连接至 GreptimeDB 时,系统会严格执行相应的访问权限控制。 + +:::tip 注意 +`static_user_provider:file` 模式下,文件的内容只会在启动时被加载到数据库中,在数据库运行时修改或追加的内容不会生效。 +::: + +### 动态文件重载 + +如果你需要在不重启服务器的情况下更新用户凭证,可以使用 `watch_file_user_provider` 替代 `static_user_provider:file`。该 provider 会监控凭证文件的变化并自动重新加载: + +```shell +./greptime standalone start --user-provider=watch_file_user_provider: +``` + +`watch_file_user_provider`的特点: +- 使用与 `static_user_provider:file` 相同的文件格式 +- 自动检测文件修改并重新加载凭证 +- 允许在不重启服务器的情况下添加、删除或修改用户 +- 如果文件临时不可用或无效,会保持上次有效的配置 + +这在需要动态管理用户访问的生产环境中特别有用。 + +## Kubernetes 集群 + +你可以在 `values.yaml` 文件中配置鉴权用户。 +更多详情,请参考 [Helm Chart 配置](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md#鉴权配置)。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/capacity-plan.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/capacity-plan.md new file mode 100644 index 0000000000..c1fc63891a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/capacity-plan.md @@ -0,0 +1,71 @@ +--- +keywords: [容量规划, CPU 需求, 内存需求, 存储需求, 数据保留策略, 硬件成本, 资源分配, 性能优化] +description: 提供 GreptimeDB 的 CPU、内存和存储需求的一般建议,帮助用户根据工作负载进行容量规划。 +--- + +# 容量规划 + +本指南提供了关于 GreptimeDB 的 CPU、内存和存储需求的一般建议。 + +GreptimeDB 具备超轻量级的启动基准, +这使数据库能以最少的服务器资源启动。 +然而当为生产环境配置服务器容量时, +以下关键因素需要被考虑: + +- 每秒处理的数据点数 +- 每秒查询请求 +- 数据量 +- 数据保留策略 +- 硬件成本 + +要监控 GreptimeDB 的各种指标,请参阅[监控](/user-guide/deployments-administration/monitoring/overview.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-administration/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-1.0/user-guide/deployments-administration/configuration.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/configuration.md new file mode 100644 index 0000000000..ca833c8bf8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/configuration.md @@ -0,0 +1,778 @@ +--- +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/overview.md)。 + +### 配置文件选项 + +你可以在 TOML 文件中指定配置项。 +例如,创建一个名为 `standalone.example.toml` 的配置文件,如下所示: + +```toml +[storage] +type = "File" +data_home = "./greptimedb_data/" +``` + +然后使用命令行参数 `-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) + +### Helm 配置 + +当使用 Helm 在 Kubernetes 上部署 GreptimeDB 时,你可以直接在 Helm `values.yaml` 文件中做相应的设置。 +请参阅 [Helm 配置项文档](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md)了解所有 Helm 支持的配置项。 + +对于仅在本篇文档中[可用的配置项](#配置项),你可以通过[注入 TOML 配置文件](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md#注入配置文件)来设置配置。 + + +### 环境变量 + +配置文件中的每个项目都可以映射到环境变量。 +例如,使用环境变量设置数据节点的 `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 +``` + +## 配置项 + +本节将介绍主要的配置项,请前往 GitHub 查看[所有配置项](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/config.md)。 + +### 协议选项 + +协议选项适用于 `frontend` 和 `standalone` 子命令,它指定了协议服务器地址和其他协议相关的选项。 + +:::tip 提示 +HTTP 协议配置适用于所有 GreptimeDB 组件:`frontend`、`datanode`、`flownode` 和 `metasrv`。 +::: + +下面的示例配置包含了所有协议选项的默认值。 +你可以在配置文件中更改这些值或禁用某些协议。 +例如禁用 OpenTSDB 协议支持,可以将 `enable` 参数设置为 `false`。 +请注意,为了保障数据库的正常工作,无法禁用 HTTP 和 gRPC 协议。 + +```toml +[http] +addr = "127.0.0.1:4000" +timeout = "30s" +body_limit = "64MB" + +[grpc] +bind_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" | +| | prom_validation_mode | 字符串 | 在 Prometheus Remote Write 协议中中是否检查字符串是否为有效的 UTF-8 字符串。可用选项:`strict`(拒绝任何包含无效 UTF-8 字符串的请求),`lossy`(用 [UTF-8 REPLACEMENT CHARACTER](https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-23/#G24272)(即 `�` ) 替换无效字符),`unchecked`(不验证字符串有效性)。 | +| grpc | | | gRPC 服务器选项 | +| | bind_addr | 字符串 | gRPC 服务绑定地址,默认为 "127.0.0.1:4001" | +| | runtime_size | 整数 | 服务器工作线程数量,默认为 8 | +| | max_connection_age | 字符串 | gRPC 连接在服务端保持的最长时间。参见 ["MAX_CONNECTION_AGE"](https://grpc.io/docs/guides/keepalive/)。默认不设置。示例:"1h" 表示 1 小时,"30m" 表示 30 分钟 | +| | flight_compression | 字符串 | Frontend 的 Arrow IPC 服务的压缩模式。可用选项:`none`:禁用所有压缩,`transport`:仅启用 gRPC 传输压缩(zstd),`arrow_ipc`:仅启用 Arrow IPC 压缩(lz4),`all`:启用所有压缩。默认值为 `none`。| +| 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 和 gRPC 接口,我们支持 TLS 配置 + +| Option | Key | Type | Description | +|------------------------------------------|-------------|---------|--------------------------------------------------| +| `mysql.tls`,`postgres.tls` 或 `grpc.tls` | | | MySQL 或 Postgres 的 TLS 配置 | +| | `mode` | String | TLS 模式,支持 `disable`, `prefer` and `require` | +| | `cert_path` | String | TLS 证书文件路径 | +| | `key_path` | String | TLS 私钥文件路径 | +| | `watch` | Boolean | 监控文件变化,自动重新加载证书或私钥 | + +### 查询选项 + +`查询`选项在 standalone、datanode 和 frontend 模式下有效,用于控制查询引擎的行为。 + +下表详细描述了这些选项: + +| 选项 | 键 | 类型 | 描述 | +| ----------- | ------------------ | ------ | -------------------------------------------------------------------- | +| parallelism | 整数 | `0` | 查询引擎的并行度。默认为 0,表示 CPU 核心数。 | + +示例配置: + +```toml +[query] +parallelism = 0 +``` + +### 存储选项 + +`存储`选项在 `datanode` 和 `standalone` 模式下有效,它指定了数据库数据目录和其他存储相关的选项。 + +GreptimeDB 支持将数据保存在本地文件系统,AWS S3 以及其兼容服务(比如 MinIO、digitalocean space、腾讯 COS、百度对象存储(BOS)等),Azure Blob Storage 和阿里云 OSS。 + +| 选项 | 键 | 类型 | 描述 | +| ------- | ----------------- | ------ | --------------------------------------------------- | +| storage | | | 存储选项 | +| | type | 字符串 | 存储类型,支持 "File","S3" 和 "Oss" 等。 | +| File | | | 本地文件存储选项,当 type="File" 时有效 | +| | data_home | 字符串 | 数据库存储根目录,默认为 "./greptimedb_data" | +| S3 | | | AWS S3 存储选项,当 type="S3" 时有效 | +| | name | 字符串 | 存储提供商名字,默认为 `S3` | +| | bucket | 字符串 | S3 桶名称 | +| | root | 字符串 | S3 桶中的根路径 | +| | endpoint | 字符串 | S3 的 API 端点 | +| | region | 字符串 | S3 区域 | +| | access_key_id | 字符串 | S3 访问密钥 id | +| | secret_access_key | 字符串 | S3 秘密访问密钥 | +| | enable_virtual_host_style | 布尔值 | 使用 virtual-host-style 域名而不是 path-style 域名调用 API,默认为 false | +| Oss | | | 阿里云 OSS 存储选项,当 type="Oss" 时有效 | +| | name | 字符串 | 存储提供商名字,默认为 `Oss` | +| | bucket | 字符串 | OSS 桶名称 | +| | root | 字符串 | OSS 桶中的根路径 | +| | endpoint | 字符串 | OSS 的 API 端点 | +| | access_key_id | 字符串 | OSS 访问密钥 id | +| | access_key_secret | 字符串 | OSS 秘密访问密钥 | +| Azblob | | | Azure Blob 存储选项,当 type="Azblob" 时有效 | +| | name | 字符串 | 存储提供商名字,默认为 `Azblob` | +| | container | 字符串 | 容器名称 | +| | root | 字符串 | 容器中的根路径 | +| | endpoint | 字符串 | Azure Blob 存储的 API 端点 | +| | account_name | 字符串 | Azure Blob 存储的账户名 | +| | account_key | 字符串 | 访问密钥 | +| | sas_token | 字符串 | 共享访问签名 | +| Gsc | | | Google Cloud Storage 存储选项,当 type="Gsc" 时有效 | +| | name | 字符串 | 存储提供商名字,默认为 `Gsc` | +| | root | 字符串 | Gsc 桶中的根路径 | +| | bucket | 字符串 | Gsc 桶名称 | +| | scope | 字符串 | Gsc 权限 | +| | credential_path | 字符串 | Gsc 访问证书 | +| | endpoint | 字符串 | GSC 的 API 端点 | + +文件存储配置范例: + +```toml +[storage] +type = "File" +data_home = "./greptimedb_data/" +``` + +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" +# cache_path = "/path/to/cache/home" +``` + +`cache_path` 指定存储缓存文件的本地目录,而 `cache_capacity` 则决定缓存目录中允许的最大文件总大小(以字节为单位)。你可以通过将 `cache_path` 设置为空字符串来禁用读取缓存。默认的缓存目录位于 `{data_home}` 目录下。我们建议你不用配置 `cache_path`,因为数据库会自动设置该目录。 + + +自 `v0.12` 之后,写入缓存不再是实验性的功能。你可以通过修改 mito 的配置调整缓存的大小 + +```toml +[[region_engine]] +[region_engine.mito] + +write_cache_size = "10GiB" +``` + +更详细的信息请参阅[性能调优技巧](/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md)。 + + +### WAL 选项 + +GreptimeDB 支持三种 WAL 存储方式:本地 WAL、Remote WAL 和 Noop WAL。关于它们的对比,请参见 [WAL 概述](/user-guide/deployments-administration/wal/overview.md)。具体配置可参考 [本地 WAL](/user-guide/deployments-administration/wal/local-wal.md)、[Remote WAL](/user-guide/deployments-administration/wal/remote-wal/configuration.md) 和 [Noop WAL](/user-guide/deployments-administration/wal/noop-wal.md) 文档。 + + +### Logging 选项 + +`frontend`、`metasrv`、`datanode` 和 `standalone` 都可以在 `[logging]` 部分配置 log、tracing 相关参数: + +```toml +[logging] +dir = "./greptimedb_data/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/deployments-administration/monitoring/tracing.md#指南如何配置-tracing-采样率)。 + +如何使用分布式追踪,请参考 [Tracing](/user-guide/deployments-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.index] +aux_path = "" +staging_size = "2GB" +metadata_cache_size = "64MiB" +content_cache_size = "128MiB" +content_cache_page_size = "64KiB" + +[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 扫描 | +| `index` | -- | -- | Mito 引擎中索引的选项。 | +| `index.aux_path` | 字符串 | `""` | 文件系统中索引的辅助目录路径,用于存储创建索引的中间文件和搜索索引的暂存文件,默认为 `{data_home}/index_intermediate`。为了向后兼容,该目录的默认名称为 `index_intermediate`。此路径包含两个子目录:- `__intm`: 用于存储创建索引时使用的中间文件。- `staging`: 用于存储搜索索引时使用的暂存文件。 | +| `index.staging_size` | 字符串 | `2GB` | 暂存目录的最大容量。 | +| `index.metadata_cache_size` | 字符串 | `64MiB` | 索引元数据的缓存大小。 | +| `index.content_cache_size` | 字符串 | `128MiB` | 索引内容的缓存大小。 | +| `index.content_cache_page_size` | 字符串 | `64KiB` | 倒排索引内容缓存的页大小。 | +| `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`). | +| `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/deployments-administration/monitoring/overview.md) 指南。 + +```toml +[export_metrics] +# Whether to enable export_metrics +enable=true +# Export time interval +write_interval = "30s" +``` + +- `enable`: 是否启用导出指标功能,默认为 `false`。 +- `write_interval`: 指标导出时间间隔。 + +#### `self_import` 方法 + +如果你使用的是 GreptimeDB 单机版,可以使用 `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 参数,比如认证信息。 + +### 心跳配置 +心跳配置在 `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 = "./greptimedb_data" +# metasrv 存储后端服务器地址,默认为 etcd 实现。 +# 对于 postgres 存储后端,格式为: +# "password=password dbname=postgres user=postgres host=localhost port=5432" +# 对于 mysql 存储后端,格式为: +# "mysql://user:password@ip:port/dbname" +# 对于 etcd 存储后端,格式为: +# "127.0.0.1:2379" +store_addrs = ["127.0.0.1:2379"] +# 如果不为空,metasrv 将使用此键前缀存储所有数据。 +store_key_prefix = "" +# metasrv 的存储后端类型。 +# 可选项: +# - `etcd_store`(默认值) +# - `memory_store` +# - `postgres_store` +# - `mysql_store` +backend = "etcd_store" +# 在 RDS 中存储元数据的表名。仅在使用 RDS kvbackend 时生效。 +# **仅当后端为 RDS kvbackend 时使用。** +meta_table_name = "greptime_metakv" +## PostgreSQL 选举的咨询锁 ID。仅在使用 PostgreSQL 作为 kvbackend 时生效。 +## 仅当后端为 `postgres_store` 时使用。 +meta_election_lock_id = 1 +# Datanode 选择器类型。 +# - "lease_based" (默认值) +# - `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 +## 设置启动 region 故障检测的延迟时间。 +## 该延迟有助于避免在所有 Datanode 尚未完全启动时,Metasrv 过早启动 region 故障检测,从而导致不必要的 region failover。 +## 尤其适用于未通过 GreptimeDB Operator 部署的集群,此时可能未正确启用集群维护模式,提前检测可能会引发误判。 +region_failure_detector_initialization_delay = "10m" +# 是否允许在本地 WAL 上进行 region failover。 +# **此选项不建议设置为 true, +# 因为这可能会在故障转移期间导致数据丢失。** +allow_region_failover_on_local_wal = false + +## Procedure 选项 +[procedure] + +## 最大重试次数 +max_retry_times = 12 + +## 程序的初始重试延迟 +retry_delay = "500ms" + +## 最大运行程序数。 +## 同一时间可以运行的程序最大数量。 +## 如果运行的程序数量超过此限制,程序将被拒绝。 +max_running_procedures = 128 + + +# Failure detector 选项 +# GreptimeDB 使用 Phi 累积故障检测器算法来检测数据节点故障。 +[failure_detector] + +## 判定节点故障前可接受的最大 φ 值。 +## 较低的值反应更快但会产生更多误报。 +threshold = 8.0 + +## 心跳间隔的最小标准差。 +## 防止微小变化导致 φ 值激增。在心跳间隔变化很小时防止过度敏感。 +min_std_deviation = "100ms" + +## 心跳之间可接受的暂停时长。 +## 在 φ 值上升前为学习到的平均间隔提供额外的宽限期,吸收临时网络故障或GC暂停。 +acceptable_heartbeat_pause = "10000ms" + +## 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" +``` + +| 键 | 类型 | 默认值 | 描述 | +| --------------------------------------------- | ------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `data_home` | String | `./greptimedb_data/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 做为元数据后端。
根据你的存储服务器类型配置地址,例如:
- 使用 `"127.0.0.1:2379"` 连接到 etcd
- 使用 `"password=password dbname=postgres user=postgres host=localhost port=5432"` 连接到 postgres
- 使用 `"mysql://user:password@ip:port/dbname"` 连接到 mysql | +| `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)。 | +| `region_failure_detector_initialization_delay` | String | `10m` | 设置启动 region 故障检测的延迟时间。该延迟有助于避免在所有 Datanode 尚未完全启动时,Metasrv 过早启动 region 故障检测,从而导致不必要的 region failover。尤其适用于未通过 GreptimeDB Operator 部署的集群,此时可能未正确启用集群维护模式,提前检测可能会引发误判。 | +| `allow_region_failover_on_local_wal` | Bool | false | 是否允许在本地 WAL 上进行 region failover。
**此选项不建议设置为 true,因为这可能会在故障转移期间导致数据丢失。** | +| `backend` | String | `etcd_store` | 元数据存储类型。
- `etcd_store` (默认)
- `memory_store` (纯内存存储 - 仅用于测试)
- `postgres_store`
- `mysql_store` | +| `meta_table_name` | String | `greptime_metakv` | 使用 RDS 存储元数据时的表名。**仅在 backend 为 postgre_store 和 mysql_store 时有效。** | +| `meta_election_lock_id` | Integer | `1` | 用于领导选举的 PostgreSQL 咨询锁 id。**仅在 backend 为 postgre_store 时有效。** | +| `procedure` | -- | -- | | +| `procedure.max_retry_times` | 整数 | `12` | Procedure 的最大重试次数。 | +| `procedure.retry_delay` | 字符串 | `500ms` | Procedure 初始重试延迟,延迟会指数增长。 | +| `procedure.max_running_procedures` | Integer | `128` | 同一时间可以运行的程序最大数量。如果运行的程序数量超过此限制,程序将被拒绝。 | +| `failure_detector` | -- | -- | 故障检测选项。 | +| `failure_detector.threshold` | 浮点数 | `8.0` | 判定节点故障前可接受的最大 φ 值。
较低的值反应更快但会产生更多误报。 | +| `failure_detector.min_std_deviation` | 字符串 | `100ms` | 心跳间隔的最小标准差。
防止微小变化导致 φ 值激增。在心跳间隔变化很小时防止过度敏感。 | +| `failure_detector.acceptable_heartbeat_pause` | 字符串 | `10000ms` | 心跳之间可接受的暂停时长。
在 φ 值上升前为学习到的平均间隔提供额外的宽限期,吸收临时网络故障或GC暂停。 | +| `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.auto_prune_interval` | String | `0s` | 定期自动裁剪远程 WAL 的时间间隔
设置为 `0s` 表示禁止自动裁剪 | +| `wal.trigger_flush_threshold` | Integer | `0` | 自动 WAL 裁剪中触发 region flush 操作的阈值
当满足以下条件时,metasrv 会对 region 发送 flush 请求:
`trigger_flush_threshold` + `prunable_entry_id` < `max_prunable_entry_id`
其中:
- `prunable_entry_id` 是该 region 可裁剪的最大日志条目 ID,在该 ID 之前的日志都不被该 region 使用
- `max_prunable_entry_id` 是使用与该 region 同一 kafka topic 的所有 region 可裁剪的最大日志条目 ID,在该 ID 之前的日志都不再被任一 region 使用
设置为 `0` 以禁止在自动 WAL 裁剪中触发 region flush 操作 | +| `wal.auto_prune_parallelism` | Integer | `10` | 自动 WAL 裁剪的最大并行任务限制,其中每个任务负责一个 kafka topic 的 WAL 裁剪 | +| `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.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 +[grpc] +bind_addr = "127.0.0.1:3001" +server_addr = "127.0.0.1:3001" +runtime_size = 8 +``` + +| Key | Type | Description | +| ---------------- | ------ | ------------------------------------------- | +| node_id | 整数 | 该 `datanode` 的唯一标识符。 | +| grpc.bind_addr | 字符串 | gRPC 服务绑定地址,默认为`"127.0.0.1:3001"`。 | +| grpc.server_addr | 字符串 | 该地址用于来自主机外部的连接和通信。如果留空或未设置,服务器将自动使用主机上第一个网络接口的 IP 地址,其端口号与 `grpc.bind_addr` 中指定的相同。 | +| grpc.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-1.0/user-guide/deployments-administration/deploy-on-kubernetes/_pre_kind_helm.mdx b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/_pre_kind_helm.mdx new file mode 100644 index 0000000000..138ed3e6d6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/_pre_kind_helm.mdx @@ -0,0 +1,92 @@ +## 前置条件 + +- [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 +``` +
diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md new file mode 100644 index 0000000000..662fb40273 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md @@ -0,0 +1,594 @@ +--- +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: "VAR::greptimedbVersion" + # -- 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: "VAR::greptimedbVersion" + # -- 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 +datanode: + 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: + - username: "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: [] +``` + +其中: + +- `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 + ``` + +每一个 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: true + replicas: 1 + podTemplate: + main: + resources: + requests: + memory: "1Gi" + cpu: "1" + limits: + memory: "2Gi" + cpu: "2" +``` + +### 对象存储配置 + +`objectStorage` 字段用于配置云对象存储(例如 AWS S3 和 Azure Blob Storage 等)作为 GreptimeDB 存储层。 + +#### AWS S3 + +```yaml +objectStorage: + credentials: + # AWS access key ID + accessKeyId: "" + # AWS secret access key + secretAccessKey: "" + s3: + # AWS S3 bucket name + bucket: "" + # AWS S3 region + region: "" + # The root path in bucket is 's3:////data/...' + root: "" + # The AWS S3 endpoint, see more detail: https://docs.aws.amazon.com/general/latest/gr/s3.html + endpoint: "" +``` + +#### Google Cloud Storage + +```yaml +objectStorage: + credentials: + # GCP serviceAccountKey JSON-formatted base64 value + serviceAccountKey: "" + gcs: + # Google Cloud Storage bucket name + bucket: "" + # Google Cloud OAuth 2.0 Scopes, example: "https://www.googleapis.com/auth/devstorage.read_write" + scope: "" + # The root path in bucket is 'gcs:////data/...' + root: "" + # Google Cloud Storage endpoint, example: "https://storage.googleapis.com" + endpoint: "" +``` + +#### Azure Blob + +```yaml +objectStorage: + credentials: + # Azure account name + accountName: "" + # Azure account key + accountKey: "" + azblob: + # Azure Blob container name + container: "" + # The root path in container is 'blob:////data/...' + root: "" + # Azure Blob endpoint, see: "https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-query-endpoint-srp?tabs=dotnet#query-for-the-blob-storage-endpoint" + endpoint: "" +``` + +#### AliCloud OSS + +```yaml +objectStorage: + credentials: + # AliCloud access key ID + accessKeyId: "" + # AliCloud access key secret + accessKeySecret: "" + oss: + # AliCloud OSS bucket name + bucket: "" + # AliCloud OSS region + region: "" + # The root path in bucket is 'oss:////data/...' + root: "" + # The AliCloud OSS endpoint + endpoint: "" +``` + +#### Volcengine TOS + +TOS ([Torch Object Storage](https://www.volcengine.com/docs/6349)) 是[火山引擎](https://www.volcengine.com)提供的海量、安全、低成本、易用、高可靠、高可用的对象存储服务。 + +```yaml +objectStorage: + credentials: + # Volcengine access key ID + accessKeyId: "" + # Volcengine secret access key + secretAccessKey: "" + s3: + # Volcengine TOS bucket name + bucket: "" + # Volcengine TOS region + region: "" + # The root path in bucket is 'tos:////data/...' + root: "" + # The Volcengine TOS endpoint, see more detail: https://www.volcengine.com/docs/6349/107356 + endpoint: "" + # Enable virtual host style so that OpenDAL will send API requests in virtual host style instead of path style. + enableVirtualHostStyle: true +``` + +### Prometheus 监控配置 + +如果你已经安装了 [prometheus-operator](https://github.com/prometheus-operator/prometheus-operator),你可以通过 `prometheusMonitor.enabled` 字段创建 Prometheus PodMonitor 来监控 GreptimeDB,如下所示: + +```yaml +prometheusMonitor: + # -- Create PodMonitor resource for scraping metrics using PrometheusOperator + enabled: false + # -- Interval at which metrics should be scraped + interval: "30s" + # -- Add labels to the PodMonitor + labels: + release: prometheus +``` + +### Debug Pod 配置 + +debug pod 中安装了各种工具(例如 mysql-client、psql-client 等)。你可以 exec 进入调试 debug pod 进行调试。使用 `debugPod.enabled` 字段创建它,如下所示: + +```yaml +debugPod: + # -- Enable debug pod + enabled: false + + # -- The debug pod image + image: + registry: docker.io + repository: greptime/greptime-tool + tag: "VAR::debugPodVersion" + + # -- The debug pod resource + resources: + requests: + memory: 64Mi + cpu: 50m + limits: + memory: 256Mi + cpu: 200m +``` + +### 配置 Metasrv 后端存储 + +#### 使用 MySQL 和 PostgreSQL 作为后端存储 + +你可以通过 `meta.backendStorage` 字段配置 Metasrv 的后端存储。 + +以 MySQL 为例。 + +```yaml +meta: + backendStorage: + mysql: + # -- MySQL host + host: "mysql.default.svc.cluster.local" + # -- MySQL port + port: 3306 + # -- MySQL database + database: "metasrv" + # -- MySQL table + table: "greptime_metakv" + # -- MySQL credentials + credentials: + # -- MySQL credentials secret name + secretName: "meta-mysql-credentials" + # -- MySQL credentials existing secret name + existingSecretName: "" + # -- MySQL credentials username + username: "root" + # -- MySQL credentials password + password: "test" +``` + +- `mysql.host`: MySQL 主机。 +- `mysql.port`: MySQL 端口。 +- `mysql.database`: MySQL 数据库。 +- `mysql.table`: MySQL 表。 +- `mysql.credentials.secretName`: MySQL 凭证 secret 名称。 +- `mysql.credentials.existingSecretName`: MySQL 凭证 secret 名称。如果你希望使用已有的 secret,你需要确保该 secret 包含 `username` 和 `password` 两个 key。 +- `mysql.credentials.username`: MySQL 凭证用户名。如果 `mysql.credentials.existingSecretName` 被设置,该字段将被忽略。`username` 将会被存储在 `username` key 中,该 key 的值为 `mysql.credentials.secretName`。 +- `mysql.credentials.password`: MySQL 凭证密码。如果 `mysql.credentials.existingSecretName` 被设置,该字段将被忽略。`password` 将会被存储在 `password` key 中,该 key 的值为 `mysql.credentials.secretName`。 + +`meta.backendStorage.postgresql` 的大部分字段与 `meta.backendStorage.mysql` 的相同。例如: + +```yaml +meta: + backendStorage: + postgresql: + # -- PostgreSQL host + host: "postgres.default.svc.cluster.local" + # -- PostgreSQL port + port: 5432 + # -- PostgreSQL database + database: "metasrv" + # -- PostgreSQL table + table: "greptime_metakv" + # -- PostgreSQL Advisory lock id used for election, shouldn't be used in other clusters or applications. + electionLockID: 1 + # -- PostgreSQL credentials + credentials: + # -- PostgreSQL credentials secret name + secretName: "meta-postgresql-credentials" + # -- PostgreSQL credentials existing secret name + existingSecretName: "" + # -- PostgreSQL credentials username + username: "root" + # -- PostgreSQL credentials password + password: "root" +``` + +- `postgresql.host`: PostgreSQL 主机。 +- `postgresql.port`: PostgreSQL 端口。 +- `postgresql.database`: PostgreSQL 数据库。 +- `postgresql.table`: PostgreSQL 表。 +- `postgresql.electionLockID`: PostgreSQL 中用于选举的锁 ID。 +- `postgresql.credentials.secretName`: PostgreSQL 凭证 secret 名称。 +- `postgresql.credentials.existingSecretName`: PostgreSQL 凭证 secret 名称。如果你希望使用已有的 secret,你需要确保该 secret 包含 `username` 和 `password` 两个 key。 +- `postgresql.credentials.username`: PostgreSQL 凭证用户名。如果 `mysql.credentials.existingSecretName` 被设置,该字段将被忽略。`username` 将会被存储在 `username` key 中,该 key 的值为 `mysql.credentials.secretName`。 +- `postgresql.credentials.password`: PostgreSQL 凭证密码。如果 `mysql.credentials.existingSecretName` 被设置,该字段将被忽略。`password` 将会被存储在 `password` key 中,该 key 的值为 `mysql.credentials.secretName`。 + +#### 使用 etcd 作为后端存储 + +:::tip NOTE +chart 版本之间的配置结构已发生变化: + +- 旧版本: `meta.etcdEndpoints` +- 新版本: `meta.backendStorage.etcd.endpoints` + +请参考 chart 仓库中配置 [values.yaml](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-cluster/values.yaml) 以获取最新的结构。 +::: + +你可以通过 `meta.backendStorage.etcd` 字段配置 etcd 作为后端存储。 + +```yaml +meta: + backendStorage: + etcd: + # -- Etcd endpoints + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + # -- Etcd store key prefix + storeKeyPrefix: "" +``` + +- `etcd.endpoints`: etcd 服务地址。 +- `etcd.storeKeyPrefix`: etcd 存储 key 前缀。所有 key 都会被存储在这个前缀下。如果你希望使用一个 etcd 集群为多个 GreptimeDB 集群提供服务,你可以为每个 GreptimeDB 集群配置不同的存储 key 前缀。这仅用于测试和调试目的。 + +### 启用 Region Failover + +你可以通过 `meta.enableRegionFailover` 字段启用 Region Failover。在启用 Region Failover 之前,请确保你的部署满足 [Region Failover](/user-guide/deployments-administration/manage-data/region-failover.md) 文档中的先决条件。如果你的配置不满足条件,**Operator 将无法部署集群组件**。 + +```yaml +meta: + enableRegionFailover: true +``` + +#### 启用 Region Failover 在本地 WAL + +在本地 WAL 上启用 Region Failover,你需要设置 `meta.enableRegionFailover: true` 和在 `meta.configData` 字段中添加 `allow_region_failover_on_local_wal = true`。 + +:::warning WARNING +在本地 WAL 启用 Region Failover 可能会导致数据丢失。另外,确保你的 Operator 版本大于或等于 v0.2.2。 +::: + +```yaml +meta: + enableRegionFailover: true + configData: | + allow_region_failover_on_local_wal = true +``` + +### 专用 WAL 卷 + +配置专用 WAL 卷时,可以为 GreptimeDB Datanode 的 WAL(预写日志)目录使用单独的磁盘,并指定自定义的 `StorageClass`。 + +```yaml +dedicatedWAL: + enabled: true + raftEngine: + fs: + storageClassName: io2 # 使用 AWS ebs io2 存储以获得更好的性能 + name: wal + storageSize: 20Gi + mountPath: /wal +``` + + +### 启用 Remote WAL + +在启用前,请务必查阅 [Remote WAL 配置](/user-guide/deployments-administration/wal/remote-wal/configuration.md)文档,以了解完整的配置项说明及相关注意事项。 + +```yaml +remoteWal: + enabled: true + kafka: + brokerEndpoints: ["kafka.kafka-cluster.svc:9092"] +meta: + configData: | + [wal] + provider = "kafka" + replication_factor = 1 + auto_prune_interval = "30m" +datanode: + configData: | + [wal] + provider = "kafka" + overwrite_entry_start_id = true +``` \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-frontend-groups.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-frontend-groups.md new file mode 100644 index 0000000000..5eafa06f5b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-frontend-groups.md @@ -0,0 +1,110 @@ +--- +keywords: [Kubernetes, deployment, GreptimeDB, frontend groups, CRD, installation, verification] +description: 在 Kubernetes 上部署带有 frontend groups 的 GreptimeDB 集群的分步指南,包括先决条件、配置、安装和验证。 +--- + +# 部署多个具有 frontend 组的 GreptimeDB 集群 + +在本指南中,你将学习如何在 Kubernetes 上部署具有多个 frontend 组的 GreptimeDB 集群。 + +## 先决条件 + +- [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 +- [GreptimeDB Operator](https://github.com/GrepTimeTeam/greptimedb-operator) >= v0.3.0 +- [ETCD](https://github.com/bitnami/charts/tree/main/bitnami/etcd) + +## 升级 operator + +安装 GreptimeDB Operator,将镜像版本设置为大于或等于 `v0.3.0`。 +请参考 GreptimeDB Operator 文档查看[如何升级 Operator](/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md#升级)。 + +## Frontend 组配置 + +:::tip NOTE +chart 版本之间的配置结构已发生变化: + +- 旧版本: `meta.etcdEndpoints` +- 新版本: `meta.backendStorage.etcd.endpoints` + +请参考 chart 仓库中配置 [values.yaml](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-cluster/values.yaml) 以获取最新的结构。 +::: + +在配置 frontend 组时,确保每个组都包含 `name` 字段。以下 `values.yaml` 示例展示了如何为读写操作分别定义不同的 frontend 组: + +```yaml +frontend: + enabled: false # 禁用默认 frontend 组 + +frontendGroups: + - name: read + replicas: 1 + config: | + default_timezone = "UTC" + [http] + timeout = "60s" + template: + main: + resources: + limits: + cpu: 2000m + memory: 2048Mi + - name: write + replicas: 1 + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: + - "etcd.etcd-cluster.svc.cluster.local:2379" + +datanode: + replicas: 1 +``` + +你可以使用以下命令应用上述配置: +``` +helm upgrade --install ${release-name} greptime/greptimedb-cluster --namespace ${namespace} -f values.yaml +``` + +## 合规配置 + +设置 frontend 组时,必须设置名称。 + +```yaml +# 非法配置 !!! +frontendGroups: +# - name: read #<=========必须指定该字段=============> + - replicas: 1 +``` + +## 校验安装 + +检查 Pod 的状态: + +```bash +kubectl get pods -n default +NAME READY STATUS RESTARTS AGE +greptimedb-datanode-0 1/1 Running 0 27s +greptimedb-frontend-read-66bf68bd5c-8kg8g 1/1 Running 0 21s +greptimedb-frontend-read-66bf68bd5c-x752l 1/1 Running 0 21s +greptimedb-frontend-write-bdd944b97-pkf9d 1/1 Running 0 21s +greptimedb-meta-699f74cd9d-42w2c 1/1 Running 0 87s +``` + +检查 services 状态: + +```bash +kubectl get service -n default +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +greptimedb-datanode ClusterIP None 4001/TCP,4000/TCP 102s +greptimedb-frontend-read ClusterIP 10.96.174.200 4001/TCP,4000/TCP,4002/TCP,4003/TCP 42s +greptimedb-frontend-write ClusterIP 10.96.223.1 4001/TCP,4000/TCP,4002/TCP,4003/TCP 42s +greptimedb-meta ClusterIP 10.96.195.163 3002/TCP,4000/TCP 3m4s +``` + +## Conclusion + +您已成功部署 GreptimeDB 集群,其 frontend 组由读写实例组成。您现在可以继续探索 GreptimeDB 集群的功能,或根据需要将其与其他工具集成。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-remote-wal.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-remote-wal.md new file mode 100644 index 0000000000..543aafecdd --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-remote-wal.md @@ -0,0 +1,83 @@ +--- +keywords: [Kubernetes, 部署, GreptimeDB, Remote WAL, Kafka, 配置] +description: 本指南将逐步介绍如何在 Kubernetes 上部署启用了 Remote WAL 的 GreptimeDB 集群,包括前置条件、依赖组件、配置说明、安装步骤。 +--- + +# 部署启用 Remote WAL 的 GreptimeDB 集群 + +本指南将介绍如何在 Kubernetes 集群中部署启用了 Remote WAL(远程写前日志)的 GreptimeDB。在开始之前,建议先阅读 [部署 GreptimeDB 集群](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md) 文档。 + + +## 前置条件 + +- [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 + +## 所需依赖 + +在部署启用了 Remote WAL 的 GreptimeDB 之前,请确保元数据存储和 Kafka 集群已经部署完成,或者已准备好可用的实例: + +- 元数据存储:请参考 [管理元数据概述](/user-guide/deployments-administration/manage-metadata/overview.md) 了解更多详情。在本示例中,我们使用 etcd 作为元数据存储。 +- Kafka 集群:请参考 [管理 Kafka](/user-guide/deployments-administration/wal/remote-wal/manage-kafka.md) 了解更多详情。 + +## Remote WAL 配置 + +:::tip NOTE +chart 版本之间的配置结构已发生变化: + +- 旧版本: `meta.etcdEndpoints` +- 新版本: `meta.backendStorage.etcd.endpoints` + +请参考 chart 仓库中配置 [values.yaml](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-cluster/values.yaml) 以获取最新的结构。 +::: + +本示例假设你已经部署了一个 Kafka 集群,运行在 `kafka-cluster` 命名空间中,并且一个 etcd 集群运行在 `etcd-cluster` 命名空间中。`values.yaml` 文件如下: + +```yaml +meta: + backendStorage: + etcd: + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + configData: | + [wal] + provider = "kafka" + replication_factor = 1 + topic_name_prefix = "gtp_greptimedb_wal_topic" + auto_prune_interval = "30m" +datanode: + configData: | + [wal] + provider = "kafka" + overwrite_entry_start_id = true +remoteWal: + enabled: true + kafka: + brokerEndpoints: ["kafka.kafka-cluster.svc.cluster.local:9092"] +``` + +## 部署 GreptimeDB 集群 + +你可以使用以下命令部署 GreptimeDB 集群: + +```bash +helm upgrade --install mycluster \ + --values values.yaml \ + greptime/greptimedb-cluster \ + -n default +``` + +## 最佳实践 + +- **不要在已部署的集群中切换 WAL 存储类型**. 如果需要将 WAL 存储从本地更换为远程,必须 删除整个集群并重新部署,包括: + - 删除集群使用的所有 PersistentVolumeClaims(PVCs) + - 清空对象存储中的集群目录 + - 删除或清理使用的元数据存储 +- 建议先使用一个**最小可行部署**来验证集群是否运行正常,例如执行建表和插入数据等基本操作,确保数据库正常工作。 + +## 后续步骤 + +- 请参考 [部署 GreptimeDB 集群](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md) 指南访问你的 GreptimeDB 集群。 +- 请参考 [快速开始](/getting-started/quick-start.md) 指南创建表并写入数据。 +- 请参考 [Remote WAL 配置](/user-guide/deployments-administration/wal/remote-wal/configuration.md) 了解更多关于 Remote WAL 配置的信息。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md new file mode 100644 index 0000000000..a3123c79cb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md @@ -0,0 +1,459 @@ +--- +keywords: [Kubernetes 部署, GreptimeDB Operator, 测试集群, 安装, 验证, etcd 集群, 监控集成] +description: 在 Kubernetes 上使用 GreptimeDB Operator 部署 GreptimeDB 集群的指南,包括前置条件、创建测试集群、安装和验证步骤。 +--- + +# 部署 GreptimeDB 集群 + +在该指南中,你将学会如何使用 GreptimeDB Operator 在 Kubernetes 上部署 GreptimeDB 集群。 + +:::note +以下输出可能会因 Helm chart 版本和具体环境的不同而有细微差别。 +::: + +import PreKindHelm from './_pre_kind_helm.mdx'; + + + +## 安装和验证 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://github.com/bitnami/charts/tree/main/bitnami/etcd) 来安装一个 etcd 集群。 + +```bash +helm install etcd \ + oci://registry-1.docker.io/bitnamicharts/etcd \ + --version VAR::etcdChartVersion \ + --set replicaCount=3 \ + --set auth.rbac.create=false \ + --set auth.rbac.token.enabled=false \ + --create-namespace \ + --set global.security.allowInsecureImages=true \ + --set image.registry=docker.io \ + --set image.repository=greptime/etcd \ + --set image.tag=VAR::etcdImageVersion \ + -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 greptime/etcd:VAR::etcdImageVersion --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 global.security.allowInsecureImages=true \ + --set image.repository=bitnami/etcd \ + --set image.tag=VAR::etcdImageVersion \ + --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 +``` +
+ +## 配置 `values.yaml` + +`values.yaml` 文件设置了 GreptimeDB 的一些参数和配置,是定义 helm chart 的关键。 +例如一个最小规模 GreptimeDB 集群定义如下: + +```yaml +image: + registry: docker.io + # 镜像仓库: + # OSS GreptimeDB 使用 `greptime/greptimedb`, + # Enterprise GreptimeDB 请咨询工作人员 + repository: + # 镜像标签: + # OSS GreptimeDB 使用数据库版本,例如 `VAR::greptimedbVersion` + # Enterprise GreptimeDB 请咨询工作人员 + tag: + pullSecrets: [] + +initializer: + registry: docker.io + repository: greptime/greptimedb-initializer + +frontend: + replicas: 1 + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + +datanode: + replicas: 1 +``` + +:::note 备注 +中国大陆用户如有网络访问问题,可直接使用阿里云 OCI 镜像仓库: + +```yaml +image: + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + # 镜像仓库: + # OSS GreptimeDB 使用 `greptime/greptimedb`, + # Enterprise GreptimeDB 请咨询工作人员 + repository: + # 镜像标签: + # OSS GreptimeDB 使用数据库版本,例如 `VAR::greptimedbVersion` + # Enterprise GreptimeDB 请咨询工作人员 + tag: + pullSecrets: [] + +initializer: + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + repository: greptime/greptimedb-initializer + +frontend: + replicas: 1 + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + +datanode: + replicas: 1 +``` +::: + +上述配置不适用于严肃的生产环境,请根据自己的需求调整配置。 +可参考[配置文档](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md)获取完整的 `values.yaml` 的配置项。 + + +## 安装 GreptimeDB 集群 + +在上述步骤中我们已经准备好了 GreptimeDB Operator,etcd 集群以及 GreptimeDB 集群相应的配置, +现在部署一个最小 GreptimeDB 集群: + +```bash +helm upgrade --install mycluster \ + greptime/greptimedb-cluster \ + --values /path/to/values.yaml \ + -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. +``` +
+ +当启动集群安装之后,我们可以用如下命令检查 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-meta-58bc88b597-ppzvj 2/2 Running 0 86s +``` +
+ +正如你所看到的,我们默认创建了一个最小的 GreptimeDB 集群,包括 1 个 frontend、1 个 datanode 和 1 个 metasrv。关于一个完整的 GreptimeDB 集群的组成,你可以参考 [architecture](/user-guide/concepts/architecture.md)。 + +## 探索 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)。 + +## 删除集群 + +:::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 +``` + +### 清理 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-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-standalone.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-standalone.md new file mode 100644 index 0000000000..bd81853e15 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-standalone.md @@ -0,0 +1,204 @@ +--- +keywords: [Kubernetes 部署, GreptimeDB 单机版, 安装] +description: 在 Kubernetes 上部署 GreptimeDB 单机版的指南。 +--- + +# 部署 GreptimeDB 单机版 + +在该指南中,你将学会如何在 Kubernetes 上部署 GreptimeDB 单机版。 + +:::note +以下输出可能会因 Helm chart 版本和具体环境的不同而有细微差别。 +::: + +import PreKindHelm from './_pre_kind_helm.mdx'; + + + +## 安装 GreptimeDB 单机版 + +### 基础安装 + +使用默认配置快速安装: + +```bash +helm upgrade --install greptimedb-standalone greptime/greptimedb-standalone -n default +``` + +
+ Expected Output +```bash +Release "greptimedb-standalone" does not exist. Installing it now. +NAME: greptimedb-standalone +LAST DEPLOYED: Mon May 26 08:06:54 2025 +NAMESPACE: default +STATUS: deployed +REVISION: 1 +TEST SUITE: None +NOTES: +*********************************************************************** + Welcome to use greptimedb-standalone + Chart version: 0.1.53 + GreptimeDB Standalone version: 0.14.3 +*********************************************************************** + +Installed components: +* greptimedb-standalone + +The greptimedb-standalone is starting, use `kubectl get statefulset greptimedb-standalone -n default` to check its status. +``` +
+ +```bash +kubectl get pod -n default +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +greptimedb-standalone-0 1/1 Running 0 40s +``` +
+ +### 自定义安装 + +创建自定义配置文件 `values.yaml`: + +```yaml +resources: + requests: + cpu: "2" + memory: "4Gi" + limits: + cpu: "4" + memory: "8Gi" +``` + +更多配置选项请参考 [文档](https://github.com/GreptimeTeam/helm-charts/tree/main/charts/greptimedb-standalone). + +使用自定义配置安装: + +```bash +helm upgrade --install greptimedb-standalone greptime/greptimedb-standalone \ + --values values.yaml \ + --namespace default +``` + +
+ Expected Output +```bash +Release "greptimedb-standalone" has been upgraded. Happy Helming! +NAME: greptimedb-standalone +LAST DEPLOYED: Mon May 26 08:18:27 2025 +NAMESPACE: default +STATUS: deployed +REVISION: 2 +TEST SUITE: None +NOTES: +*********************************************************************** + Welcome to use greptimedb-standalone + Chart version: 0.1.53 + GreptimeDB Standalone version: 0.14.3 +*********************************************************************** + +Installed components: +* greptimedb-standalone + +The greptimedb-standalone is starting, use `kubectl get statefulset greptimedb-standalone -n default` to check its status. +``` +
+ +```bash +kubectl get pod -n default +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +greptimedb-standalone-0 1/1 Running 0 3s +``` +
+ +## 访问 GreptimeDB + +安装完成后,您可以通过以下方式访问 GreptimeDB: + +### MySQL 协议 + +```bash +kubectl port-forward svc/greptimedb-standalone 4002:4002 -n default > connections.out & +``` + +```bash +mysql -h 127.0.0.1 -P 4002 +``` + +
+ Expected Output +```bash +Welcome to the MariaDB monitor. Commands end with ; or \g. +Your MySQL connection id is 8 +Server version: 8.4.2 Greptime + +Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. + +Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. + +MySQL [(none)]> +``` +
+ +### PostgreSQL 协议 + +```bash +kubectl port-forward svc/greptimedb-standalone 4003:4003 -n default > connections.out & +``` + +```bash +psql -h 127.0.0.1 -p 4003 -d public +``` + +
+ Expected Output +```bash +psql (15.12, server 16.3-greptimedb-0.14.3) +WARNING: psql major version 15, server major version 16. + Some psql features might not work. +Type "help" for help. + +public=> +``` +
+ +### HTTP 协议 + +```bash +kubectl port-forward svc/greptimedb-standalone 4000:4000 -n default > connections.out & +``` + +```bash +curl -X POST \ + -d 'sql=show tables' \ + http://localhost:4000/v1/sql +``` + +
+ Expected Output +```bash +{"output":[{"records":{"schema":{"column_schemas":[{"name":"Tables","data_type":"String"}]},"rows":[["numbers"]],"total_rows":1}}],"execution_time_ms":5}[root +``` +
+ +## 卸载 + +删除 GreptimeDB 单机版: + +```bash +helm uninstall greptimedb-standalone -n default +``` + +```bash +kubectl delete pvc -l app.kubernetes.io/instance=greptimedb-standalone -n default +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md new file mode 100644 index 0000000000..b9d72ce2e7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/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-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.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-1.0/user-guide/deployments-administration/deploy-on-kubernetes/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/overview.md new file mode 100644 index 0000000000..2c28bf4d28 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/overview.md @@ -0,0 +1,42 @@ +--- +keywords: [Kubernetes 部署, Operator 模式, 自动化管理, 集群部署, 单机实例, 私有云, 公有云] +description: 在 Kubernetes 上部署 GreptimeDB 的概述,介绍了 GreptimeDB Operator 的功能和使用方法。 +--- + +# 在 Kubernetes 上部署 GreptimeDB + +GreptimeDB 专为云原生环境而构建,从第一天起就可以在 Kubernetes 上部署。 +你可以在任何云服务提供商上部署 GreptimeDB,包括 AWS、阿里云或谷歌云等。 + +## 部署 GreptimeDB 单机版 + +对于开发、测试或小规模生产用例,你可以在 Kubernetes 上[部署 GreptimeDB 单机实例](deploy-greptimedb-standalone.md)。 +这种方式较为简单,无需管理完整集群的复杂性。 + +## 部署 GreptimeDB 集群 + +对于需要高可用性和可扩展性的生产环境, +你可以使用 GreptimeDB Operator 在 Kubernetes 上[部署 GreptimeDB 集群](deploy-greptimedb-cluster.md)以建立分布式 GreptimeDB 集群, +水平扩展并高效处理大量数据。 + +## 配置 + +在部署 GreptimeDB 集群或单机实例时,你可以通过创建 `values.yaml` 文件 +来对 GreptimeDB 应用自定义配置。 +有关可用配置选项的完整列表,请参阅[通用 Helm Chart 配置](./common-helm-chart-configurations.md)。 + +## 管理 GreptimeDB Operator + +基于 GreptimeDB Operator,你可以很轻松地部署、升级和管理 GreptimeDB 集群和单机实例。 +无论是私有还是公有云部署,GreptimeDB Operator 都将快速部署和扩容 GreptimeDB 变得简单易行。 +了解如何[管理 GreptimeDB Operator](./greptimedb-operator-management.md), +包括安装和升级。 + +## 进阶部署 + +在熟悉了 [GreptimeDB 的架构和组件](/user-guide/concepts/architecture.md)之后,你可以进一步探索高级部署场景: + +- [部署带有 Remote WAL 的 GreptimeDB 集群](configure-remote-wal.md):将 Kafka 配置为 GreptimeDB 集群的远程预写日志 (WAL),以持久记录每个数据修改并确保不丢失内存缓存的数据。 +- [使用 MySQL/PostgreSQL 作为元数据存储](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md#配置-metasrv-后端存储):集成 MySQL/PostgreSQL 数据库以提供强大的元数据存储功能,增强可靠性和性能。 +- [部署多 Frontend 的 GreptimeDB 集群](configure-frontend-groups.md):GreptimeDB 集群的 Frontend 组由多个 Frontend 实例组成,以改善负载分配和可用性。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md new file mode 100644 index 0000000000..7807ea9dc8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md @@ -0,0 +1,157 @@ +--- +keywords: [备份, 恢复, 导出工具, 导入工具, 数据库备份, 数据恢复, 命令行工具, 使用场景, 最佳实践] +description: 介绍 GreptimeDB 的导出和导入工具,用于数据库备份和恢复,包括命令语法、选项、常见使用场景、最佳实践和故障排除等内容。 +--- + +# GreptimeDB 导出和导入工具 + +本指南描述了如何使用 GreptimeDB 的导出和导入工具进行数据库备份和恢复。 + +有关详细的命令行选项和高级配置,请参阅 [数据导出和导入](/reference/command-lines/utilities/data.md)。 + +## 概述 + +## 导出操作 + +### 完整数据库备份 +导出所有数据库备份。此操作将每个数据库导出到单个目录中,包括所有表及其数据。 +```bash +# 导出所有数据库备份 +greptime cli data export \ + --addr localhost:4000 \ + --output-dir /tmp/backup/greptimedb +``` +输出目录结构: +``` +/ +└── greptime/ + └── / + ├── create_database.sql + ├── create_tables.sql + ├── copy_from.sql + └── <数据文件> +``` + +#### 导出到 S3 + +导出所有数据库备份到 S3: +```bash +greptime cli data export \ + --addr localhost:4000 \ + --s3 \ + --s3-bucket \ + --s3-access-key \ + --s3-secret-key \ + --s3-region \ + --s3-root \ + --s3-endpoint +``` + +### 仅导出表结构 +仅导出表结构而不包含数据。此操作将 `CREATE TABLE` 语句导出到 SQL 文件中,允许您备份表结构而不包含实际数据。 +```bash +# 仅导出表结构 +greptime cli data export \ + --addr localhost:4000 \ + --output-dir /tmp/backup/schemas \ + --target schema +``` + +### 基于时间范围备份 +```bash +# 导出指定时间范围内的数据 +greptime cli data 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 data export \ + --addr localhost:4000 \ + --output-dir /tmp/backup/greptimedb \ + --database '{my_database_name}' +``` + +## 导入操作 + +### 完整数据库备份 +导入所有数据库备份。 +```bash +# 导入所有数据库 +greptime cli data import \ + --addr localhost:4000 \ + --input-dir /tmp/backup/greptimedb +``` + +### 仅导入表结构 +仅导入表结构而不包含数据。此操作将 `CREATE TABLE` 语句从 SQL 文件中导入,允许您恢复表结构而不包含实际数据。 +```bash +# 仅导入表结构 +greptime cli data import \ + --addr localhost:4000 \ + --input-dir /tmp/backup/schemas \ + --target schema +``` + +### 指定数据库备份 +```bash +# 导入指定数据库 +greptime cli data import \ + --addr localhost:4000 \ + --input-dir /tmp/backup/greptimedb \ + --database '{my_database_name}' +``` + +## 最佳实践 + +1. **并行度配置** + - 根据可用系统资源调整 `--export-jobs`/`--import-jobs` + - 从较低的值开始,逐步增加 + - 在操作期间监控系统性能 + +2. **备份策略** + - 使用时间范围进行增量数据备份 + - 定期备份用于灾难恢复 + +3. **错误处理** + - 使用 `--max-retry` 处理临时异常 + - 保留日志以便故障排除 + +## 性能提示 + +1. **导出性能** + - 对大型数据集使用时间范围 + - 根据 CPU/内存调整并行任务数量 + - 考虑网络带宽限制 + +2. **导入性能** + - 注意监控数据库资源 + +1. **导出性能** + - 对大型数据集使用时间范围 + - 根据 CPU/内存调整并行任务 + - 考虑网络带宽限制 + +2. **导入性能** + - 监控数据库资源 + +## 故障排除 + +### 常见问题 + +1. **连接错误** + - 验证服务器地址和端口 + - 检查网络连接 + - 确保身份验证凭据正确 + +2. **权限问题** + - 验证输出/输入目录的读写权限 + +3. **资源限制** + - 减少并行任务数 + - 确保足够的磁盘空间 + - 在操作期间监控系统资源 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md new file mode 100644 index 0000000000..69c423cf51 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md @@ -0,0 +1,120 @@ +--- +keywords: [备份, 恢复, 导出工具, 导入工具, 数据库元信息备份, 数据恢复, 命令行工具] +description: 介绍 GreptimeDB 的元数据导出和导入工具,用于数据库元信息的备份和恢复,包括命令语法、选项、常见使用场景 +--- + +# GreptimeDB 元信息导出和导入工具 + +本指南描述了如何使用 GreptimeDB 的元信息导出和导入工具进行元数据库备份和恢复。 + +有关详细的命令行选项和高级配置,请参阅 [元数据导出和导入](/reference/command-lines/utilities/metadata.md)。 + +## 概述 + +## 导出操作 + +### 导出到 S3 云存储 + +将元数据从 PostgreSQL 导出到 S3 云存储,用于云备份存储: + +```bash +greptime cli meta snapshot save \ + --store-addrs 'password=password dbname=postgres user=postgres host=localhost port=5432' \ + --backend postgres-store \ + --s3 \ + --s3-bucket your-bucket-name \ + --s3-region ap-southeast-1 \ + --s3-access-key \ + --s3-secret-key +``` + +**输出**: 在指定的 S3 桶中创建 `metadata_snapshot.metadata.fb` 文件。 + +### 导出到本地目录 + +#### 从 PostgreSQL 后端导出 + +将元数据从 PostgreSQL 导出到本地目录: + +```bash +greptime cli meta snapshot save \ + --store-addrs 'password=password dbname=postgres user=postgres host=localhost port=5432' \ + --backend postgres-store +``` + +#### 从 MySQL 后端导出 + +将元数据从 MySQL 导出到本地目录: + +```bash +greptime cli meta snapshot save \ + --store-addrs 'mysql://user:password@127.0.0.1:3306/database' \ + --backend mysql-store +``` + +#### 从 etcd 后端导出 + +将元数据从 etcd 导出到本地目录: + +```bash +greptime cli meta snapshot save \ + --store-addrs 127.0.0.1:2379 \ + --backend etcd-store +``` + +**输出**: 在当前工作目录中创建 `metadata_snapshot.metadata.fb` 文件。 + +## 导入操作 + +:::warning +**重要**: 在导入元数据之前,请确保目标存储后端的对应表中没有**任何数据**,否则可能会导致元数据损坏。 + +如果你需要导入到具有现有数据的后端,请使用 `--force` 标志绕过此安全检查。但是,请谨慎操作,因为这可能导致数据损坏。 +::: + +### 从 S3 云存储导入 + +从 S3 备份恢复元数据到 PostgreSQL 存储后端: + +```bash +greptime cli meta snapshot restore \ + --store-addrs 'password=password dbname=postgres user=postgres host=localhost port=5432' \ + --backend postgres-store \ + --s3 \ + --s3-bucket your-bucket-name \ + --s3-region ap-southeast-1 \ + --s3-access-key \ + --s3-secret-key +``` + +### 从本地文件导入 + +#### 导入到 PostgreSQL 后端 + +从本地备份文件恢复元数据到 PostgreSQL: + +```bash +greptime cli meta snapshot restore \ + --store-addrs 'password=password dbname=postgres user=postgres host=localhost port=5432' \ + --backend postgres-store +``` + +#### 导入到 MySQL 后端 + +从本地备份文件恢复元数据到 MySQL: + +```bash +greptime cli meta snapshot restore \ + --store-addrs 'mysql://user:password@127.0.0.1:3306/database' \ + --backend mysql-store +``` + +#### 导入到 etcd 后端 + +从本地备份文件恢复元数据到 etcd: + +```bash +greptime cli meta snapshot restore \ + --store-addrs 127.0.0.1:2379 \ + --backend etcd-store +``` \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-based-on-cross-region-deployment-in-single-cluster.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-based-on-cross-region-deployment-in-single-cluster.md new file mode 100644 index 0000000000..d509cbcf4b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-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-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-for-standalone.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-for-standalone.md new file mode 100644 index 0000000000..0bf03d6aac --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-for-standalone.md @@ -0,0 +1 @@ +# GreptimeDB Standalone 的 DR 方案 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/disaster-recovery/overview.md new file mode 100644 index 0000000000..d6cb277e71 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-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/deployments-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/deployments-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-1.0/user-guide/deployments-administration/maintenance/maintenance-mode.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/maintenance-mode.md new file mode 100644 index 0000000000..05dbaab817 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/maintenance-mode.md @@ -0,0 +1,111 @@ +--- +keywords: [GreptimeDB, 维护模式, metasrv, 集群管理, region 调度, 自动平衡, 故障转移, 升级, 维护] +description: 介绍如何管理 GreptimeDB 集群维护模式,以便在防止自动 region 调度和故障转移的同时安全地执行升级和维护等操作。 +--- + +# 集群维护模式 + +集群维护模式是 GreptimeDB 中的一个安全特性,用于临时禁止集群的自动调度操作。 + +该模式在以下情况下特别有用: +- 集群部署 +- 集群升级 +- 计划停机 +- 任何可能暂时影响集群稳定性的操作 + + +## 何时使用维护模式 + +### 使用 GreptimeDB Operator +如果你使用 GreptimeDB Operator 升级集群,你不需要手动启用维护模式。Operator 会自动处理。 + +### 不使用 GreptimeDB Operator +当不使用 GreptimeDB Operator 升级集群时,**在以下情况下必须手动启用 Metasrv 的维护模式**: +1. 部署新集群(在 metasrv 节点就绪后启用维护模式) +2. Datanode 节点滚动升级 +3. Metasrv 节点升级 +4. Frontend 节点升级 +5. 任何可能暂时影响节点可用性的操作 + +在集群部署/升级完成后,你可以停用维护模式。 + +## 维护模式的影响 + +当维护模式启用时: +- Region Balancer(如果启用)将暂停 +- Region Failover(如果启用)将暂停 +- 手动操作/迁移 Region 仍然可行 +- 集群读、写服务正常工作 +- 监控和指标收集继续运行 + +## 管理维护模式 +维护模式可以通过 Metasrv 的 HTTP 接口启用和禁用:`http://{METASRV}:{HTTP_PORT}/admin/maintenance/enable` 和 `http://{METASRV}:{HTTP_PORT}/admin/maintenance/disable`。请注意,此接口监听 Metasrv 的 `HTTP_PORT`,默认为 `4000`。 + +### 启用维护模式 + +:::danger +调用运维模式接口后,请务必检查接口返回的 HTTP 状态码为 200,并确认响应内容符合预期。如果出现异常或接口行为不符合预期,请谨慎操作,并避免继续执行集群升级等高风险操作。 +::: + +通过发送 POST 请求到 `/admin/maintenance/enable` 端点启用维护模式。 + +```bash +curl -X POST 'http://localhost:4000/admin/maintenance/enable' +``` + +预期输出: +```bash +{"enabled":true} +``` + +如果遇到任何问题或意外行为,请不要继续进行维护操作。 + +### 停用维护模式 + +:::danger +在关闭运维模式之前,必须确认**所有组件均已恢复至正常状态**。 +::: + +通过发送 POST 请求到 `/admin/maintenance/disable` 端点停用维护模式。 + +在停用维护模式之前: +1. 确保所有组件健康且正常运行 +2. 验证所有节点是否正确加入集群 + +```bash +curl -X POST 'http://localhost:4000/admin/maintenance/disable' +``` + +预期输出: +```bash +{"enabled":false} +``` + +### 检查维护模式状态 + +通过发送 GET 请求到 `/admin/maintenance/status` 端点检查维护模式状态。 + +```bash +curl -X GET http://localhost:4000/admin/maintenance/status +``` + +预期输出: +```bash +{"enabled":false} +``` + +## 故障排除 + +### 常见问题 + +1. **无法启用维护模式** + - 验证 Metasrv 是否正在运行且可访问 + - 检查你是否具有正确的权限 + - 确保 RPC 端口正确 + +### 最佳实践 + +1. 在操作前后始终验证维护模式状态 +2. 准备好回滚计划 +3. 监控集群健康状况 +4. 记录所有维护期间进行的更改 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/prevent-metadata-changes.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/prevent-metadata-changes.md new file mode 100644 index 0000000000..893c30b0c9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/prevent-metadata-changes.md @@ -0,0 +1,70 @@ +--- +keywords: [GreptimeDB, GreptimeDB 集群, 维护, 暂停元数据变更] +description: 管理 GreptimeDB 暂停元数据变更的指南,用于安全执行元数据备份等操作。 +--- + +# 防止元数据变更 + +要防止元数据变更,你可以暂停 Procedure Manager。此机制拒绝所有新 procedure(即新的元数据变更操作),同时允许现有 procedure 继续运行。 +一旦启用,Metasrv 将拒绝以下 procedure 操作(包括不限于): + +**DDL 操作:** +- 创建表 +- 删除表 +- 修改表 +- 创建数据库 +- 删除数据库 +- 创建视图 +- 创建 Flow +- 删除 Flow + +**Region 调度操作:** +- Region Migration +- Region Failover (如果启用) +- Region Balancer (如果启用) + +你在启用暂停元数据变更功能后尝试执行这些操作时,可能会看到错误消息。对于 Region 调度操作,你可以启用 [集群维护模式](/user-guide/deployments-administration/maintenance/maintenance-mode.md) 来临时暂时它们。 + +## 管理 Procedure Manager +Procedure Manager 可以通过 Metasrv 的 HTTP 接口暂停和恢复:`http://{METASRV}:{HTTP_PORT}/admin/procedure-manager/pause` 和 `http://{METASRV}:{HTTP_PORT}/admin/procedure-manager/resume`。请注意,此接口监听 Metasrv 的 `HTTP_PORT`,默认为 `4000`。 + +### 暂停 Procedure Manager + +通过向 `/admin/procedure-manager/pause` 端点发送 POST 请求来暂停 Procedure Manager。 + +```bash +curl -X POST 'http://localhost:4000/admin/procedure-manager/pause' +``` + +预期输出: +```bash +{"status":"paused"} +``` + +### 恢复 Procedure Manager + +通过向 `/admin/procedure-manager/resume` 端点发送 POST 请求来恢复 Procedure Manager。 + +```bash +curl -X POST 'http://localhost:4000/admin/procedure-manager/resume' +``` + +预期输出: +```bash +{"status":"running"} +``` + +### 检查 Procedure Manager 状态 + +通过向 `/admin/procedure-manager/status` 端点发送 GET 请求来检查 Procedure Manager 状态。 + +```bash +curl -X GET 'http://localhost:4000/admin/procedure-manager/status' +``` + +预期输出: +```bash +{"status":"running"} +``` + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/recovery-mode.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/recovery-mode.md new file mode 100644 index 0000000000..8ba1f16ee1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/recovery-mode.md @@ -0,0 +1,58 @@ +--- +keywords: [GreptimeDB, 恢复模式, metasrv, 集群管理, 数据恢复] +description: 介绍如何使用 GreptimeDB 集群恢复模式来解决 Datanode 启动失败问题,并从 region 数据丢失或损坏中恢复。 +--- + +# 集群恢复模式 + +恢复模式是 GreptimeDB 提供的一项安全机制,使开发者能够在集群出现故障时,手动将其恢复至正常状态。 + +## 何时使用恢复模式 + +恢复模式在 Datanode 启动失败时特别有用,通常是由于 "Empty region directory" 错误,这可能是由于: +- Datanode 数据损坏(缺少 Region 数据目录) +- 从元数据快照恢复集群 + +## 恢复模式管理 + +恢复模式可以通过 Metasrv 的 HTTP 接口启用和禁用:`http://{METASRV}:{HTTP_PORT}/admin/recovery/enable` 和 `http://{METASRV}:{HTTP_PORT}/admin/recovery/disable`。请注意,此接口监听 Metasrv 的 `HTTP_PORT`,默认为 `4000`。 + +### 启用恢复模式 + +通过发送 POST 请求到 `/admin/recovery/enable` 端点启用恢复模式。 + + +```bash +curl -X POST 'http://localhost:4000/admin/recovery/enable' +``` + +预期输出: +```bash +{"enabled":true} +``` + +### 禁用恢复模式 + +通过发送 POST 请求到 `/admin/recovery/disable` 端点禁用恢复模式。 + +```bash +curl -X POST 'http://localhost:4000/admin/recovery/disable' +``` + +预期输出: +```bash +{"enabled":false} +``` + +### 检查恢复模式状态 + +通过发送 GET 请求到 `/admin/recovery/status` 端点检查恢复模式状态。 + +```bash +curl -X GET 'http://localhost:4000/admin/recovery/status' +``` + +预期输出: +```bash +{"enabled":false} +``` \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/sequence-management.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/sequence-management.md new file mode 100644 index 0000000000..1aefe07f3b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/sequence-management.md @@ -0,0 +1,66 @@ +--- +keywords: [GreptimeDB, 资源标识维护, metasrv, 元数据, 维护, 待分配表 ID, 表 ID] +description: 介绍如何维护和更新 GreptimeDB 集群中的资源标识(ID),包括在元数据恢复后重置待分配表 ID。 +--- + +# 资源标识(ID)管理 + +资源标识(ID)管理主要用于在从[元数据备份](/user-guide/deployments-administration/manage-metadata/restore-backup.md)恢复集群时,手动设置资源标识(如表 ID)。这是因为备份文件可能未包含最新的`待分配表 ID`值,如果不及时重置,可能会导致资源冲突或数据不一致。 + +### 理解表 ID 及 待分配表 ID 的关系 + +在 GreptimeDB 中: +- **表 ID**:每个表都有一个唯一的数字标识符,用于数据库内部识别和管理表 +- **待分配表 ID(Next Table ID)**:系统预留的下一个可用的表 ID 值。当创建新表时,系统会自动分配这个 ID 给新表,然后将`待分配表 ID`递增 + +**举例说明:** +- 假设当前集群中已有表 ID 为 1001、1002、1003 的表 +- 此时`待分配表 ID`应该是 1004 +- 当创建新表时,系统分配 ID 1004 给新表,并将`待分配表 ID`更新为 1005 +- 如果从备份恢复时,`待分配表 ID`仍然是 1002,就会与现有表 ID 1002、1003 产生冲突(通常你会在 Datanode 启动时遇到 `Region 1024 is corrupted, reason: ` 的错误) + + +通常情况下,资源标识(ID)由数据库自动维护,无需人工干预。但在某些特殊场景下(如从元数据备份恢复集群,且备份后集群又创建了新表),备份中的`待分配表 ID`可能已经落后于实际集群状态,此时需要手动调整。 + +**如何判断是否需要手动设置`待分配表 ID`:** +1. 查询当前集群中所有表的 ID:`SELECT TABLE_ID FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_ID DESC LIMIT 1;` +2. 通过 API 获取当前的`待分配表 ID`(见下方接口说明) +3. 如果现有表 ID 的最大值大于等于当前的`待分配表 ID`,则需要手动设置`待分配表 ID`为一个更大的值。通常为现有表 ID 的最大值加 1。 + + +你可以通过 Metasrv 的 HTTP 接口获取或设置`待分配的表 ID`:`http://{METASRV}:{HTTP_PORT}/admin/sequence/table/next-id`(获取)和 `http://{METASRV}:{HTTP_PORT}/admin/sequence/table/set-next-id`(设置)。请注意,此接口监听 Metasrv 的 `HTTP_PORT`,默认为 `4000`。 + +### 设置待分配的表 ID + +要安全地更新`待分配的表 ID`,请按照以下步骤操作: + +1. **启用集群恢复模式** - 这可以防止在更新过程中创建新表。详情请参阅[集群恢复模式](/user-guide/deployments-administration/maintenance/recovery-mode.md)。 +2. **设置待分配的表 ID** - 通过 HTTP 接口设置`待分配的表 ID`。 +3. **重启 metasrv 节点** - 这确保新的`待分配的表 ID`被正确设置。 +4. **禁用集群恢复模式** - 恢复正常的集群操作。 + +通过发送 POST 请求到 `/admin/sequence/table/set-next-id` 端点设置`待分配的表 ID`: + +```bash +curl -X POST 'http://localhost:4000/admin/sequence/table/set-next-id' \ + -H 'Content-Type: application/json' \ + -d '{"next_table_id": 2048}' +``` + +预期输出(`next_table_id` 可能不同): + +```bash +{"next_table_id":2048} +``` + +### 获取待分配的表 ID + +```bash +curl -X GET 'http://localhost:4000/admin/sequence/table/next-id' +``` + +预期输出(`next_table_id` 可能不同): + +```bash +{"next_table_id":1254} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/table-reconciliation.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/table-reconciliation.md new file mode 100644 index 0000000000..59c43c87ae --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/maintenance/table-reconciliation.md @@ -0,0 +1,102 @@ +--- +keywords: [GreptimeDB, 表元数据协调, 元数据一致性, Metasrv, Datanode, 表元数据修复] +description: 了解 GreptimeDB 的表协调机制,该机制可检测并修复 Metasrv 和 Datanode 之间的元数据不一致问题。 +--- +# 表元数据修复 + +## 概述 + +在 GreptimeDB 分布式环境中,系统采用了分层的元数据管理架构: +- **Metasrv**:作为元数据管理层,负责维护集群中所有表的元信息 +- **Datanode**:负责实际的数据存储和查询执行,同时会持久化部分表元信息 + +在理想情况下,Metasrv 和 Datanode 的表元信息应该保持完全一致。但在实际生产环境中,从[元数据备份](/user-guide/deployments-administration/manage-metadata/restore-backup.md)恢复集群的操作可能会导致元数据不一致。 + +**Table Reconciliation** 是 GreptimeDB 提供的表元数据修复机制,用于: +- 检测 Metasrv 与 Datanode 之间的元信息差异 +- 根据预定义的策略修复不一致问题 +- 确保系统能够从异常状态恢复到一致、可用的状态 + +## 在开始之前 +在开始表元数据修复之前,你需要: +1. 从[元数据备份](/user-guide/deployments-administration/manage-metadata/restore-backup.md)中恢复集群 +2. 将[待分配表 ID](/user-guide/deployments-administration/maintenance/sequence-management.md) 设置为原集群的待分配表 ID + +## 修复场景 + +### `Table not found` 错误 + +当集群从特定元数据恢复后,写入和查询可能出现 `Table not found` 错误。 + +- **场景一**:原集群在备份元数据后新增了表,导致新增表的元数据没有包含在备份中,从而查询这些新增表时出现 `Table not found` 错误。这种情况下,新建表将丢失,同时你必须手动设置 [待分配表 ID](/user-guide/deployments-administration/maintenance/sequence-management.md),确保恢复后的集群在新创建表时不会因为表 ID 冲突导致创建失败。 + +- **场景二**:原集群在备份元数据后将原有表重命名,这种情况下新表名将丢失。 + +### `Empty region directory` 错误 + +当集群从特定元数据恢复后,启动 Datanode 时出现 `Empty region directory` 错误。这通常是因为原集群在备份元数据后删除了表(即执行 `DROP TABLE`),导致删除表的元数据没有包含在备份中,从而启动 Datanode 时出现该错误。针对这种情况,你需要在启动集群时,在 Metasrv 启动后开启 [Recovery Mode](/user-guide/deployments-administration/maintenance/recovery-mode.md),确保 Datanode 可以正常启动。 + +- **Mito Engine 表**:表元信息不可修复,需要手动执行 `DROP TABLE` 命令删除不存在的表。 +- **Metric Engine 表**:表元信息可以修复,需要手动执行 `ADMIN reconcile_table(table_name)` 命令修复表元信息。 + +### `No field named` 错误 + +当集群从特定元数据恢复后,写入和查询可能出现 `No field named` 错误。这通常是因为原集群在备份元数据后删除了列(即执行 `DROP COLUMN`),导致删除列的元数据没有包含在备份中,从而查询这些已删除列时出现该错误。针对这种情况,你需要手动执行 `ADMIN reconcile_table(table_name)` 命令修复表元信息。 + +### `schema has a different type` 错误 + +当集群从特定元数据恢复后,写入和查询可能出现 `schema has a different type` 错误。这通常是因为原集群在备份元数据后修改了列类型(即执行 `MODIFY COLUMN [column_name] [type]`),导致修改列类型的元数据没有包含在备份中,从而查询这些修改后的列时出现该错误。针对这种情况,你需要手动执行 `ADMIN reconcile_table(table_name)` 命令修复表元信息。 + +### 缺少特定列 + +当集群从特定元数据恢复后,写入和查询可能正常运行,但是未包含一些列。这是因为原集群在备份元数据后新增了列(即执行 `ADD COLUMN`),导致新增列的元数据未包含在备份中,从而查询时无法列出这些列。针对这种情况,你需要手动执行 `ADMIN reconcile_table(table_name)` 命令修复表元信息。 + +### 列缺少索引 + +当集群从特定元数据恢复后,写入和查询可能正常运行,但是 `SHOW CREATE TABLE`/`SHOW INDEX FROM [table_name]` 显示某些列未包含预期索引。这是因为原集群在备份元数据后修改了索引(即执行 `MODIFY INDEX [column_name] SET [index_type] INDEX`),导致索引变更后的元数据未包含在备份中。针对这种情况,你需要手动执行 `ADMIN reconcile_table(table_name)` 命令修复表元信息。 + +## 修复操作 + +GreptimeDB 提供了以下 Admin 函数用于触发表元数据修复: + +### 修复所有表 + +修复整个集群中所有表的元数据不一致问题: + +```sql +ADMIN reconcile_catalog() +``` + +### 修复指定数据库 + +修复指定数据库中所有表的元数据不一致问题: + +```sql +ADMIN reconcile_database(database_name) +``` + +### 修复指定表 + +修复单个表的元数据不一致问题: + +```sql +ADMIN reconcile_table(table_name) +``` + +### 查看修复进度 + +上述 Admin 函数执行后会返回一个 `ProcedureID`,你可以通过以下命令查看修复任务的执行进度: + +```sql +ADMIN procedure_state(procedure_id) +``` + +当 `procedure_state` 返回 Done 时,标识修复任务完成。 + +## 注意事项 + +在执行表元数据修复操作时,请注意以下几点: + +- 修复操作是异步执行的,可以通过 `procedure_id` 查看执行进度 +- 建议在业务低峰期执行修复操作,以减少对系统性能的影响 +- 对于大规模的修复操作(如 `reconcile_catalog()`),建议先在测试环境验证 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/basic-table-operations.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/basic-table-operations.md new file mode 100644 index 0000000000..5c60d0e630 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/basic-table-operations.md @@ -0,0 +1,359 @@ +--- +keywords: [pg, pgsql, 表操作, 创建表, 修改表, 删除表, 描述表] +description: 介绍 GreptimeDB 中表的基本操作,包括创建数据库和表、描述表、显示表定义和索引、列出现有表、修改表和删除表等内容。 +--- + +# 表的基本操作 + +在阅读本文档之前请先阅读 [数据模型](/user-guide/concepts/data-model.md). + +GreptimeDB 通过 SQL 提供了表管理的功能,下面通过 [MySQL Command-Line Client](https://dev.mysql.com/doc/refman/8.0/en/mysql.html) 来演示它。 + +以下部分更详细的关于 SQL 语法的解释,请参考 [SQL reference](/reference/sql/overview.md)。 + +## 创建数据库 + +默认的数据库是 `public`,可以手动创建一个数据库。 + +```sql +CREATE DATABASE test; +``` + +```sql +Query OK, 1 row affected (0.05 sec) +``` + +创建一个具有 7 天 `TTL`(数据存活时间)的数据库,也就是该数据库中的所有表如果没有单独设置 TTL 选项,都将继承此选项值。 + +```sql +CREATE DATABASE test WITH (ttl='7d'); +``` + +列出所有现有的数据库。 + +```sql +SHOW DATABASES; +``` + +```sql ++---------+ +| Schemas | ++---------+ +| test | +| public | ++---------+ +2 rows in set (0.00 sec) +``` + +使用 `like` 语法: + +```sql +SHOW DATABASES LIKE 'p%'; +``` + +```sql ++---------+ +| Schemas | ++---------+ +| public | ++---------+ +1 row in set (0.00 sec) +``` + +然后更改数据库: + +```sql +USE test; +``` + +更改回 `public` 数据库: + +```sql +USE public; +``` + +## 创建表 + +:::tip NOTE +注意:GreptimeDB 提供了一种 schemaless 方法来写入数据,不需要使用额外的协议手动创建表。参见 [自动生成表结构](/user-guide/ingest-data/overview.md#自动生成表结构)\*\*。 +::: + +如果您有特殊需要,仍然可以通过 SQL 手动创建表。假设我们想要创建一个名为 `monitor` 的表,其数据模型如下: + +- `host` 是独立机器的主机名,是 `Tag` 列,用于在查询时过滤数据。 +- `ts` 是收集数据的时间,是 `Timestamp` 列。它也可以在查询数据时用作时间范围的过滤器。 +- `cpu` 和 `memory` 是机器的 CPU 利用率和内存利用率,是包含实际数据且未索引的 `Field` 列。 + +创建表的 SQL 代码如下。在 SQL 中,我们使用 PRIMARY KEY 来指定 `Tag`,使用 `TIME INDEX` 来指定 `Timestamp` 列,其余列是 `Field`。 + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64 DEFAULT 0, + memory FLOAT64, + 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 目前不支持在创建表后更改 TIME INDEX 约束, +因此,在创建表之前,仔细选择适当的 TIME INDEX 列。 +::: + +### `CREATE TABLE` 语法 + +- 时间戳列:GreptimeDB 是一个时序数据库系统,在创建表时,必须用 `TIME INDEX` 关键字明确指定时间序列的列。 + 时间序列的列的数据类型必须是 `TIMESTAMP`。 +- 主键:`Primary key`指定的主键列类似于其他时序系统中的 Tag,比如 [InfluxDB][1]。主键和时间戳列用于唯一地定义一条时间线,这类似于其他时间序列系统中的时间线的概念,如 [InfluxDB][2]。 +- 表选项:当创建一个表时,可以指定一组表选项,点击[这里](/reference/sql/create.md#table-options)了解更多细节。 + +### 表名约束 + +GreptimeDB 支持在表名中使用有限的特殊字符,但必须遵守以下约束: +- 有效的 GreptimeDB 表名必须以字母(小写或大写)或 `-` / `_` / `:` 开头。 +- 表名的其余部分可以是字母数字或以下特殊字符:`-` / `_` / `:` / `@` / `#`。 +- 任何包含特殊字符的表名都必须用反引号括起来。 +- 任何包含大写字母的表名都必须用反引号括起来。 + +以下是有效和无效表名的例子: + +```sql +-- ✅ Ok +create table a (ts timestamp time index); + +-- ✅ Ok +create table a0 (ts timestamp time index); + +-- 🚫 Invalid table name +create table 0a (ts timestamp time index); + +-- 🚫 Invalid table name +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 +[2]: https://docs.influxdata.com/influxdb/v1/concepts/glossary/#series + +## 描述表 + +显示表的详细信息: + +```sql +DESC TABLE monitor; +``` + +```sql ++--------+----------------------+------+------+---------------------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------+----------------------+------+------+---------------------+---------------+ +| host | String | PRI | YES | | TAG | +| ts | TimestampMillisecond | PRI | NO | current_timestamp() | TIMESTAMP | +| cpu | Float64 | | YES | 0 | FIELD | +| memory | Float64 | | YES | | FIELD | ++--------+----------------------+------+------+---------------------+---------------+ +4 rows in set (0.01 sec) +``` + +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` 语句来列出现有的表 + +```sql +SHOW TABLES; +``` + +```sql ++------------+ +| Tables | ++------------+ +| monitor | +| scripts | ++------------+ +3 rows in set (0.00 sec) +``` + +注意:`scripts` 表是一个内置的表,用于存放用户定义的函数(UDF)。 + +其目前只支持表名的过滤,可以通过表名字对其进行过滤。 + +```sql +SHOW TABLES LIKE monitor; +``` + +```sql ++---------+ +| Tables | ++---------+ +| monitor | ++---------+ +1 row in set (0.00 sec) +``` + +列出其他数据库中的表: + +```sql +SHOW TABLES FROM test; +``` + +```sql ++---------+ +| Tables | ++---------+ +| monitor | ++---------+ +1 row in set (0.01 sec) +``` + +## 改动表 + +可以像在 MySQL 数据库中一样,改变现有表的模式 + +```sql +ALTER TABLE monitor ADD COLUMN label VARCHAR; +``` + +```sql +Query OK, 0 rows affected (0.03 sec) +``` + +```sql +ALTER TABLE monitor DROP COLUMN label; +``` + +```sql +Query OK, 0 rows affected (0.03 sec) +``` + +`ALTER TABLE` 语句还支持添加、删除、重命名列以及修改列的数据类型等更改。有关更多信息,请参阅[ALTER 参考指南](/reference/sql/alter.md)。 + +## 删除表 + +:::danger 危险操作 +表删除后不可撤销!请谨慎操作! +::: + +`DROP TABLE [db.]table` 用于删除 `db` 或当前正在使用的数据库中的表。 + +删除当前数据库中的表 `test`: + +```sql +DROP TABLE monitor; +``` + +```sql +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 方法创建一个表: + +```shell +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))' \ +http://localhost:4000/v1/sql?db=public +``` + +```json +{ "code": 0, "output": [{ "affectedrows": 1 }], "execution_time_ms": 10 } +``` + +关于 SQL HTTP 请求的更多信息,请参考 [API 文档](/user-guide/protocols/http.md#post-sql-语句)。 + +## 时区 + +SQL 客户端会话中指定的时区将影响创建或更改表时的默认时间戳值。 +如果将时间戳列的默认值设置为不带时区的字符串,则该默认值会被自动添加客户端的时区信息。 + +有关客户端时区的影响,请参考 [写入数据](/user-guide/ingest-data/for-iot/sql.md#时区) 文档中的时区部分。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/compaction.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/compaction.md new file mode 100644 index 0000000000..fd5f73a9cc --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/compaction.md @@ -0,0 +1,157 @@ +--- +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 周 + +如果未指定时间窗口大小,GreptimeDB 将使用 1 小时作为初始时间窗口并在第一次压缩时通过文件的时间分布推断窗口,通过从上述集合中选择**能够覆盖所有要压缩文件的整个时间跨度的**,**最小的**时间窗口作为时间窗口大小。 + +例如,在第一次压缩期间,所有输入 SST 文件的时间跨度为 4 小时,那么 GreptimeDB 将选择 12 小时作为该表的时间窗口,并将此参数持久化以便后续的压缩中使用。 + +### 有序组 +有序组(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 会基于合并开销来计算一个文件合并策略,从而将有序组的数量减少到 1。如果有序组的数量没有超过 1(也就是任意两个文件的时间范围都不重叠),TWCS 会检查是否存在过多的文件碎片,并在必要时合并这些碎片文件,因为 SST 文件数量也会影响查询性能。 + +对于窗口分配,SST 文件可能跨越多个时间窗口。为了确保不受陈旧数据影响,TWCS 根据 SST 的最大时间戳来进行分配。在时间序列工作负载中,无序写入很少发生,即使发生了,最近数据的查询性能也比陈旧数据更为重要。 + +TWCS 提供了 5 个参数供调整: +- `trigger_file_num`: 单一时间窗口中触发 compaction 的文件数量(默认为 4) +- `max_output_file_size`: compaction 产生文件的最大大小(默认无限制) + +以下图表显示了当 `trigger_file_num`为 3 时,窗口中的文件如何被压缩: +- 在 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 中的样子。 +- 在 E 中,一个新文件 `[11, 12]` 被写入。尽管仍然只有一个有序组,但文件数量达到了 `trigger_file_num`(3),因此将会把 `[5, 6, 9,10]` 与 `[11,12]` 合并形成 `[5,6,9,10,11,12 ]`. + +![compaction-trigger-file-num.png](/compaction-trigger-file-num.png) + +### 指定 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.trigger_file_num'='8', + '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 文件的窗口大小(以秒为单位) +- `parallelism` 参数用于控制压缩的并行度(默认为 1) + +例如,触发使用 1 小时窗口的压缩: + +```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 秒)的时间跨度拆分成多个分块,并将这些分块合并为一个输出文件,确保没有重叠的文件。 + +你还可以指定 `parallelism` 参数来通过并发处理多个文件以加速压缩: + +```sql +-- 使用默认时间窗口和并行度为 2 的 SWCS 压缩 +ADMIN COMPACT_TABLE("monitor", "swcs", "parallelism=2"); + +-- 使用自定义时间窗口和并行度的 SWCS 压缩 +ADMIN COMPACT_TABLE("monitor", "swcs", "window=1800,parallelism=2"); +``` + +`parallelism` 参数同样适用于常规压缩: + +```sql +-- 并行度为 2 的常规压缩 +ADMIN COMPACT_TABLE("monitor", "regular", "parallelism=2"); +``` + +下图展示了一次 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-1.0/user-guide/deployments-administration/manage-data/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/overview.md new file mode 100644 index 0000000000..859639fc4d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-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/deployments-administration/manage-data/region-failover.md) +* [Compaction](compaction.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/region-failover.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/region-failover.md new file mode 100644 index 0000000000..aaa9180bbe --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/region-failover.md @@ -0,0 +1,82 @@ +--- +keywords: [Region Failover, 故障恢复, 恢复时间, 共享存储, Kafka WAL] +description: 介绍 Region Failover 功能及其在 GreptimeDB 中的应用,包括开启 Region Failover、恢复时间和改进恢复时间的建议等内容。 +--- + +# Region Failover + +Region Failover 提供了在不丢失数据的情况下从 Region 故障中恢复的能力。这是通过 [Region 迁移](/user-guide/deployments-administration/manage-data/region-migration.md) 实现的。 + +## 开启 Region Failover + + +该功能仅在 GreptimeDB 集群模式下可用,并且需要满足以下条件 + +- 使用 Kafka WAL (Remote WAL) 或 Local WAL (在本地 WAL 上启用 Region Failover ,在 Failover 过程中可能会导致数据丢失) +- 使用[共享存储](/user-guide/deployments-administration/configuration.md#storage-options) (例如:AWS S3) + +如果想要在本地 WAL 上启用 Region Failover,需要设置 `allow_region_failover_on_local_wal=true` 在 [metasrv](/user-guide/deployments-administration/configuration.md#metasrv-only-configuration) 配置文件中。不建议启用此选项,因为它可能会导致数据丢失。 + +### 通过配置文件 + +在 [metasrv](/user-guide/deployments-administration/configuration.md#metasrv-only-configuration) 配置文件中设置 `enable_region_failover=true`. +另外,你还需要将 `region_failure_detector_initialization_delay` 设置为较大的值,并在 `region_failure_detector_initialization_delay` 期间内,启动[集群维护模式](/user-guide/deployments-administration/maintenance/maintenance-mode.md),以避免在 Datanode 启动或升级期间触发不必要的 Region Failover。 + +### 通过 GreptimeDB Operator + +要通过 GreptimeDB Operator 启用 Region Failover,可以参考 [常见 Helm Chart 配置项](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md#enable-region-failover) 了解更多详细信息。 + +## 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-administration/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-1.0/user-guide/deployments-administration/manage-data/region-migration.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/region-migration.md new file mode 100644 index 0000000000..f8010c9ede --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/region-migration.md @@ -0,0 +1,81 @@ +--- +keywords: [Region 迁移, 数据迁移, 负载均衡, 迁移请求, 迁移状态] +description: 介绍 Region 迁移功能及其在 GreptimeDB 中的应用,包括查询 Region 分布、选择迁移目标节点、发起迁移请求和查询迁移状态等内容。 +--- + +# Region Migration + +Region 迁移允许用户在 Datanode 间移动 Region 数据。 + +:::warning 注意 +该功能仅在 GreptimeDB 集群模式下可用,并且需要满足以下条件 +- 使用共享存储 (例如:AWS S3) + +无法在任何上述以外的情况下使用 Region 迁移。 +::: + + +## 查询 Region 分布 + +首先需要查询该数据表分区(Region)分布情况,即查询数据表中的 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='migration_target' order by datanode_id asc; +``` + +例如:有以下的 Region 分布 +```sql ++-------------+---------------+ +| datanode_id | region_id | ++-------------+---------------+ +| 1 | 4398046511104 | ++-------------+---------------+ +1 row in set (0.01 sec) +``` + + +更多关于 `region_peers` 表的信息,请阅读 [REGION-PEERS](/reference/sql/information-schema/region-peers.md)。 + +## 选择 Region 迁移的目标节点 +:::warning Warning +当起始节点等于目标节点时,Region 迁移不会被执行 +::: + +如果你通过 GreptimeDB operator 部署 DB 集群,Datanode 的 `peer_id` 总是从 0 开始递增。例如,DB 集群有 3 个 Datanode,则 `peer_id` 应为 0,1,2。 +最后,你可以通过以下 SQL 请求发起 Region 迁移请求: + +```sql +ADMIN migrate_region(4398046511104, 1, 2, 60); +``` + +`migrate_region` 参数说明: + +```sql +ADMIN migrate_region(region_id, from_peer_id, to_peer_id, replay_timeout); +``` + +| Option | Description | Required | | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------ | --- | +| `region_id` | Region Id | **Required** | | +| `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-1.0/user-guide/deployments-administration/manage-data/table-sharding.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/table-sharding.md new file mode 100644 index 0000000000..fa88ab6b79 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-data/table-sharding.md @@ -0,0 +1,198 @@ +--- +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 < 'South', + device_id < 100 AND area >= 'South', + device_id >= 100 AND area <= 'East', + device_id >= 100 AND area > 'East' +); +``` + +以下内容以具有两个分区列的 `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'); +``` + +:::tip NOTE +注意,当写入数据不满足分区规则中的任何规则时,数据将被分配到默认分区(即表的第一个分区 0)。 +::: + +## 分布式查询 + +只需使用 `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-1.0/user-guide/deployments-administration/manage-metadata/configuration.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/configuration.md new file mode 100644 index 0000000000..b29a4435bb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/configuration.md @@ -0,0 +1,164 @@ +--- +keywords: [GreptimeDB, 元数据存储, 配置, etcd, MySQL, PostgreSQL, metasrv, 存储后端设置] +description: GreptimeDB metasrv 组件中配置元数据存储后端(etcd、MySQL、PostgreSQL)的综合指南,包括设置说明和最佳实践。 +--- + +# 元数据存储配置 + +本节介绍如何为 GreptimeDB Metasrv 组件配置不同的元数据存储后端。元数据存储用于存储关键的系统信息,包括 catalog、schema、table、region 以及其他对 GreptimeDB 运行至关重要的元数据。 + +## 可用存储后端 + +GreptimeDB 支持以下元数据存储后端: + +- **etcd**:开发和测试环境的默认推荐后端,提供简单性和易用性 +- **MySQL/PostgreSQL**:适合生产环境的后端选择,能够无缝对接现有的数据库基础设施和云服务商提供的 RDS 服务 + +本文档描述的每种后端的 TOML 配置,适用于没有使用 Helm Chart 部署 GreptimeDB 的情况下。 +如果你使用 Helm Chart 部署 GreptimeDB,可以参考 [Common Helm Chart Configurations](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md#configuring-metasrv-backend-storage) 了解更多详情。 + +## 使用 etcd 作为元数据存储 + +虽然 etcd 适合开发和测试环境,但对于需要高可用性和可扩展性的生产环境来说可能并不是最佳选择。 + +配置 metasrv 组件使用 etcd 作为元数据存储: + +```toml +# metasrv 组件的元数据存储后端 +backend = "etcd_store" + +# 存储服务器地址 +# 可以指定多个 etcd 端点以实现高可用性 +store_addrs = ["127.0.0.1:2379"] + +[backend_tls] +# - "disable" - 不使用 TLS +# - "require" - 要求 TLS +mode = "prefer" + +# 客户端证书文件路径(用于客户端身份验证) +# 例如 "/path/to/client.crt" +cert_path = "" + +# 客户端私钥文件路径(用于客户端身份验证) +# 例如 "/path/to/client.key" +key_path = "" + +# CA 证书文件路径(用于服务器证书验证) +# 使用自定义 CA 或自签名证书时必需 +# 留空则仅使用系统根证书 +# 例如 "/path/to/ca.crt" +ca_cert_path = "" +``` + +### 最佳实践 + +虽然 etcd 可以用作元数据存储,但我们不建议在生产环境中使用它,除非你对 etcd 的操作和维护有丰富的经验。有关 etcd 管理的详细指南,包括安装、备份和维护程序,请参阅[管理 etcd](/user-guide/deployments-administration/manage-metadata/manage-etcd.md)。 + +使用 etcd 作为元数据存储时: + +- 在不同可用区部署多个端点以实现高可用性 +- 配置适当的自动压缩设置以管理存储增长 +- 实施定期维护程序: + - 定期运行 `Defrag` 命令以回收磁盘空间 + - 监控 etcd 集群健康指标 + - 根据使用模式审查和调整资源限制 + + +## 使用 MySQL 作为元数据存储 + +MySQL 可作为一种可行的元数据存储后端选项。特别是在需要与现有 MySQL 基础设施集成,或存在特定 MySQL 相关需求的场景下,这一选择尤为适用。对于生产环境部署,我们强烈建议使用各大云服务商提供的关系型数据库服务(RDS),以获得更高的可靠性和托管服务带来的便利。 + +配置 metasrv 组件以使用 MySQL 作为元数据存储: + +```toml +# metasrv 组件的元数据存储后端 +backend = "mysql_store" + +# 存储服务器地址 +# 格式:mysql://user:password@ip:port/dbname +store_addrs = ["mysql://user:password@ip:port/dbname"] + +# 可选:自定义元数据存储表名 +# 默认值: greptime_metakv +meta_table_name = "greptime_metakv" + +[backend_tls] +# - "disable" - 不使用 TLS +# - "prefer" (默认) - 尝试 TLS,失败时回退到明文连接 +# - "require" - 要求 TLS +# - "verify_ca" - 要求 TLS 并验证 CA +# - "verify_full" - 要求 TLS 并验证主机名 +mode = "prefer" + +# 客户端证书文件路径(用于客户端身份验证) +# 例如 "/path/to/client.crt" +cert_path = "" + +# 客户端私钥文件路径(用于客户端身份验证) +# 例如 "/path/to/client.key" +key_path = "" + +# CA 证书文件路径(用于服务器证书验证) +# 使用自定义 CA 或自签名证书时必需 +# 留空则仅使用系统根证书 +# 例如 "/path/to/ca.crt" +ca_cert_path = "" +``` + +当多个 GreptimeDB 集群共享同一个 MySQL 实例时,必须为每个 GreptimeDB 集群设置一个唯一的 `meta_table_name` 以避免元数据冲突。 + +## 使用 PostgreSQL 作为元数据存储 + +PostgreSQL 可作为一种可行的元数据存储后端选项。特别是在需要与现有 PostgreSQL 基础设施集成,或存在特定 PostgreSQL 相关需求的场景下,这一选择尤为适用。对于生产环境部署,我们强烈建议使用各大云服务商提供的关系型数据库服务(RDS),以获得更高的可靠性和托管服务带来的便利。 + +配置 metasrv 组件以使用 PostgreSQL 作为元数据存储: + +```toml +# metasrv 组件的元数据存储后端 +backend = "postgres_store" + +# 存储服务器地址 +# 格式: password=password dbname=postgres user=postgres host=localhost port=5432 +store_addrs = ["password=password dbname=postgres user=postgres host=localhost port=5432"] + +# 可选:自定义元数据存储表名 +# 默认值: greptime_metakv +meta_table_name = "greptime_metakv" + +# 可选: 用于选举的 Advisory lock ID +# 默认值: 1 +meta_election_lock_id = 1 + +# 可选:PostgreSQL schema,用于元数据表和选举表名称限定。 +# 在 PostgreSQL 15 及更高版本中,默认的 public schema 通常被限制写入权限, +# 非超级用户无法在 public schema 中创建表。 +# 当遇到权限限制时,可通过此参数指定一个具有写入权限的 schema。 +meta_schema_name = "greptime_schema" + +[backend_tls] +# - "disable" - 不使用 TLS +# - "prefer" (默认) - 尝试 TLS,失败时回退到明文连接 +# - "require" - 要求 TLS +# - "verify_ca" - 要求 TLS 并验证 CA +# - "verify_full" - 要求 TLS 并验证主机名 +mode = "prefer" + +# 客户端证书文件路径(用于客户端身份验证) +# 例如 "/path/to/client.crt" +cert_path = "" + +# 客户端私钥文件路径(用于客户端身份验证) +# 例如 "/path/to/client.key" +key_path = "" + +# CA 证书文件路径(用于服务器证书验证) +# 使用自定义 CA 或自签名证书时必需 +# 留空则仅使用系统根证书 +# 例如 "/path/to/ca.crt" +ca_cert_path = "" +``` +当多个 GreptimeDB 集群共享同一个 PostgreSQL 实例或与其他应用程序共享时,必须配置两个唯一标识符以防止冲突: + +1. 为每个 GreptimeDB 集群设置唯一的 `meta_table_name` 以避免元数据冲突 +2. 为每个 GreptimeDB 集群分配唯一的 `meta_election_lock_id` 以防止与使用同一 PostgreSQL 实例的其他应用程序发生 advisory lock 冲突 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/manage-etcd.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/manage-etcd.md new file mode 100644 index 0000000000..2d405d0519 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/manage-etcd.md @@ -0,0 +1,548 @@ +--- +keywords: [etcd, kubernetes, helm, 备份, 恢复] +description: 管理 etcd 集群的综合指南,包括使用 kubernetes 和 helm 的安装、备份和恢复过程。 +--- + +# 管理 etcd + +GreptimeDB 集群默认需要一个 etcd 集群用于[元数据存储](https://docs.greptime.com/nightly/contributor-guide/metasrv/overview)。让我们使用 Bitnami 的 etcd Helm [chart](https://github.com/bitnami/charts/tree/main/bitnami/etcd) 安装一个 etcd 集群。 + +## 先决条件 + +- [Kubernetes](https://kubernetes.io/docs/setup/) >= v1.23 +- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) >= v1.18.0 +- [Helm](https://helm.sh/docs/intro/install/) >= v3.0.0 + +## 安装 + +将以下配置保存为文件 `etcd.yaml`: + +```yaml +global: + security: + allowInsecureImages: true + +image: + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + repository: bitnami/etcd + tag: VAR::etcdImageVersion + +replicaCount: 3 + +auth: + rbac: + create: false + token: + enabled: false + +persistence: + storageClass: null + size: 8Gi + +resources: + limits: + cpu: '2' + memory: 8Gi + requests: + cpu: '2' + memory: 8Gi + +autoCompactionMode: "periodic" +autoCompactionRetention: "1h" + +extraEnvVars: + - name: ETCD_QUOTA_BACKEND_BYTES + value: "8589934592" + - name: ETCD_ELECTION_TIMEOUT + value: "2000" + - name: ETCD_SNAPSHOT_COUNT + value: "10000" +``` + +安装 etcd 集群: + +```bash +helm upgrade \ + --install etcd oci://greptime-registry.cn-hangzhou.cr.aliyuncs.com/charts/etcd \ + --create-namespace \ + --version VAR::etcdChartVersion \ + -n etcd-cluster \ + --values etcd.yaml +``` + +等待 etcd 集群运行: + +```bash +kubectl get pod -n etcd-cluster +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +etcd-0 1/1 Running 0 64s +etcd-1 1/1 Running 0 65s +etcd-2 1/1 Running 0 72s +``` +
+ +等待 etcd 集群运行完毕,使用以下命令检查 etcd 集群的健康状态: + +```bash +kubectl -n etcd-cluster \ + exec etcd-0 -- etcdctl \ + --endpoints etcd-0.etcd-headless.etcd-cluster:2379,etcd-1.etcd-headless.etcd-cluster:2379,etcd-2.etcd-headless.etcd-cluster:2379 \ + endpoint status -w table +``` + +
+ Expected Output +```bash ++----------------------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+ +| ENDPOINT | ID | VERSION | DB SIZE | IS LEADER | IS LEARNER | RAFT TERM | RAFT INDEX | RAFT APPLIED INDEX | ERRORS | ++----------------------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+ +| etcd-0.etcd-headless.etcd-cluster:2379 | 680910587385ae31 | 3.5.15 | 20 kB | false | false | 4 | 73991 | 73991 | | +| etcd-1.etcd-headless.etcd-cluster:2379 | d6980d56f5e3d817 | 3.5.15 | 20 kB | false | false | 4 | 73991 | 73991 | | +| etcd-2.etcd-headless.etcd-cluster:2379 | 12664fc67659db0a | 3.5.15 | 20 kB | true | false | 4 | 73991 | 73991 | | ++----------------------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+ +``` +
+ +## 备份 + +在 bitnami etcd chart 中,使用共享存储卷 Network File System (NFS) 存储 etcd 备份数据。通过 Kubernetes 中的 CronJob 进行 etcd 快照备份,并挂载 NFS PersistentVolumeClaim (PVC),可以将快照传输到 NFS 中。 + +添加以下配置,并将其命名为 `etcd-backup.yaml` 文件,注意需要将 **existingClaim** 修改为你的 NFS PVC 名称: + +```yaml +global: + security: + allowInsecureImages: true + +image: + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + repository: bitnami/etcd + tag: VAR::etcdImageVersion + +replicaCount: 3 + +auth: + rbac: + create: false + token: + enabled: false + +persistence: + storageClass: null + size: 8Gi + +resources: + limits: + cpu: '2' + memory: 8Gi + requests: + cpu: '2' + memory: 8Gi + +autoCompactionMode: "periodic" +autoCompactionRetention: "1h" + +extraEnvVars: + - name: ETCD_QUOTA_BACKEND_BYTES + value: "8589934592" + - name: ETCD_ELECTION_TIMEOUT + value: "2000" + - name: ETCD_SNAPSHOT_COUNT + value: "10000" + +# Backup settings +disasterRecovery: + enabled: true + cronjob: + schedule: "*/30 * * * *" + historyLimit: 2 + snapshotHistoryLimit: 2 + pvc: + existingClaim: "${YOUR_NFS_PVC_NAME_HERE}" +``` + +重新部署 etcd 集群: + +```bash +helm upgrade \ + --install etcd oci://greptime-registry.cn-hangzhou.cr.aliyuncs.com/charts/etcd \ + --create-namespace \ + --version VAR::etcdChartVersion \ + -n etcd-cluster \ + --values etcd-backup.yaml +``` + +你可以看到 etcd 备份计划任务: + +```bash +kubectl get cronjob -n etcd-cluster +``` + +
+ Expected Output +```bash +NAME SCHEDULE TIMEZONE SUSPEND ACTIVE LAST SCHEDULE AGE +etcd-snapshotter */30 * * * * False 0 36s +``` +
+ +```bash +kubectl get pod -n etcd-cluster +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +etcd-0 1/1 Running 0 35m +etcd-1 1/1 Running 0 36m +etcd-2 0/1 Running 0 6m28s +etcd-snapshotter-28936038-tsck8 0/1 Completed 0 4m49s +``` +
+ +```bash +kubectl logs etcd-snapshotter-28936038-tsck8 -n etcd-cluster +``` + +
+ Expected Output +```log +etcd-0.etcd-headless.etcd-cluster.svc.cluster.local:2379 is healthy: successfully committed proposal: took = 2.698457ms +etcd 11:18:07.47 INFO ==> Snapshotting the keyspace +{"level":"info","ts":"2025-01-06T11:18:07.579095Z","caller":"snapshot/v3_snapshot.go:65","msg":"created temporary db file","path":"/snapshots/db-2025-01-06_11-18.part"} +{"level":"info","ts":"2025-01-06T11:18:07.580335Z","logger":"client","caller":"v3@v3.5.15/maintenance.go:212","msg":"opened snapshot stream; downloading"} +{"level":"info","ts":"2025-01-06T11:18:07.580359Z","caller":"snapshot/v3_snapshot.go:73","msg":"fetching snapshot","endpoint":"etcd-0.etcd-headless.etcd-cluster.svc.cluster.local:2379"} +{"level":"info","ts":"2025-01-06T11:18:07.582124Z","logger":"client","caller":"v3@v3.5.15/maintenance.go:220","msg":"completed snapshot read; closing"} +{"level":"info","ts":"2025-01-06T11:18:07.582688Z","caller":"snapshot/v3_snapshot.go:88","msg":"fetched snapshot","endpoint":"etcd-0.etcd-headless.etcd-cluster.svc.cluster.local:2379","size":"20 kB","took":"now"} +{"level":"info","ts":"2025-01-06T11:18:07.583008Z","caller":"snapshot/v3_snapshot.go:97","msg":"saved","path":"/snapshots/db-2025-01-06_11-18"} +Snapshot saved at /snapshots/db-2025-01-06_11-18 +``` +
+ +接下来,可以在 NFS 服务器中看到 etcd 备份快照: + +```bash +ls ${NFS_SERVER_DIRECTORY} +``` + +
+ Expected Output +```bash +db-2025-01-06_11-18 db-2025-01-06_11-20 db-2025-01-06_11-22 +``` +
+ +## 恢复 + +当您遇到 etcd 数据丢失或损坏(例如,存储在 etcd 中的关键信息被意外删除,或者发生无法恢复的灾难性集群故障)时,您需要执行 etcd 恢复。此外,恢复 etcd 还可用于开发和测试目的。 + +恢复前需要停止向 etcd 集群写入数据(停止 GreptimeDB Metasrv 对 etcd 的写入),并创建最新的快照文件用于恢复。 + +添加以下配置文件,命名为 `etcd-restore.yaml`。注意,**existingClaim** 是你的 NFS PVC 的名字,**snapshotFilename** 为 etcd 快照文件名: + +```yaml +global: + security: + allowInsecureImages: true + +image: + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + repository: bitnami/etcd + tag: VAR::etcdImageVersion + +replicaCount: 3 + +auth: + rbac: + create: false + token: + enabled: false + +persistence: + storageClass: null + size: 8Gi + +resources: + limits: + cpu: '2' + memory: 8Gi + requests: + cpu: '2' + memory: 8Gi + +autoCompactionMode: "periodic" +autoCompactionRetention: "1h" + +extraEnvVars: + - name: ETCD_QUOTA_BACKEND_BYTES + value: "8589934592" + - name: ETCD_ELECTION_TIMEOUT + value: "2000" + - name: ETCD_SNAPSHOT_COUNT + value: "10000" + +# Restore settings +startFromSnapshot: + enabled: true + existingClaim: "${YOUR_NFS_PVC_NAME_HERE}" + snapshotFilename: "${YOUR_ETCD_SNAPSHOT_FILE_NAME}" +``` + +部署 etcd 恢复集群: + +```bash +helm upgrade \ + --install etcd-recover oci://greptime-registry.cn-hangzhou.cr.aliyuncs.com/charts/etcd \ + --create-namespace \ + --version VAR::etcdChartVersion \ + -n etcd-cluster \ + --values etcd-restore.yaml +``` + +等待 etcd 恢复集群运行: + +```bash +kubectl get pod -n etcd-cluster -l app.kubernetes.io/instance=etcd-recover +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +etcd-recover-0 1/1 Running 0 91s +etcd-recover-1 1/1 Running 0 91s +etcd-recover-2 1/1 Running 0 91s +``` +
+ +:::tip NOTE +chart 版本之间的配置结构已发生变化: + +- 旧版本: `meta.etcdEndpoints` +- 新版本: `meta.backendStorage.etcd.endpoints` + +请参考 chart 仓库中配置 [values.yaml](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-cluster/values.yaml) 以获取最新的结构。 +::: + +接着,将 Metasrv 的 [backendStorage.etcd.endpoints](https://github.com/GreptimeTeam/helm-charts/tree/main/charts/greptimedb-cluster) 改成新的 etcd recover 集群,本例中为 `"etcd-recover.etcd-cluster.svc.cluster.local:2379"`: + +```yaml +apiVersion: greptime.io/v1alpha1 +kind: GreptimeDBCluster +metadata: + name: greptimedb +spec: + # 其他配置 + meta: + backendStorage: + etcd: + endpoints: + - "etcd-recover.etcd-cluster.svc.cluster.local:2379" +``` + +然后重启 GreptimeDB Metasrv 完成 etcd 恢复。 + +## Monitoring + +- 安装 Prometheus Operator (例如: [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack)). +- 安装 podmonitor CRD. + +将以下配置保存为文件 `etcd-monitoring.yaml`: + +```yaml +global: + security: + allowInsecureImages: true + +image: + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + repository: bitnami/etcd + tag: VAR::etcdImageVersion + +replicaCount: 3 + +auth: + rbac: + create: false + token: + enabled: false + +persistence: + storageClass: null + size: 8Gi + +resources: + limits: + cpu: '2' + memory: 8Gi + requests: + cpu: '2' + memory: 8Gi + +autoCompactionMode: "periodic" +autoCompactionRetention: "1h" + +extraEnvVars: + - name: ETCD_QUOTA_BACKEND_BYTES + value: "8589934592" + - name: ETCD_ELECTION_TIMEOUT + value: "2000" + - name: ETCD_SNAPSHOT_COUNT + value: "10000" + +# Monitoring settings +metrics: + enabled: true + podMonitor: + enabled: true + namespace: etcd-cluster + interval: 10s + scrapeTimeout: 10s + additionalLabels: + release: prometheus +``` + +部署并监控 etcd: + +```bash +helm upgrade \ + --install etcd oci://greptime-registry.cn-hangzhou.cr.aliyuncs.com/charts/etcd \ + --create-namespace \ + --version VAR::etcdChartVersion \ + -n etcd-cluster \ + --values etcd-monitoring.yaml +``` + +### Grafana dashboard + +使用 [ETCD Cluster Overview dashboard](https://grafana.com/grafana/dashboards/15308-etcd-cluster-overview/) (ID: 15308) 来监控 etcd 的指标. + +1. 登录你的 Grafana. +2. 导航至 Dashboards -> New -> Import. +3. 输入 Dashboard ID: 15308, 选择数据源并加载图表. + +![ETCD Cluster Overview dashboard](/etcd-cluster-overview-dashboard.png) + +## ⚠️ Defrag - Critical Warning + +Defrag 是一项高风险操作,可能会严重影响您的 ETCD 集群及其依赖系统(例如 GreptimeDB): + +1. 执行期间会阻止所有读/写操作(集群将不可用)。 +2. 高 I/O 使用率可能导致客户端应用程序超时。 +3. 如果碎片整理耗时过长,可能会触发领导者选举。 +4. 如果资源分配不当,可能会导致 OOM 终止。 +5. 如果在过程中中断,可能会损坏数据。 + +ETCD 使用多版本并发控制 (MVCC) 机制,用于存储多个版本的 KV。随着时间的推移,随着数据的更新和删除,后端数据库可能会变得碎片化,从而增加存储空间并降低性能。Defrag 是指压缩这些存储空间以回收空间并提高性能的过程。 + +在 `etcd-defrag.yaml` 文件中添加以下与 defrag 相关的配置: + +```yaml +global: + security: + allowInsecureImages: true + +image: + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + repository: bitnami/etcd + tag: VAR::etcdImageVersion + +replicaCount: 3 + +auth: + rbac: + create: false + token: + enabled: false + +persistence: + storageClass: null + size: 8Gi + +resources: + limits: + cpu: '2' + memory: 8Gi + requests: + cpu: '2' + memory: 8Gi + +autoCompactionMode: "periodic" +autoCompactionRetention: "1h" + +extraEnvVars: + - name: ETCD_QUOTA_BACKEND_BYTES + value: "8589934592" + - name: ETCD_ELECTION_TIMEOUT + value: "2000" + - name: ETCD_SNAPSHOT_COUNT + value: "10000" + +# Defragmentation settings +defrag: + enabled: true + cronjob: + schedule: "0 3 * * *" # Daily at 3:00 AM + suspend: false + successfulJobsHistoryLimit: 1 + failedJobsHistoryLimit: 1 +``` + +部署 etcd 集群并开启 defrag 功能: + +```bash +helm upgrade \ + --install etcd oci://greptime-registry.cn-hangzhou.cr.aliyuncs.com/charts/etcd \ + --create-namespace \ + --version VAR::etcdChartVersion \ + -n etcd-cluster \ + --values etcd-defrag.yaml +``` + +你可以看到 etcd defrag 定时任务: + +```bash +kubectl get cronjob -n etcd-cluster +``` + +
+ Expected Output +```bash +NAME SCHEDULE TIMEZONE SUSPEND ACTIVE LAST SCHEDULE AGE +etcd-defrag 0 3 * * * False 0 34s +``` +
+ +```bash +kubectl get pod -n etcd-cluster +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +etcd-0 1/1 Running 0 4m30s +etcd-1 1/1 Running 0 4m29s +etcd-2 1/1 Running 0 4m29s +etcd-defrag-29128518-sstbf 0/1 Completed 0 90s +``` +
+ +```bash +kubectl logs etcd-defrag-29128518-sstbf -n etcd-cluster +``` + +
+ Expected Output +```log +Finished defragmenting etcd member[http://etcd-0.etcd-headless.etcd-cluster.svc.cluster.local:2379] +Finished defragmenting etcd member[http://etcd-1.etcd-headless.etcd-cluster.svc.cluster.local:2379] +Finished defragmenting etcd member[http://etcd-2.etcd-headless.etcd-cluster.svc.cluster.local:2379] +``` +
diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/overview.md new file mode 100644 index 0000000000..6bfabe5948 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/overview.md @@ -0,0 +1,34 @@ +--- + keywords: [GreptimeDB, 元数据存储, etcd, MySQL, PostgreSQL, 配置] + description: GreptimeDB 元数据存储选项概述,包括 etcd、MySQL 和 PostgreSQL,以及生产环境部署建议。 +--- + +# 概述 + +GreptimeDB 集群 Metasrv 组件需要一个元数据存储来保存元数据。GreptimeDB 提供了灵活的元数据存储选项,包括 [etcd](https://etcd.io/)、[MySQL](https://www.mysql.com/) 和 [PostgreSQL](https://www.postgresql.org/)。每种选项都针对不同的部署场景设计,在可扩展性、可靠性和运维开销之间取得平衡。 + +- [etcd](https://etcd.io/):一个轻量级的分布式键值存储,非常适合元数据管理。其简单性和易于设置的特点使其成为开发和测试环境的绝佳选择。 +- [MySQL](https://www.mysql.com/) 和 [PostgreSQL](https://www.postgresql.org/):企业级关系型数据库,提供强大的元数据存储能力。它们提供包括 ACID 事务、复制和全面的备份解决方案在内的基本功能,使其成为生产环境的理想选择。这两种数据库在各大云平台上都广泛提供托管数据库服务(RDS)。 + +## 推荐方案 + +对于测试和开发环境,[etcd](https://etcd.io/) 提供了一个轻量级且简单的元数据存储解决方案。 + +**对于生产环境部署,我们强烈建议使用云服务商提供的关系型数据库服务(RDS)作为元数据存储。** 这种方式具有以下优势: + +- 托管服务内置高可用性和灾难恢复能力 +- 自动化的备份和维护 +- 专业的监控和支持 +- 相比自托管解决方案,降低了运维复杂度 +- 与其他云服务无缝集成 + +## 最佳实践 + +- 为元数据存储实施定期备份计划 +- 建立全面的存储健康状态和性能指标监控 +- 制定清晰的灾难恢复流程 +- 记录元数据存储配置和维护程序 + +## 后续步骤 +- 要配置元数据存储后端,请参阅[配置](/user-guide/deployments-administration/manage-metadata/configuration.md)。 +- 要为测试和开发环境设置 etcd,请参阅[管理 etcd](/user-guide/deployments-administration/manage-metadata/manage-etcd.md)。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/restore-backup.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/restore-backup.md new file mode 100644 index 0000000000..84c5465c49 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/manage-metadata/restore-backup.md @@ -0,0 +1,37 @@ +--- + keywords: [GreptimeDB, 元数据备份, 恢复, 迁移, etcd, MySQL, PostgreSQL, 灾难恢复] + description: 介绍如何在不同的存储后端(etcd、MySQL、PostgreSQL)之间备份、恢复和迁移 GreptimeDB 元数据,以及确保数据一致性的最佳实践。 +--- + +# 备份、恢复和迁移 + +GreptimeDB 通过其 CLI 工具提供元数据备份和恢复功能。该功能支持所有主要的元数据存储后端,包括 etcd、MySQL 和 PostgreSQL。有关使用这些功能的详细说明,请参阅[备份和恢复](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md)指南。 + +## 备份 + +为了获得最佳的备份可靠性,建议在 DDL(数据定义语言)操作(即建表、删表、修改表结构等)较少的时段进行元数据备份。这有助于确保数据一致性,并降低部分或不完整备份的风险。 + +执行备份的步骤: + +1. 确认 GreptimeDB 集群处于正常运行状态 +2. 使用 CLI 工具执行备份,按照[备份和恢复](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md)指南中的导出元数据步骤操作 +3. 确保备份输出文件已创建,且文件大小大于 0 + +## 恢复 + +从备份恢复的步骤: + +1. 使用 CLI 工具恢复元数据,按照[备份和恢复](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md)指南中的导入元数据步骤操作 +2. 重启 GreptimeDB 集群以应用恢复的元数据 +3. 将[待分配表 ID](/user-guide/deployments-administration/maintenance/sequence-management.md) 设置为原集群的待分配表 ID +4. 调用[表元数据修复](/user-guide/deployments-administration/maintenance/table-reconciliation.md)函数,修复表元数据不一致问题 + +## 迁移 + +我们建议在 DDL(数据定义语言)操作(即建表、删表、修改表结构等)较少的时段进行元数据迁移,以确保数据一致性并降低部分或不完整迁移的风险。 + +将元数据从一个存储后端迁移到另一个存储后端的步骤: + +1. 从源存储备份元数据 +2. 将元数据恢复到目标存储 +3. 重启整个 GreptimeDB 集群(所有组件)以应用恢复的元数据 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/check-db-status.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/check-db-status.md new file mode 100644 index 0000000000..7a38490be7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/check-db-status.md @@ -0,0 +1,49 @@ +--- +keywords: [GreptimeDB 健康检查, GreptimeDB 运行状态, GreptimeDB 部署状态, GreptimeDB 运行指标] +description: 通过 HTTP 接口检查 GreptimeDB 的健康状态、部署状态和运行指标。 +--- + +# 检查 GreptimeDB 状态 + +GreptimeDB 包含了一系列的 HTTP 接口可供查询 GreptimeDB 的运行情况。 +以下发起的 HTTP 请求均假定 GreptimeDB 运行在节点 `127.0.0.1` 上,其 HTTP 服务监听默认的 `4000` 端口。 + +## 查看 GreptimeDB 是否正常运行: + +你可以使用 `/health` 接口检查 GreptimeDB 是否正常运行。 +HTTP 状态码 `200 OK` 表示 GreptimeDB 运行正常。 + +例子: + +```bash +curl -i -X GET http://127.0.0.1:4000/health +HTTP/1.1 200 OK +content-type: application/json +content-length: 2 +date: Tue, 31 Dec 2024 02:15:22 GMT + +{} +``` + +有关健康检查接口的更多信息,请参考[健康检查接口](/reference/http-endpoints.md#健康检查)。 + +## 查看 GreptimeDB 的部署状态 + +你可以使用 `/status` 接口检查 GreptimeDB 的部署状态。 + +```bash +curl -X GET http://127.0.0.1:4000/status | jq + +{ + "source_time": "2024-12-27T07:57:47Z", + "commit": "b4bd34c530d62b95346a26a9470c03b9f6fb15c8", + "branch": "main", + "rustc_version": "rustc 1.84.0-nightly (e92993dbb 2024-10-18)", + "hostname": "127.0.0.1", + "version": "0.12.0" +} +``` + +有关状态接口的更多信息,请参考[状态接口](/reference/http-endpoints.md#状态)。 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/cluster-monitoring-deployment.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/cluster-monitoring-deployment.md new file mode 100644 index 0000000000..b8569f4552 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/cluster-monitoring-deployment.md @@ -0,0 +1,322 @@ +--- +keywords: [Kubernetes 部署, 集群, 监控] +description: 在 Kubernetes 上部署 GreptimeDB 集群的自监控完整指南,包括 Grafana 仪表盘设置和配置项。 +--- + +# 自监控 GreptimeDB 集群 + +在阅读本文档前,请确保你已经了解如何[在 Kubernetes 上部署 GreptimeDB 集群](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md)。 +本文将介绍在部署 GreptimeDB 集群时如何配置监控。 + +## 快速开始 + +你可以在使用 Helm Chart 部署 GreptimeDB 集群时,通过对 `values.yaml` 文件进行配置来启用监控和 Grafana。下面是一个完整的 `values.yaml` 示例,用于部署一个最小化的带有监控和 Grafana 的 GreptimeDB 集群: + +```yaml +image: + registry: docker.io + # 镜像仓库: + # OSS GreptimeDB 使用 `greptime/greptimedb`, + # GreptimeDB 企业版配置请咨询工作人员 + repository: + # 镜像标签: + # OSS GreptimeDB 使用数据库版本,例如 `VAR::greptimedbVersion` + # GreptimeDB 企业版配置请咨询工作人员 + tag: + pullSecrets: [] + +initializer: + registry: docker.io + repository: greptime/greptimedb-initializer + +monitoring: + # 启用监控 + enabled: true + +grafana: + # 用于监控面板 + # 需要先启用监控 `monitoring.enabled: true` 选项 + enabled: true + +frontend: + replicas: 1 + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + +datanode: + replicas: 1 +``` + +:::note 备注 +如果你在中国大陆遇到网络访问问题,可直接使用阿里云 OCI 镜像仓库: + +```yaml +image: + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + # 镜像仓库: + # OSS GreptimeDB 使用 `greptime/greptimedb`, + # GreptimeDB 企业版配置请咨询工作人员 + repository: + # 镜像标签: + # OSS GreptimeDB 使用数据库版本,例如 `VAR::greptimedbVersion` + # GreptimeDB 企业版配置请咨询工作人员 + tag: + pullSecrets: [] + +initializer: + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + repository: greptime/greptimedb-initializer + +monitoring: + # 启用监控 + enabled: true + vector: + # 监控需要使用 Vector + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + +grafana: + # 用于监控面板 + # 需要先启用监控 `monitoring.enabled: true` 选项 + enabled: true + image: + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + +frontend: + replicas: 1 + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + +datanode: + replicas: 1 +``` +::: + +当启用 `monitoring` 后,GreptimeDB Operator 会额外启动一个 GreptimeDB Standalone 实例用于收集 GreptimeDB 集群的指标和日志数据。 +为了收集日志数据,GreptimeDB Operator 会在每一个 Pod 中启动一个 [Vector](https://vector.dev/) 的 Sidecar 容器。 + +当启用 `grafana` 后,会部署一个 Grafana 实例,并将用于集群监控的 GreptimeDB Standalone 实例作为其数据源。 +这样就可以开箱即用地通过 Prometheus 和 MySQL 协议来可视化 GreptimeDB 集群的监控数据。 + +接下来使用上述配置的 `values.yaml` 文件来部署 GreptimeDB 集群: + +```bash +helm upgrade --install mycluster \ + greptime/greptimedb-cluster \ + --values /path/to/values.yaml \ + -n default +``` + +部署完成后,你可以用如下命令来查看 GreptimeDB 集群的 Pod 状态: + +```bash +kubectl -n default get pods +``` + +
+ Expected Output +```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 +``` +
+ +你可以转发 Grafana 的端口到本地来访问 Grafana 仪表盘: + +```bash +kubectl -n default port-forward svc/mycluster-grafana 18080:80 +``` + +请参考[访问 Grafana 仪表盘](#访问-grafana仪表盘)章节来查看相应的数据面板。 + + +## 配置监控数据的收集 + +本节将介绍监控配置的细节。 + +### 启用监控 + +在使用 Helm Chart 部署 GreptimeDB 集群时,在 [`values.yaml`](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md#setup-valuesyaml) 中添加以下配置来启用监控: + +```yaml +monitoring: + enabled: true +``` + +这将部署一个名为 `${cluster-name}-monitoring` 的 GreptimeDB Standalone 实例来收集指标和日志。你可以使用以下命令验证部署: + +```bash +kubectl get greptimedbstandalones.greptime.io ${cluster-name}-monitoring -n ${namespace} +``` + +GreptimeDB Standalone 实例使用 `${cluster-name}-monitoring-standalone` 作为 Kubernetes Service 名称来暴露服务。你可以使用以下地址访问监控数据: + +- **Prometheus 指标**:`http://${cluster-name}-monitor-standalone.${namespace}.svc.cluster.local:4000/v1/prometheus` +- **SQL 日志**:`${cluster-name}-monitor-standalone.${namespace}.svc.cluster.local:4002`。默认情况下,集群日志存储在 `public._gt_logs` 表中。 + +### 自定义监控数据存储 + +默认情况下,GreptimeDB Standalone 实例使用 Kubernetes 默认的 StorageClass 将监控数据存储在本地存储中。 +你可以通过 `values.yaml` 中的 `monitoring.standalone` 字段来配置 GreptimeDB Standalone 实例。例如,以下配置使用 S3 对象存储来存储监控数据: + +```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" +``` +### 自定义 Vector Sidecar + +用于日志收集的 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" +``` + +### 使用 `kubectl` 部署的 YAML 配置 + +如果你没有使用 Helm Chart 部署 GreptimeDB 集群, +可以在 `GreptimeDBCluster` 的 YAML 中使用 `monitoring` 字段来手动配置自监控模式: + +```yaml +monitoring: + enabled: true +``` + +详细的配置选项请参考 [`GreptimeDBCluster` API 文档](https://github.com/GreptimeTeam/greptimedb-operator/blob/main/docs/api-references/docs.md#monitoringspec)。 + + +## Grafana 配置 + +### 启用 Grafana + +在 `values.yaml` 中添加以下配置启用 Grafana 部署, +注意该功能必须先启用[监控(`monitoring.enabled: true`)配置](#启用监控): + +```yaml +monitoring: + enabled: true + +grafana: + enabled: true +``` + +### 自定义 Grafana 数据源 + +默认情况下,Grafana 使用 `mycluster` 和 `default` 作为集群名称和命名空间来创建数据源。 +要监控其他名称或命名空间的集群,请根据实际的集群名称和命名空间自定义配置。 +以下是 `values.yaml` 配置示例: + +```yaml +monitoring: + enabled: true + +grafana: + enabled: true + datasources: + datasources.yaml: + datasources: + - name: greptimedb-metrics + type: prometheus + url: http://${cluster-name}-monitor-standalone.${namespace}.svc.cluster.local:4000/v1/prometheus + access: proxy + isDefault: true + + - name: greptimedb-logs + type: mysql + url: ${cluster-name}-monitor-standalone.${namespace}.svc.cluster.local:4002 + access: proxy + database: public +``` + +此配置会在 Grafana 中为 GreptimeDB 集群的监控创建以下数据源: + +- **`greptimedb-metrics`**:用于存储监控数据的单机数据库中的集群指标,通过 Prometheus 协议提供服务(`type: prometheus`) +- **`greptimedb-logs`**:用于存储监控数据的单机数据库中的集群日志,通过 MySQL 协议提供服务(`type: mysql`),默认使用 `public` 数据库。 + +### 访问 Grafana 仪表盘 + +你可以通过将 Grafana 服务端口转发到本地来访问 Grafana 仪表盘: + +```bash +kubectl -n ${namespace} port-forward svc/${cluster-name}-grafana 18080:80 +``` + +然后打开 `http://localhost:18080` 来访问 Grafana 仪表盘。 +默认登录凭据为: + +- **用户名**:`admin` +- **密码**:`gt-operator` + +接着进入到 `Dashboards` 部分来查看用于监控 GreptimeDB 集群而预配置的仪表盘。 + +![Grafana Dashboard](/kubernetes-cluster-grafana-dashboard.jpg) + + +## 清理 PVC + +:::danger +清理操作将移除 GreptimeDB 集群的元数据和数据,请确保在操作前已备份数据。 +::: + +请参考[清理 GreptimeDB 集群](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md#cleanup)文档 +查看如何卸载 GreptimeDB 集群, + +要清理 GreptimeDB 用于监控的单机数据库的 PVC,请使用以下命令: + +```bash +kubectl -n default delete pvc -l app.greptime.io/component=${cluster-name}-monitor-standalone +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/key-logs.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/key-logs.md new file mode 100644 index 0000000000..ac638d66c7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/key-logs.md @@ -0,0 +1,200 @@ +--- +keywords: [关键日志, 错误日志, 运维日志, GreptimeDB 日志] +description: 通过关键日志了解 GreptimeDB 的运行情况,以及排查错误出现的原因。 +--- + +# 运维关键日志 + +GreptimeDB 在运行过程中,会将一些关键的操作以及预期外的错误信息输出到日志中。 +你可以通过这些日志了解 GreptimeDB 的运行情况,以及排查错误出现的原因。 + +## 日志位置 + +GreptimeDB 的组件默认都会输出 INFO 级别的日志到以下位置: + +- 标准输出 +- GreptimeDB 当前工作目录下的 `greptimedb_data/logs` 目录 + +日志文件的输出目录也可以通过配置文件的 `[logging]` 小节或者启动参数 `--log_dir` 修改: + +```toml +[logging] +dir = "/path/to/logs" +``` + +日志文件格式为: +- `greptimedb.YYYY-MM-DD-HH` 包含 INFO 以上等级的日志 +- `greptimedb-err.YYYY-MM-DD-HH` 包含错误日志 + +例如: + +```bash +greptimedb.2025-04-11-06 +greptimedb-err.2025-04-11-06 +``` + +目前 GreptimeDB 的组件包括 + +- frontend +- datanode +- metasrv +- flownode + +如果需要调整日志级别,如查看某组件 DEBUG 级别的日志,可以参考[这篇文档](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-change-log-level-on-the-fly.md)在运行时进行修改。 + +## 重要日志 + +以下将列举建议关注的日志 + +### 错误日志 + +数据库在正常平稳运行时,不会输出错误日志。如果数据库的一些操作出现异常,或者出现了 panic,都会打印错误日志。建议用户检查所有组件的错误日志。 + +#### Panic + +如果数据库出现了 panic ,则建议收集 panic 的日志反馈给官方。通常 panic 日志如下,关键字为 `panicked at`: + +```bash +2025-04-02T14:44:24.485935Z ERROR common_telemetry::panic_hook: panicked at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/expr/src/logical_plan/plan.rs:1035:25: +with_new_exprs for Distinct does not support sort expressions backtrace= 0: backtrace::backtrace::libunwind::trace + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/backtrace-0.3.74/src/backtrace/libunwind.rs:116:5 + backtrace::backtrace::trace_unsynchronized + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/backtrace-0.3.74/src/backtrace/mod.rs:66:5 + 1: backtrace::backtrace::trace + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/backtrace-0.3.74/src/backtrace/mod.rs:53:14 + 2: backtrace::capture::Backtrace::create + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/backtrace-0.3.74/src/capture.rs:292:9 + 3: backtrace::capture::Backtrace::new + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/backtrace-0.3.74/src/capture.rs:257:22 + 4: common_telemetry::panic_hook::set_panic_hook::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/common/telemetry/src/panic_hook.rs:37:25 + 5: as core::ops::function::Fn>::call + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/alloc/src/boxed.rs:1984:9 + std::panicking::rust_panic_with_hook + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/std/src/panicking.rs:820:13 + 6: std::panicking::begin_panic_handler::{{closure}} + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/std/src/panicking.rs:678:13 + 7: std::sys::backtrace::__rust_end_short_backtrace + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/std/src/sys/backtrace.rs:168:18 + 8: rust_begin_unwind + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/std/src/panicking.rs:676:5 + 9: core::panicking::panic_fmt + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/core/src/panicking.rs:75:14 + 10: datafusion_expr::logical_plan::plan::LogicalPlan::with_new_exprs + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/expr/src/logical_plan/plan.rs:1035:25 + 11: ::analyze::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/optimizer/type_conversion.rs:105:17 + 12: core::ops::function::impls:: for &F>::call_mut + at /greptime/.rustup/toolchains/nightly-2024-12-25-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/ops/function.rs:272:13 + 13: core::ops::function::impls:: for &mut F>::call_once + at /greptime/.rustup/toolchains/nightly-2024-12-25-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/ops/function.rs:305:13 + 14: datafusion_common::tree_node::Transformed::transform_parent + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/common/src/tree_node.rs:764:44 + 15: datafusion_common::tree_node::TreeNode::transform_up::transform_up_impl::{{closure}} + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/common/src/tree_node.rs:265:13 + 16: stacker::maybe_grow + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/stacker-0.1.17/src/lib.rs:55:9 + datafusion_common::tree_node::TreeNode::transform_up::transform_up_impl + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/common/src/tree_node.rs:260:9 + 17: datafusion_common::tree_node::TreeNode::transform_up + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/common/src/tree_node.rs:269:9 + 18: datafusion_common::tree_node::TreeNode::transform + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/common/src/tree_node.rs:220:9 + 19: ::analyze + at /greptime/codes/greptime/procedure-traits/src/query/src/optimizer/type_conversion.rs:46:9 + 20: query::query_engine::state::QueryEngineState::optimize_by_extension_rules::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/query_engine/state.rs:195:17 + 21: core::iter::traits::iterator::Iterator::try_fold + at /greptime/.rustup/toolchains/nightly-2024-12-25-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2370:21 + 22: query::query_engine::state::QueryEngineState::optimize_by_extension_rules + at /greptime/codes/greptime/procedure-traits/src/query/src/query_engine/state.rs:192:9 + 23: query::planner::DfLogicalPlanner::plan_sql::{{closure}}::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/planner.rs:119:20 + 24: as core::future::future::Future>::poll + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tracing-0.1.40/src/instrument.rs:321:9 + 25: query::planner::DfLogicalPlanner::plan_sql::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/planner.rs:71:5 + 26: ::plan::{{closure}}::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/planner.rs:198:73 + 27: as core::future::future::Future>::poll + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tracing-0.1.40/src/instrument.rs:321:9 + 28: ::plan::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/planner.rs:195:5 +... +``` + +### Metasrv + +当 GreptimeDB 集群出现节点上线,节点下线,region 迁移,schema 变更等情况时, metasrv 都会记录相应的日志。因此,除了各个组件的错误日志外,也建议关注 metasrv 的以下日志关键字 + +#### Metasrv 切主/发起选举 + +```bash +// error 级别,标识当前 leader step down, 接下来会发生新的选举,注意 {:?} 这部分是 leader 标识 +"Leader :{:?} step down" +``` + +#### Region 续租失败 + +```bash +// Warn 级别,表示一个 region 被拒绝续租,region 在某个 DN 上未被正常关闭/调度时,该 region 续租请求会被拒绝。 +Denied to renew region lease for datanode: {datanode_id}, region_id: {region_id} +``` + +```bash +// Info 级别,DN 收到续租失败信息,并尝试关闭目标 region +Closing staled region: +``` + +#### Region Failover + +```bash +// Warn 级别,发现部分 region 未通过 Phi 健康检测,需要执行 failover 操作,冒号后面好打印出相关的 region ids +Detects region failures: + +// 某一个 region 迁移失败 +Failed to wait region migration procedure + +// Info 级别,当维护模式打开时,failover procedure 会被跳过。 +Maintenance mode is enabled, skip failover +``` + +#### Region 迁移 + +```bash +// info 级别,表明某一个 region 开始迁移,日志后面会打印出 region 相关信息 +Starting region migration procedure + +// error 级别,某一个 region 迁移失败 +Failed to wait region migration procedure +``` + +#### Procedure + +Metasrv 内部通过一个叫做 procedure 的组件执行一些分布式操作。可以关注该组件的错误日志 + +```bash +Failed to execute procedure +``` + +#### Flow 创建失败 + +在创建 flow 失败时,通常在 procedure 的错误日志中可以看到失败的原因。日志可能包含以下关键字 + +```bash +Failed to execute procedure metasrv-procedure:: CreateFlow +``` + +### Datanode + +#### Compaction + +在 compaction 开始和结束时,datanode 上会有如下日志: + +```bash +2025-05-16T06:01:08.794415Z INFO mito2::compaction::task: Compacted SST files, region_id: 4612794875904(1074, 0), input: [FileMeta { region_id: 4612794875904(1074, 0), file_id: FileId(a29500fb-cae0-4f3f-8376-cb3f14653378), time_range: (1686455010000000000::Nanosecond, 1686468410000000000::Nanosecond), level: 0, file_size: 45893329, available_indexes: [], index_file_size: 0, num_rows: 5364000, num_row_groups: 53, sequence: Some(114408000) }, FileMeta { region_id: 4612794875904(1074, 0), file_id: FileId(a31dcb1b-19ae-432f-8482-9e1b7db7b53b), time_range: (1686468420000000000::Nanosecond, 1686481820000000000::Nanosecond), level: 0, file_size: 45900506, available_indexes: [], index_file_size: 0, num_rows: 5364000, num_row_groups: 53, sequence: Some(119772000) }], output: [FileMeta { region_id: 4612794875904(1074, 0), file_id: FileId(5d105ca7-9e3c-4298-afb3-e85baae3b2e8), time_range: (1686455010000000000::Nanosecond, 1686481820000000000::Nanosecond), level: 1, file_size: 91549797, available_indexes: [], index_file_size: 0, num_rows: 10728000, num_row_groups: 105, sequence: Some(119772000) }], window: Some(86400), waiter_num: 0, merge_time: 3.034328293s +``` + +```bash +2025-05-16T06:01:08.805366Z INFO mito2::request: Successfully compacted region: 4612794875904(1074, 0) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/monitor-cluster-with-prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/monitor-cluster-with-prometheus.md new file mode 100644 index 0000000000..040bba7865 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/monitor-cluster-with-prometheus.md @@ -0,0 +1,115 @@ +--- +keywords: [cluster, monitoring, Prometheus] +description: 本文介绍了如何在 Kubernetes 环境中使用现有的 Prometheus 实例监控 GreptimeDB 集群,包括配置 PodMonitor、启用指标收集和设置 Grafana 仪表板。 +--- + +# 使用 Prometheus 监控 GreptimeDB Cluster + +在阅读本文档之前,请确保你已经了解如何[在 Kubernetes 上部署 GreptimeDB 集群](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md)。 + +我们推荐使用[自监控方法](cluster-monitoring-deployment.md)来监控 GreptimeDB 集群, +这种模式配置简单且提供了开箱即用的 Grafana 仪表板。 +但如果你已经在 Kubernetes 集群中部署了 Prometheus 实例,并希望写入 +GreptimeDB 集群的监控指标,请按照本文档中的步骤操作。 + +## 检查 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 实例时,确保你设置了用于抓取 GreptimeDB 集群指标的标签。 +例如,你现有的 Prometheus 实例包含下面的配置: + +```yaml +apiVersion: monitoring.coreos.com/v1 +kind: PodMonitor +metadata: + name: greptime-podmonitor + namespace: default +spec: + selector: + matchLabels: + release: prometheus + # 其他配置... +``` + +当 `PodMonitor` 被部署后, +Prometheus Operator 会持续监视 `default` 命名空间中匹配 `spec.selector.matchLabels` 中定义的所有标签(在此示例中为 `release: prometheus`)的 Pod。 + +## 为 GreptimeDB 集群启用 `prometheusMonitor` + +使用 Helm Chart 部署 GreptimeDB 集群时, +在你的 `values.yaml` 文件中启用 `prometheusMonitor` 字段。例如: + +```yaml +prometheusMonitor: + # 启用 Prometheus 监控 - 这将创建 PodMonitor 资源 + enabled: true + # 配置抓取间隔 + interval: "30s" + # 配置标签 + labels: + release: prometheus +``` + +**重要:** `labels` 字段的值(`release: prometheus`) +必须与创建 Prometheus 实例时使用的 `matchLabels` 的值匹配, +否则指标收集将无法正常工作。 + +配置 `prometheusMonitor` 后, +GreptimeDB Operator 将自动创建 `PodMonitor` 资源并按指定的时间间隔 `interval` 将指标导入到 Prometheus。 +你可以使用以下命令检查 `PodMonitor` 资源: + +``` +kubectl get podmonitors.monitoring.coreos.com -n ${namespace} +``` + +:::note +如果你没有使用 Helm Chart 部署 GreptimeDB 集群, +可以在 `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 + backendStorage: + etcd: + endpoints: + - "etcd.etcd-cluster.svc.cluster.local:2379" + datanode: + replicas: 1 + prometheusMonitor: + enabled: true + interval: "30s" + labels: + release: prometheus +``` + +::: + +## Grafana 仪表板 + +你需要自己部署 Grafana, +然后导入仪表板。 + +### 添加数据源 + +部署 Grafana 后, +参考 Grafana 的[数据源](https://grafana.com/docs/grafana/latest/datasources/)文档添加以下两种类型的数据源: + +- **Prometheus**:将其命名为 `metrics`。此数据源连接到你的收集 GreptimeDB 集群监控指标的 Prometheus 实例,因此请使用你的 Prometheus 实例 URL 作为连接 URL。 +- **MySQL**:将其命名为 `information-schema`。此数据源连接到你的 GreptimeDB 集群,通过 SQL 协议访问集群元数据。如果你已经按照[在 Kubernetes 上部署 GreptimeDB 集群](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md)指南部署了 GreptimeDB,服务器地址为 `${cluster-name}-frontend.${namespace}.svc.cluster.local:4002`,数据库为 `information_schema`。 + +### 导入仪表板 + +[GreptimeDB 集群指标仪表板](https://github.com/GreptimeTeam/greptimedb/tree/VAR::greptimedbVersion/grafana/dashboards/metrics/cluster)使用 `metrics` 和 `information-schema` 数据源来显示 GreptimeDB 集群指标。 + +请参考 Grafana 的[导入仪表板](https://grafana.com/docs/grafana/latest/dashboards/build-dashboards/import-dashboards/)文档了解如何导入仪表板。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/overview.md new file mode 100644 index 0000000000..489b19d4e7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/overview.md @@ -0,0 +1,14 @@ +--- +keywords: [监控, 数据库监控, 导出指标, 链路追踪, Prometheus] +description: 介绍监控 GreptimeDB 的方法,包括导出指标和链路追踪。 +--- + +import DocCardList from '@theme/DocCardList'; + +# 监控 + +数据库的有效管理在很大程度上依赖于监控。 +你可以使用以下方法监控 GreptimeDB: + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/runtime-info.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/runtime-info.md new file mode 100644 index 0000000000..0fcdf0348a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/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-1.0/user-guide/deployments-administration/monitoring/slow-query.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/slow-query.md new file mode 100644 index 0000000000..501d7d37b7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/slow-query.md @@ -0,0 +1,71 @@ +--- +keywords: [GreptimeDB 慢查询, 慢查询日志, 慢查询监控, 慢查询配置] +description: 介绍如何在 GreptimeDB 中配置和使用慢查询日志进行监控。 +--- + +# 慢查询(实验性功能) + +GreptimeDB 提供了慢查询日志功能,帮助您发现和修复慢查询。默认情况下,慢查询会输出到系统表 `greptime_private.slow_queries` 中,阈值为 `30s`,采样率为 `1.0`,TTL 为 `30d`。 + +`greptime_private.slow_queries` 表的架构如下: + +```sql ++--------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------+----------------------+------+------+---------+---------------+ +| cost | UInt64 | | NO | | FIELD | +| threshold | UInt64 | | NO | | FIELD | +| query | String | | NO | | FIELD | +| is_promql | Boolean | | NO | | FIELD | +| timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| promql_range | UInt64 | | NO | | FIELD | +| promql_step | UInt64 | | NO | | FIELD | +| promql_start | TimestampMillisecond | | NO | | FIELD | +| promql_end | TimestampMillisecond | | NO | | FIELD | ++--------------+----------------------+------+------+---------+---------------+ +``` + +- `cost`: 查询的执行时间,单位为毫秒。 +- `threshold`: 慢查询的阈值,单位为毫秒。 +- `query`: 查询语句。 +- `is_promql`: 是否为 PromQL 查询。 +- `timestamp`: 查询的时间戳。 +- `promql_range`: 查询的时间范围。仅当 `is_promql` 为 `true` 时使用。 +- `promql_step`: 查询的时间步长。仅当 `is_promql` 为 `true` 时使用。 +- `promql_start`: 查询的开始时间。仅当 `is_promql` 为 `true` 时使用。 +- `promql_end`: 查询的结束时间。仅当 `is_promql` 为 `true` 时使用。 + +在集群模式下,你可以在 frontend 配置中配置慢查询(与单机模式相同),例如: + +```toml +[slow_query] +## 是否启用慢查询日志。 +enable = true + +## 慢查询的记录类型。可以是 `system_table` 或 `log`。 +## 如果选择 `system_table`,慢查询将记录在系统表 `greptime_private.slow_queries` 中。 +## 如果选择 `log`,慢查询将记录在日志文件 `greptimedb-slow-queries.*` 中。 +record_type = "system_table" + +## 慢查询的阈值。可以是可读的时间字符串,例如:`10s`,`100ms`,`1s`。 +threshold = "30s" + +## 慢查询日志的采样率。值应在 (0, 1] 范围内。例如,`0.1` 表示 10% 的慢查询将被记录,`1.0` 表示所有慢查询将被记录。 +sample_ratio = 1.0 + +## `slow_queries` 系统表的 TTL。当 `record_type` 为 `system_table` 时,默认值为 `30d`。 +ttl = "30d" +``` + +如果你使用 Helm 部署 GreptimeDB,可以在 `values.yaml` 文件中配置慢查询,例如: + +```yaml +slowQuery: + enable: true + recordType: "system_table" + threshold: "30s" + sampleRatio: "1.0" + ttl: "30d" +``` + +如果使用 `log` 作为记录类型,慢查询将记录在日志文件 `greptimedb-slow-queries.*` 中。默认情况下,日志文件位于 `${data_home}/logs` 目录。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/standalone-monitoring.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/standalone-monitoring.md new file mode 100644 index 0000000000..a1848c9b3b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/standalone-monitoring.md @@ -0,0 +1,57 @@ +--- +keywords: [standalone monitoring, GreptimeDB, metrics, Grafana] +description: 使用 Prometheus 指标和 Grafana 监控 GreptimeDB 单机实例的指南。 +--- + +# 单机监控 + +GreptimeDB 单机版在 HTTP 端口(默认 `4000`)上提供 `/metrics` 端点,暴露 [Prometheus 指标](/reference/http-endpoints.md#指标)。 + +## 监控配置 + +你可以配置 GreptimeDB 将指标导出到 GreptimeDB 自身或外部的 Prometheus 实例。 + +### 将指标存储到 GreptimeDB 自身 + +将指标存储到 GreptimeDB 自身既方便又推荐用于自监控,且支持基于 SQL 的查询和分析。 + +要启用自监控,请在你的 TOML 配置文件中配置 `export_metrics` 部分: + +```toml +[export_metrics] +enable = true +# 指标收集间隔 +write_interval = "30s" +[export_metrics.self_import] +db = "greptime_metrics" +``` + +此配置: +- 每 30 秒收集和写入指标。 +- 将指标导出到 GreptimeDB 内的 `greptime_metrics` 数据库。请确保在导出指标之前 `greptime_metrics` 数据库[已被创建](/reference/sql/create.md#create-database)。 + +### 导出指标到 Prometheus + +对于已有 Prometheus 基础设施的环境,GreptimeDB 可以通过 Prometheus 远程写入协议导出指标。 + +具体方法为,在 TOML 配置文件中使用 `remote_write` 选项配置 `export_metrics` 部分: + +```toml +[export_metrics] +enable=true +write_interval = "30s" +[export_metrics.remote_write] +# Prometheus Remote-Write 协议指定的 URL +url = "https://your/remote_write/endpoint" +# 一些可选的 HTTP 参数,如身份验证信息 +headers = { Authorization = {{Authorization}} } +``` + +此配置: +- 将导出间隔设置为 30 秒 +- 指定 Prometheus 远程写入 URL,应指向你的 Prometheus 实例 +- 可选择包含远程写入 URL 的 HTTP 头,如身份验证信息 + +## Grafana 仪表板集成 + +GreptimeDB 为监控单机部署提供预构建的 Grafana 仪表板。你可以从 [GreptimeDB 代码库](https://github.com/GreptimeTeam/greptimedb/tree/VAR::greptimedbVersion/grafana/dashboards/metrics/standalone) 访问仪表板 JSON 文件。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/tracing.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/tracing.md new file mode 100644 index 0000000000..72a1a00ba2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/monitoring/tracing.md @@ -0,0 +1,116 @@ +--- +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 部分](/user-guide/deployments-administration/configuration.md#logging-选项) 有对 tracing 的相关配置项说明,[standalone.example.toml](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/standalone.example.toml) 的 logging 部分提供了参考配置项。 + +## 教程:使用 Jaeger 追踪 GreptimeDB 调用链路 + +[Jaeger](https://www.jaegertracing.io/) 是一个开源的、端到端的分布式链路追踪系统,最初由 Uber 开发并开源。它的目标是帮助开发人员监测和调试复杂的微服务架构中的请求流程。 + +Jaeger 支持基于 gRPC 的 OTLP 协议,所以 GreptimeDB 可以将跟踪数据导出到 Jaeger。以下教程向您展示如何部署和使用 Jaeger 来跟踪 GreptimeDB。 + +### 步骤一:部署 Jaeger + +使用 jaeger 官方提供的 `all-in-one` docker 镜像启动一个 Jaeger 实例: + +```bash +docker run --rm -d --name jaeger \ + -e COLLECTOR_ZIPKIN_HOST_PORT=:9411 \ + -p 6831:6831/udp \ + -p 6832:6832/udp \ + -p 5778:5778 \ + -p 16686:16686 \ + -p 4317:4317 \ + -p 4318:4318 \ + -p 14250:14250 \ + -p 14268:14268 \ + -p 14269:14269 \ + -p 9411:9411 \ + jaegertracing/all-in-one:latest +``` + +### 步骤二:部署 GreptimeDB + +编写配置文件,允许 GreptimeDB 进行链路追踪。将下面的配置项保存为文件 `config.toml` + +```Toml +[logging] +enable_otlp_tracing = true +``` + +之后使用 standalone 模式启动 GreptimeDB + +```bash +greptime standalone start -c config.toml +``` + +参考章节 [Mysql](/user-guide/protocols/mysql.md) 如何连接到 GreptimeDB。在 Mysql Client 中运行下面的 SQL 语句: + +```sql +CREATE TABLE host ( + ts timestamp(3) time index, + host STRING PRIMARY KEY, + val BIGINT, +); + +INSERT INTO TABLE host VALUES + (0, 'host1', 0), + (20000, 'host2', 5); + +SELECT * FROM host ORDER BY ts; + +DROP TABLE host; +``` + +### 步骤三:在 Jaeger 中获取 trace 信息 + +1. 转到 http://127.0.0.1:16686/ 并选择“Search”选项卡。 +2. 在服务下拉列表中选择 `greptime-standalone` 服务。 +3. 单击 **Find Traces** 以显示追踪到的链路信息。 + +![JaegerUI](/jaegerui.png) + +![Select-tracing](/select-tracing.png) + +## 指南:如何配置 tracing 采样率 + +GreptimeDB 提供了许多协议与接口,用于数据的插入、查询等功能。您可以通过 tracing 采集到每种操作的调用链路。但是对于某些高频操作,将所有该操作的 tracing 都采集下来,可能没有必要而且浪费存储空间。这个时候,您可以使用 `tracing_sample_ratio` 来对各种操作 tracing 的采样率进行设置,这样能够很大程度上减少导出 tracing 的数量并有利于系统观测。 + +GreptimeDB 根据接入的协议,还有该协议对应的操作,对所有 tracing 进行了分类: + +| **protocol** | **request_type** | +|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| grpc | inserts / query.sql / query.logical_plan / query.prom_range / query.empty / ddl.create_database / ddl.create_table / ddl.alter / ddl.drop_table / ddl.truncate_table / ddl.empty / deletes / row_inserts / row_deletes | +| mysql | | +| postgres | | +| otlp | metrics / traces | +| opentsdb | | +| influxdb | write_v1 / write_v2 | +| prometheus | remote_read / remote_write / format_query / instant_query / range_query / labels_query / series_query / label_values_query | +| http | sql / promql + +您可以通过 `tracing_sample_ratio` 来配置不同 tracing 的采样率。 + +```toml +[logging] +enable_otlp_tracing = true +[logging.tracing_sample_ratio] +default_ratio = 0.0 +[[logging.tracing_sample_ratio.rules]] +protocol = "mysql" +ratio = 1.0 +[[logging.tracing_sample_ratio.rules]] +protocol = "grpc" +request_types = ["inserts"] +ratio = 0.3 +``` + +上述配置制定了两条采样规则,并制定了默认采样率,GreptimeDB 会根据您提供的采样规则,从第一条开始匹配,并使用第一条匹配到的采样规则作为该 tracing 的采样率,如果没有任何规则匹配,则 `default_ratio` 会被作为默认采样率被使用。采样率的范围是 `[0.0, 1.0]`, `0.0` 代表所有 tracing 都不采样,`1.0` 代表采样所有 tracing。 + +比如上面提供的规则,使用 mysql 协议接入的所有调用都将被采样,使用 grpc 插入的数据会被采样 30%,其余所有 tracing 都不会被采样。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/overview.md new file mode 100644 index 0000000000..bc9553f054 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/overview.md @@ -0,0 +1,56 @@ +--- +keywords: [配置项, 鉴权, Kubernetes 部署, Android 运行, 容量规划, GreptimeCloud] +description: GreptimeDB 部署概述,包括配置项、鉴权、在 Kubernetes 上部署、在 Android 上运行、容量规划和 GreptimeCloud 的介绍。 +--- + +# 运维部署及管理 + +GreptimeDB 可以部署在你自己的基础设施上,也可以通过全托管云服务 GreptimeCloud 进行管理。 +本指南概述了部署策略、配置、监控和管理的相关内容。 + +## GreptimeDB 架构 + +在进行 GreptimeDB 的部署和管理之前,有必要了解其[架构](/user-guide/concepts/architecture.md)。 + +## 自托管 GreptimeDB 部署 + +本节概述了自托管环境中部署和管理 GreptimeDB 的关键点。 + +### 配置和部署 + +- **配置:** 在部署 GreptimeDB 前,[检查配置](configuration.md)以确保满足你的相关需要,包括协议设置、存储选项等。 +- **鉴权:** 默认情况下鉴权没有被启动。了解如何[启用和配置鉴权](./authentication/overview.md)。 +- **Kubernetes 部署:** 按照[部署指南](./deploy-on-kubernetes/overview.md)在 Kubernetes 上部署 GreptimeDB。 +- **容量规划:** 通过[容量规划](/user-guide/deployments-administration/capacity-plan.md)确保集群能够处理业务所需的工作负载。 + +### 组件管理 + +- **Cluster Failover:** 通过设置 [Remote WAL](./wal/remote-wal/configuration.md) 以实现高可用性。 +- **管理元数据:** 为 GreptimeDB 设置[元数据存储](./manage-data/overview.md)。 + +### 监控 + +- **监控:** 通过指标、Traces 和运行时信息[监控集群的健康状况和性能](./monitoring/overview.md)。 + +### 数据管理和性能 + +- **数据管理:** 通过[管理数据策略](/user-guide/deployments-administration/manage-data/overview.md) 以防止数据丢失、降低成本并优化性能。 +- **性能调优:** 查看[性能调优技巧](/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md)并学习如何[设计表结构](/user-guide/deployments-administration/performance-tuning/design-table.md)以提高性能。 + +### 灾难恢复 + +- **灾难恢复:** 实施[灾难恢复策略](/user-guide/deployments-administration/disaster-recovery/overview.md)以保护你的数据并确保业务连续性。 + +### 其他 + +- **在 Android 上运行:** 了解如何[在 Android 设备上运行 GreptimeDB](run-on-android.md)。 +- **升级:** 按照[升级指南](/user-guide/deployments-administration/upgrade.md)升级 GreptimeDB。 + +## GreptimeCloud + +对于完全托管的体验, +请考虑 [GreptimeCloud](https://greptime.cloud)。 +GreptimeCloud 使你能够轻松部署、监控和扩展 GreptimeDB 实例,内置指标监控和告警功能。 +它旨在为时序数据平台和 Prometheus 后端提供可扩展、高效的无服务器解决方案。 + +更多详情,请参阅 [GreptimeCloud 文档](https://docs.greptime.com/nightly/greptimecloud/overview)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/performance-tuning/design-table.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/performance-tuning/design-table.md new file mode 100644 index 0000000000..7aaea97b4b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/performance-tuning/design-table.md @@ -0,0 +1,366 @@ +--- +keywords: [数据模型, 表结构, 标签, tag 列, 时间线, 高基数, 倒排索引, 全文索引, 跳数索引, 宽表, 分布式表] +description: 详细介绍了 GreptimeDB 的数据模型使用指南,以及常见场景的表结构设计方式。 +--- + +# 数据建模指南 + +表结构设计将极大影响写入和查询性能。 +在写入数据之前,你需要了解业务中涉及到的数据类型、数据规模以及常用查询, +并根据这些数据特征进行数据建模。 +本文档将详细介绍 GreptimeDB 的数据模型使用指南,以及常见场景的表结构设计方式。 + +## 了解 GreptimeDB 的数据模型 + +在阅读本文档之前,请先阅读 GreptimeDB [数据模型文档](/user-guide/concepts/data-model.md)。 + +## 基本概念 + +**基数(Cardinality)**:指数据集中唯一值的数量。可以分为"高基数"和"低基数": + +- **低基数(Low Cardinality)**:低基数列通常具有固定值。 + 唯一值的总数通常不超过1万个。 + 例如,`namespace`、`cluster`、`http_method` 通常是低基数的。 +- **高基数(High Cardinality)**:高基数列包含大量的唯一值。 + 例如,`trace_id`、`span_id`、`user_id`、`uri`、`ip`、`uuid`、`request_id`、表的自增 ID,时间戳通常是高基数的。 + + +## 列类型 + +在 GreptimeDB 中,列被分为三种语义类型:`Tag`、`Field` 和 `Timestamp`。 +时间戳通常表示数据采样的时间或日志/事件发生的时间。 +GreptimeDB 使用 `TIME INDEX` 约束来标识 `Timestamp` 列。 +因此,`Timestamp` 列也被称为 `TIME INDEX` 列。 +如果你有多个时间戳数据类型的列,你只能将其中一个定义为 `TIME INDEX`,其他的定义为 `Field` 列。 + +在 GreptimeDB 中,Tag 列是可选的。Tag 列的主要用途包括: + +1. 定义存储时数据的排序方式。 + GreptimeDB 使用 `PRIMARY KEY` 约束来定义 tag 列和 tag 的排序顺序。 + 与传统数据库不同,GreptimeDB 的主键是用来定义时间序列的。 + GreptimeDB 中的表按照 `(primary key, timestamp)` 的顺序对行进行排序。 + 这提高了具有相同 tag 数据的局部性。 + 如果没有定义 tag 列,GreptimeDB 按时间戳对行进行排序。 +2. 唯一标识一个时间序列。 + 当表不是 append-only 模式时,GreptimeDB 根据时间戳在同一时间序列(主键)下去除重复行。 +3. 便于从使用 label 或 tag 的其他时序数据库迁移。 + + +## 主键 + +### 主键是可选的 + +错误的主键或索引可能会显著降低性能。 +通常,你可以创建一个没有主键的仅追加表,因为对于许多场景来说,按时间戳排序数据已经有不错测性能了。 +这也可以作为性能基准。 + +```sql +CREATE TABLE http_logs ( + access_time TIMESTAMP TIME INDEX, + application STRING, + remote_addr STRING, + http_status STRING, + http_method STRING, + http_refer STRING, + user_agent STRING, + request_id STRING, + request STRING, +) with ('append_mode'='true'); +``` + +`http_logs` 表是存储 HTTP 服务器日志的示例。 + +- `'append_mode'='true'` 选项将表创建为仅追加表。 + 这确保一个日志不会覆盖另一个具有相同时间戳的日志。 +- 该表按时间对日志进行排序,因此按时间搜索日志效率很高。 + + +### 何时使用主键 + +当有适合的低基数列且满足以下条件之一时,可以使用主键: + +- 大多数查询可以从排序中受益。 +- 你需要通过主键和时间索引对行进行去重(包括删除)。 + +例如,如果你总是只查询特定应用程序的日志,可以将 `application` 列设为主键(tag)。 + +```sql +SELECT message FROM http_logs WHERE application = 'greptimedb' AND access_time > now() - '5 minute'::INTERVAL; +``` + +应用程序的数量通常是有限的。表 `http_logs_v2` 使用 `application` 作为主键。 +它按应用程序对日志进行排序,因此查询同一应用程序下的日志速度更快,因为它只需要扫描少量行。设置 tag 还能减少磁盘空间,因为它提高了数据的局部性,对压缩更友好。 + +```sql +CREATE TABLE http_logs_v2 ( + access_time TIMESTAMP TIME INDEX, + application STRING, + remote_addr STRING, + http_status STRING, + http_method STRING, + http_refer STRING, + user_agent STRING, + request_id STRING, + request STRING, + PRIMARY KEY(application), +) with ('append_mode'='true'); +``` + +为了提高时序场景下的排序和去重速度,GreptimeDB 内部按时间序列缓冲和处理行。 +因此,它不需要反复比较每行的主键。 +如果 tag 列具有高基数,这可能会成为问题: + +1. 由于数据库无法有效地批处理行,性能可能会降低。 +2. 由于数据库必须为每个时间序列维护元数据,可能会增加内存和 CPU 使用率。 +3. 去重可能会变得过于昂贵。 + +因此,不能将高基数列作为主键,或在主键中放入过多列。目前,主键值的推荐数量不超过 10 万。过长的主键将对插入性能产生负面影响并增加内存占用。主键最好不超过 5 个列。 + +选取 tag 列的建议: + +- 在 `WHERE`/`GROUP BY`/`ORDER BY` 中频繁出现的低基数列。 + 这些列通常很少变化。 + 例如,`namespace`、`cluster` 或 AWS `region`。 +- 无需将所有低基数列设为 tag,因为这可能影响写入和查询性能。 +- 通常对 tag 使用短字符串和整数,避免 `FLOAT`、`DOUBLE`、`TIMESTAMP`。 +- 如果高基数列经常变化,切勿将其设为 tag。 +例如,`trace_id`、`span_id`、`user_id` 绝不能用作 tag。 +如果将它们设为 field 而非 tag,GreptimeDB 可以有很不错的性能。 + + +## 索引 + +除了主键外,你还可以使用倒排索引按需加速特定查询。 + +GreptimeDB 支持倒排索引,可以加速对低基数列的过滤。 +创建表时,可以使用 `INVERTED INDEX` 子句指定[倒排索引](/contributor-guide/datanode/data-persistence-indexing.md#倒排索引)列。 +例如,`http_logs_v3` 为 `http_method` 列添加了倒排索引。 + +```sql +CREATE TABLE http_logs_v3 ( + access_time TIMESTAMP TIME INDEX, + application STRING, + remote_addr STRING, + http_status STRING, + http_method STRING INVERTED INDEX, + http_refer STRING, + user_agent STRING, + request_id STRING, + request STRING, + PRIMARY KEY(application), +) with ('append_mode'='true'); +``` + +以下查询可以使用 `http_method` 列上的倒排索引。 + +```sql +SELECT message FROM http_logs_v3 WHERE application = 'greptimedb' AND http_method = `GET` AND access_time > now() - '5 minute'::INTERVAL; +``` + +倒排索引支持以下运算符: +- `=` +- `<` +- `<=` +- `>` +- `>=` +- `IN` +- `BETWEEN` +- `~` + + +### 跳数索引 + +对于高基数列如 `trace_id`、`request_id`,使用[跳数索引](/user-guide/manage-data/data-index.md#跳数索引)更为合适。 +这种方法的存储开销更低,资源使用量更少,特别是在内存和磁盘消耗方面。 + +示例: + +```sql +CREATE TABLE http_logs_v4 ( + access_time TIMESTAMP TIME INDEX, + application STRING, + remote_addr STRING, + http_status STRING, + http_method STRING INVERTED INDEX, + http_refer STRING, + user_agent STRING, + request_id STRING SKIPPING INDEX, + request STRING, + PRIMARY KEY(application), +) with ('append_mode'='true'); +``` + +以下查询可以使用跳数索引过滤 `request_id` 列。 + +```sql +SELECT message FROM http_logs_v4 WHERE application = 'greptimedb' AND request_id = `25b6f398-41cf-4965-aa19-e1c63a88a7a9` AND access_time > now() - '5 minute'::INTERVAL; +``` + +然而,请注意跳数索引的查询功能通常不如倒排索引丰富。 +跳数索引无法处理复杂的过滤条件,在低基数列上可能有较低的过滤性能。它只支持等于运算符。 + +### 全文索引 + +对于需要分词和按术语搜索的非结构化日志消息,GreptimeDB 提供了全文索引。 + +例如,`raw_logs` 表在 `message` 字段中存储非结构化日志。 + +```sql +CREATE TABLE IF NOT EXISTS `raw_logs` ( + message STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', case_sensitive = 'false'), + ts TIMESTAMP(9) NOT NULL, + TIME INDEX (ts), +) with ('append_mode'='true'); +``` + +`message` 字段使用 `FULLTEXT INDEX` 选项进行全文索引。 +更多信息请参见[fulltext 列选项](/reference/sql/create.md#fulltext-列选项)。 + +存储和查询结构化日志通常比带有全文索引的非结构化日志性能更好。 +建议[使用 Pipeline](/user-guide/logs/quick-start.md#创建-pipeline) 将日志转换为结构化日志。 + + +### 何时使用索引 + +GreptimeDB 中的索引十分灵活。 +你可以为任何列创建索引,无论该列是 tag 还是 field。 +为 time index 列创建额外索引没有意义。 +另外,你一般不需要为所有列创建索引。 +因为维护索引可能引入额外成本并阻塞 ingestion。 +不良的索引可能会占用过多磁盘空间并使查询变慢。 + +你可以用没有额外索引的表作为 baseline。 +如果查询性能已经可接受,就无需为表创建索引。 +在以下情况可以为列创建索引: + +- 该列在过滤条件中频繁出现。 +- 没有索引的情况下过滤该列不够快。 +- 该列有合适的索引类型。 + +下表列出了所有索引类型的适用场景。 + +| | 倒排索引 | 全文索引 | 跳数索引| +| ----- | ----------- | ------------- |------------- | +| 适用场景 | - 过滤低基数列 | - 文本内容搜索 | - 精确过滤高基数列 | +| 创建方法 | - 使用 `INVERTED INDEX` 指定 |- 在列选项中使用 `FULLTEXT INDEX` 指定 | - 在列选项中使用 `SKIPPING INDEX` 指定 | + + +## 去重 + +如果需要去重,可以使用默认表选项,相当于将 `append_mode` 设为 `false` 并启用去重功能。 + +```sql +CREATE TABLE IF NOT EXISTS system_metrics ( + host STRING, + cpu_util DOUBLE, + memory_util DOUBLE, + disk_util DOUBLE, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY(host), + TIME INDEX(ts) +); +``` + +当表不是 append-only 的时候,GreptimeDB 会通过相同的主键和时间戳对行进行去重。 +例如,`system_metrics` 表通过 `host` 和 `ts` 删除重复行。 + +### 数据更新和合并 + +GreptimeDB 支持两种不同的去重策略:`last_row` 和 `last_non_null`。 +你可以通过 `merge_mode` 表选项来指定策略。 + +GreptimeDB 使用基于 LSM-Tree 的存储引擎, +不会就地覆盖旧数据,而是允许多个版本的数据共存。 +这些版本在查询时再合并。 +默认的合并行为是 `last_row`,意味着只保留最近插入的行。 + +![merge-mode-last-row](/merge-mode-last-row.png) + +在 `last_row` 合并模式下, +对于相同主键和时间值,只返回最新的行, +所以更新一行时需要提供所有 field 的值。 + +对于只需要更新特定 field 值而其他 field 保持不变的场景, +可以将 `merge_mode` 选项设为 `last_non_null`。 +该模式在查询时会选取每个字段的最新的非空值, +这样可以在更新时只提供需要更改的 field 的值。 + +![merge-mode-last-non-null](/merge-mode-last-non-null.png) + +为了与 InfluxDB 的更新行为一致,通过 InfluxDB line protocol 自动创建的表默认启用 `last_non_null` 合并模式。 + +`last_row` 合并模式不需要检查每个单独的字段值,因此通常比 `last_non_null` 模式更快。 +请注意,append-only 表不能设置 `merge_mode`,因为它们不执行合并。 + +### 何时使用 append-only 表 + +如果不需要以下功能,可以使用 append-only 表: + +- 去重 +- 删除 + +GreptimeDB 通过去重功能实现 `DELETE`,因此 append-only 表目前不支持删除。 +去重需要更多的计算并限制了写入和查询的并行性,所以使用 append-only 表通常具有更好的性能。 + +## 宽表 vs. 多表 + +在监控或 IoT 场景中,通常同时收集多个指标。 +我们建议将同时收集的指标放在单个表中,以提高读写吞吐量和数据压缩效率。 + +![wide_table](/wide_table.png) + +比较遗憾,Prometheus 的存储还是多表单值的方式,不过 GreptimeDB 的 Prometheus Remote Storage protocol 通过[Metric Engine](/contributor-guide/datanode/metric-engine.md)在底层使用宽表数据共享。 + +## 分布式表 + +GreptimeDB 支持对数据表进行分区,以分散读写热点并实现水平扩展。 + +### 关于分布式表的两个误解 + +作为时序数据库,GreptimeDB 在存储层自动基于 TIME INDEX 列对数据进行分区。 +因此,你无需也不建议按时间分区数据 +(例如,每天一个分区或每周一个表)。 + +此外,GreptimeDB 是列式存储数据库, +因此对表进行分区是指按行进行水平分区, +每个分区包含所有列。 + + +### 何时分区以及确定分区数量 + +单个表能够利用机器中的所有资源,特别是在查询的时候。 +分区表并不总是能提高性能: + +- 分布式查询计划并不总是像本地查询计划那样高效。 +- 分布式查询可能会引入网络间额外的数据传输。 + +因此,除非单台机器不足以服务表,否则无需分区表。 +例如: + +- 本地磁盘空间不足以存储数据或在使用对象存储时缓存数据。 +- 你需要更多 CPU 来提高查询性能或更多内存用于高开销的查询。 +- 磁盘吞吐量成为瓶颈。 +- 写入速率大于单个节点的吞吐量。 + +GreptimeDB 在每次主要版本更新时都会发布[benchmark report](https://github.com/GreptimeTeam/greptimedb/tree/VAR::greptimedbVersion/docs/benchmarks/tsbs), +里面提供了单个分区的写入吞吐量作为参考。 +你可以在你的的目标场景根据该报告来估计写入量是否接近单个分区的限制。 + +估计分区总数时,可以考虑写入吞吐量并额外预留 50% 的 CPU 资源,以确保查询性能和稳定性。也可以根据需要调整此比例。例如,如果查询较多,那么可以预留更多 CPU 资源。 + + +### 分区方法 + +GreptimeDB 使用表达式定义分区规则。 +为获得最佳性能,建议选择均匀分布、稳定且与查询条件一致的分区键。 + +例如: + +- 按 trace id 的前缀分区。 +- 按数据中心名称分区。 +- 按业务名称分区。 + +分区键应该尽量贴合查询条件。 +例如,如果大多数查询针对特定数据中心的数据,那么可以使用数据中心名称作为分区键。 +如果不了解数据分布,可以对现有数据执行聚合查询以收集相关信息。 +更多详情,请参考[表分区指南](/user-guide/deployments-administration/manage-data/table-sharding.md#partition) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md new file mode 100644 index 0000000000..e05b5bd7a1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md @@ -0,0 +1,163 @@ +--- +keywords: [性能调优, 查询性能, 缓存配置, 写入优化, 表结构设计, 指标监控, 对象存储, 批量写入, append-only 表] +description: 提供 GreptimeDB 性能调优的技巧,包括查询性能指标、缓存配置、写入优化和表结构设计建议。 +--- + +# 性能调优技巧 + +GreptimeDB 实例的默认配置可能不适合所有场景。因此根据场景调整数据库配置和使用方式相当重要。 + +GreptimeDB 提供了各种指标来帮助监控和排查性能问题。官方仓库里提供了用于独立模式和集群模式的 [Grafana dashboard 模版](https://github.com/GreptimeTeam/greptimedb/tree/main/grafana)。 + +## 查询 + +### ANALYZE QUERY + +GreptimeDB 支持查询分析功能,通过 `EXPLAIN ANALYZE [VERBOSE] ` 语句可以看到逐步的查询耗时。 + +### 指标 + +以下指标可用于诊断查询性能问题: +| 指标 | 类型 | 描述 | +|---|---|---| +| greptime_mito_read_stage_elapsed_bucket | histogram | 存储引擎中查询不同阶段的耗时。 | +| greptime_mito_cache_bytes | gauge | 缓存内容的大小 | +| greptime_mito_cache_hit | counter | 缓存命中总数 | +| greptime_mito_cache_miss | counter | 缓存未命中总数 | + + +### 增大缓存大小 + +可以监控 `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" +``` + + +一些建议: +- 至少将写入缓存设置为磁盘空间的 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 表,因为日志消息可能具有相同的时间戳。 + +### 禁用预写式日志(WAL) + +如果您是从 Kafka 等可以重放的数据源消费并写入到 GreptimeDB,可以通过禁用 WAL 来进一步提升写入吞吐量。 + +请注意,当 WAL 被禁用后,未刷新到磁盘或对象存储的数据将无法恢复,需要从原始数据源重新恢复,比如重新从 Kafka 读取或重新抓取日志。 + +通过设置表选项 `skip_wal='true'` 来禁用 WAL: + +```sql +CREATE TABLE logs( + message STRING, + ts TIMESTAMP TIME INDEX +) WITH (skip_wal = 'true'); +``` + +## 写入 + +### 指标 + +以下指标有助于诊断写入问题: + +| 指标 | 类型 | 描述 | +|---|---|---| +| 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-1.0/user-guide/deployments-administration/run-on-android.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/run-on-android.md new file mode 100644 index 0000000000..3621c34786 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/run-on-android.md @@ -0,0 +1,112 @@ +--- +keywords: [安卓平台, ARM64 CPU, Android API 23, Termux 终端模拟器, 二进制文件, 配置文件, 启动服务, 连接数据库] +description: 在安卓平台运行 GreptimeDB 的指南,包括安装终端模拟器、下载二进制文件、创建配置文件、启动服务和连接数据库的步骤。 +--- + +# 在安卓平台运行 + +从 v0.4.0 开始,GreptimeDB 支持在采用了 ARM64 CPU 和 Android API 23 版本以上的安卓平台运行。 + +## 安装终端模拟器 + +您可以从 [GitHub release 页面](https://github.com/termux/termux-app/releases/latest) 下载 [Termux 终端模拟器](https://termux.dev/) 来运行 GreptimeDB. + + + +## 下载 GreptimeDB 的二进制 + +请执行以下命令来下载安卓平台的 GreptimeDB 二进制: +```bash +VERSION=$(curl -sL \ + -H "Accept: application/vnd.github+json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + "https://api.github.com/repos/GreptimeTeam/greptimedb/releases/latest" | sed -n 's/.*"tag_name": "\([^"]*\)".*/\1/p') + + +curl -sOL "https://github.com/GreptimeTeam/greptimedb/releases/download/${VERSION}/greptime-android-arm64-${VERSION}.tar.gz" +tar zxvf ./greptime-android-arm64-${VERSION}.tar.gz +./greptime -V +``` + +如果下载成功,以上命令将输出当前 GreptimeDB 的版本信息。 + +## 创建 GreptimeDB 的配置文件 + +您可以通过以下命令来创建一个最小化的配置文件以允许从局域网访问 GreptimeDB: + +```bash +DATA_DIR="$(pwd)/greptimedb-data" +mkdir -p ${DATA_DIR} + +cat < ./config.toml +[http] +addr = "0.0.0.0:4000" + +[grpc] +bind_addr = "0.0.0.0:4001" + +[mysql] +addr = "0.0.0.0:4002" + +[storage] +data_home = "${DATA_DIR}" +type = "File" +EOF +``` + +## 从命令行启动 GreptimeDB + +```bash +./greptime --log-dir=$(pwd)/logs standalone start -c ./config.toml +``` + +## 从局域网连接运行在安卓设备上的 GreptimeDB + +> 您可以通过`ifconfig`来获取您所使用的的安卓设备的网络地址。 + +在启动 GreptimeDB 后,您可以从局域网内安装了 MySQL 客户端的设备上通过 MySQL 协议访问 GreptimeDB。 + +```bash +mysql -h -P 4002 +``` + +连接成功后,您可以像在任何其他平台一样使用运行在安卓设备上的 GreptimeDB! + +``` +Welcome to the MySQL monitor. Commands end with ; or \g. +Your MySQL connection id is 8 +Server version: 5.1.10-alpha-msql-proxy Greptime + +Copyright (c) 2000, 2023, Oracle and/or its affiliates. + +Oracle is a registered trademark of Oracle Corporation and/or its +affiliates. Other names may be trademarks of their respective +owners. + +Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. + +mysql> CREATE TABLE monitor (env STRING, host STRING, ts TIMESTAMP, cpu DOUBLE DEFAULT 0, memory DOUBLE, TIME INDEX (ts), PRIMARY KEY(env,host)); +Query OK, 0 rows affected (0.14 sec) + +mysql> INSERT INTO monitor(ts, env, host, cpu, memory) VALUES + -> (1655276557000,'prod', 'host1', 66.6, 1024), + -> (1655276557000,'prod', 'host2', 66.6, 1024), + -> (1655276557000,'prod', 'host3', 66.6, 1024), + -> (1655276558000,'prod', 'host1', 77.7, 2048), + -> (1655276558000,'prod', 'host2', 77.7, 2048), + -> (1655276558000,'test', 'host3', 77.7, 2048), + -> (1655276559000,'test', 'host1', 88.8, 4096), + -> (1655276559000,'test', 'host2', 88.8, 4096), + -> (1655276559000,'test', 'host3', 88.8, 4096); +Query OK, 9 rows affected (0.14 sec) + +mysql> +mysql> select * from monitor where env='test' and host='host3'; ++------+-------+---------------------+------+--------+ +| env | host | ts | cpu | memory | ++------+-------+---------------------+------+--------+ +| test | host3 | 2022-06-15 15:02:38 | 77.7 | 2048 | +| test | host3 | 2022-06-15 15:02:39 | 88.8 | 4096 | ++------+-------+---------------------+------+--------+ +2 rows in set (0.20 sec) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/troubleshooting.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/troubleshooting.md new file mode 100644 index 0000000000..5a4391473b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/troubleshooting.md @@ -0,0 +1,110 @@ +--- +keywords: [问题排查, 配置问题排查, 性能问题排查, 写入问题排查] +description: GreptimeDB 的问题排查指南,包括常见问题的排查方法和指标。 +--- + +# 问题排查 + +在遇到错误或者性能问题时,我们可以基于指标和日志了解 GreptimeDB 的状态。这些信息也可以帮助进一步排查问题的原因。 +以下列举了部分常见异常情况的排查方法。对于无法简单定位原因的情况,提供指标和日志给官方团队也能提高官方排查问题的效率。 + +## 查看 CPU 和 Memory 负载 + +可直接从 Dashboard 中查看对应组件的 CPU 和 Memory 负载,其中 CPU 显示的是 millicore,Memory 则是当前进程的 RSS。此时需要要关注对应的 CPU 和 Memory 负载是否有超过 Pod 的 Limit,如果 CPU 已经触碰到 Pod 的 Limit,那么将会触发 throttle,用户可感受的现象就是请求处理变慢;如果 Memory 已经到达 Limit 超过 70%,那么将有可能会被 OOM。 + +## 创建 flow 失败 + +创建 flow 失败时,一个场景的原因是没有部署 flownode,可以检查 + +- 集群中是否部署了 flownode +- 集群中 flownode 状态是否 READY + +如果已经部署了 flownode,则可以通过排查 metasrv 和 flownode 的日志进一步排查,也可以通过内部表查看 flow 节点是否成功创建: + +```sql +select * from information_schema.cluster_info; +``` + +## 对象存储配置问题 + +对象存储配置不对时,GreptimeDB 访问对象存储会出现异常。如果 GreptimeDB 没有存储任何数据,一般不需要访问对象存储,因此刚部署完成时可能观察不到错误。当创建一张表或者开始通过写入协议往 GreptimeDB 写入数据后,则可以观察到请求报错。 + +通常 DB 返回错误信息会包含对象存储的报错。可以通过 DB 的错误日志找到对象存储具体的报错信息。一些常见的错误原因包括 + +- Access Key 或 Secret Access Key 填写错误 +- 对象存储的权限配置不对 +- 如果使用的是腾讯云 COS 的 S3 兼容 API,由于腾讯云[禁用了 path-style 域名](https://cloud.tencent.com/document/product/436/102489),需要在 GreptimeDB 的 S3 配置中设置 `enable_virtual_host_style = true` + +以 S3 为例,GreptimeDB 需要用到的权限包括 + +```txt +"s3:PutObject", +"s3:ListBucket", +"s3:GetObject", +"s3:DeleteObject" +``` + +## 写入吞吐低 + +通过大盘里的 Ingestion 相关面板可以观察到写入的吞吐: + +![ingestion rate](/ingestion-rate.jpg) + +如果写入吞吐低于预期压力,那么有可能是写入延时较高,DB 出现积压导致的。大盘在 `Frontend Requests` 区域中提供了一些面板来观察请求的耗时: + +![p99-latencies](/dashboard-p99-latencies.jpg) + +你可以通过 `Mito Engine` 区域的 `Write Stall` 面板观察是否有节点出现了 stall(stall 的值长时间超过 0)。 +如果有,则说明节点写入出现了瓶颈。 + +![write-stall](/write-stall.jpg) + +通过观察 `Write Buffer` 的面板也可以观察用于写入的 buffer 的大小变化,如果 buffer 很快被写满,那么可以考虑成比例调大 `global_write_buffer_size` 和 `global_write_buffer_reject_size`: + +![write-buffer](/write-buffer.jpg) + +通过 Write Stage 面板可以查看写入耗时高的阶段: + +![write-stage](/write-stage.jpg) + +可以通过 Compaction/Flush 相关面板查看后台任务的情况 +- 是否出现频繁的 flush 操作,如果有,则可以考虑成比例调大 `global_write_buffer_size` 和 `global_write_buffer_reject_size` +- 是否有长时间的 compaction 和 flush 操作,如果有,则写入有可能受这些后台任务影响 + +此外,通过日志里 `flush memtables` 相关的日志可以看到单次 flush 的耗时, + +## 写入内存消耗过高 + +DB 写入过程中会估算出当前所有 memtable 的总大小。可以通过 `Write Buffer` 面板查看 memtable 的内存占用。 + +![write-buffer-memtable](/write-buffer-memtable.jpg) + +注意这部分的值可能比实际申请的内存要小。 + +如果发现写入时 DB 的内存增长速度过快,或者写入经常出现 OOM 的情况,则可能跟表结构设计不合理有关。 + +一个常见的原因是主键(Primary Key)设计不合理。如果主键的数量过多,则会导致写入时消耗非常多的内存,可能导致数据库内存占用过大。出现这种情况时,往往 `Write Buffer` 会长期处于高位置。这种情况增加写入 buffer 的大小一般不会改善问题,需要减少主键的列数,或者去掉高基数的主键列。 + +## 查询耗时高 + +如果查询的耗时较高,可以通过在查询前面加上 `EXPLAIN ANALYZE` 或 `EXPLAIN ANALYZE VERBOSE` 重新执行。查询的结果会带上各个阶段执行的耗时用于协助排查。 + +此外 `Read Stage` 的面板也能协助了解不同阶段的查询耗时: + +![read-stage](/read-stage.jpg) + +## 缓存写满 + +如果需要了解各个缓存的大小,可以通过 `Cached Bytes` 面板查询节不同缓存已经使用的大小: + +![cached-bytes](/cached-bytes.jpg) + +对于查询耗时高的节点,也可以通过查询缓存大小来判断是否缓存已经写满。 + +## 对象存储耗时 + +可以通过大盘中的 `OpenDAL` 区域的面板查看对象存储操作的耗时,例如以下面板是对象存储写入操作的响应耗时: + +![opendal](/opendal.jpg) + +如果怀疑对象存储操作出现抖动,可以观察相关的面板。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/upgrade.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/upgrade.md new file mode 100644 index 0000000000..46ae954ae6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/upgrade.md @@ -0,0 +1,28 @@ +--- +keywords: [版本升级, 升级步骤, 数据库升级] +description: 介绍如何将 GreptimeDB 升级到最新版本,包括一些不兼容的变更和升级具体步骤。 +--- + +# 版本升级 + +## 如何升级 GreptimeDB + +如果你当前部署的 GreptimeDB 版本是 v0.12 或更高版本,v0.14 完全兼容现有的数据库配置和数据格式,可以直接进行升级。若你使用的是 v0.12 之前的版本,建议先参考 v0.12 的升级文档将数据库升级至 v0.12,然后再升级到 v0.14,以确保兼容性和平稳过渡。 + +## 将升级对业务带来的影响最小化 + +在升级 GreptimeDB 之前,请全面备份数据以防止潜在的数据丢失。 +此备份作为升级过程中出现任何问题时的安全保障。 + +为最大限度降低升级对业务的影响,我们推荐以下可选实践: +- **滚动升级:** 在 Kubernetes 上采用[滚动升级](https://kubernetes.io/docs/tutorials/kubernetes-basics/update/update-intro/)策略逐步更替 GreptimeDB 实例。 +该方案通过新旧实例渐进式替换,在确保服务持续可用的前提下实现零停机升级。 +- **客户端重试机制:** 建议在客户端配置具备指数退避特性的自动重试策略, +可有效规避升级过程中的瞬时服务不可用问题。 +- **写操作熔断:** 对于允许短暂维护的业务场景, +可在升级窗口期暂时停止写入操作, +此方案能最大限度保障数据一致性。 +- **双写迁移方案**:实施新旧版本双写机制, +待新版本验证通过后逐步切换流量。 +该方案既能确保数据一致性校验, +又可实现读流量灰度迁移。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/local-wal.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/local-wal.md new file mode 100644 index 0000000000..48cd387260 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/local-wal.md @@ -0,0 +1,45 @@ +--- +keywords: [配置, 本地 WAL, GreptimeDB Datanode, GreptimeDB] +description: 介绍如何配置 GreptimeDB 中的本地 WAL。 +--- + +# 本地 WAL + +本节介绍如何配置 GreptimeDB Datanode 组件的本地 WAL。 + +```toml +[wal] +provider = "raft_engine" +file_size = "128MB" +purge_threshold = "1GB" +purge_interval = "1m" +read_batch_size = 128 +sync_write = false +``` + +## 选项 + +如果你使用 Helm Chart 部署 GreptimeDB,可以参考[常见 Helm Chart 配置项](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md)了解如何通过注入配置文件以配置 Datanode。 + +| 配置项 | 描述 | 默认值 | +| ----------------- | ----------------------------------------------------------------------------------------------- | ----------------- | +| `provider` | WAL 的提供者。可选项:`raft_engine`(本地文件系统存储)、`kafka`(使用 Kafka 的远程 WAL 存储)或 `noop`(无操作 WAL 提供者) | `"raft_engine"` | +| `dir` | 日志写入目录 | `{data_home}/wal` | +| `file_size` | 单个 WAL 日志文件的大小 | `128MB` | +| `purge_threshold` | 触发清理的 WAL 总大小阈值 | `1GB` | +| `purge_interval` | 触发清理的时间间隔 | `1m` | +| `read_batch_size` | 读取批次大小 | `128` | +| `sync_write` | 是否在每次写入日志时调用 fsync | `false` | + +## 最佳实践 + +### 使用单独的高性能卷作为 WAL 目录 +在部署 GreptimeDB 时,配置单独的卷作为 WAL 目录具有显著优势。这样做可以: + + +- 使用高性能磁盘——包括专用物理卷或自定义的高性能 `StorageClass`,以提升 WAL 的写入吞吐量。 +- 隔离 WAL I/O 与缓存文件访问,降低 I/O 竞争,提升整体系统性能。 + + +如果你使用 Helm Chart 部署 GreptimeDB,可以参考[常见 Helm Chart 配置项](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md)了解如何配置专用 WAL 卷。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/noop-wal.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/noop-wal.md new file mode 100644 index 0000000000..1953f2a198 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/noop-wal.md @@ -0,0 +1,41 @@ +--- +keywords: [配置, Noop WAL, GreptimeDB Datanode, GreptimeDB, 集群模式] +description: 介绍如何在集群模式下为 GreptimeDB Datanode 组件配置 Noop WAL。 +--- +# Noop WAL + +Noop WAL 是一种特殊的 WAL 提供者,用于 WAL 暂时不可用时的紧急情况。它不会存储任何 WAL 数据。 + +## 可用性 + +Noop WAL **仅在集群模式下可用**,单机模式不支持。 + +## 使用场景 + +- **WAL 暂时不可用**:当 WAL 提供者(如 Kafka)暂时不可用时,可以将 Datanode 切换到 Noop WAL 保持集群运行。 +- **测试和开发**:适用于不需要 WAL 持久化的测试场景。 + +## 数据丢失警告 + +**使用 Noop WAL 时,Datanode 关闭或重启会导致所有未刷新的数据丢失。** 仅应在 WAL 提供者不可用时临时使用,不建议用于生产环境,除非是紧急情况。 + +## 配置 + +为 Datanode 配置 Noop WAL: + +```toml +[wal] +provider = "noop" +``` + +在 GreptimeDB 集群中,WAL 配置分为两部分: + +- **Metasrv** - 负责为新 Region 生成 WAL 元数据,应配置为 `raft_engine` 或 `kafka`。 +- **Datanode** - 负责 WAL 数据读写,可在 WAL 提供者不可用时配置为 `noop`。 + +注意:Noop WAL 只能配置在 Datanode 上,Metasrv 不支持。使用 Noop WAL 时,Metasrv 仍使用原配置的 WAL 提供者。 + +## 最佳实践 + +- 定期使用 `admin flush_table()` 或 `admin flush_region()` 刷新 Region,减少数据丢失。 +- WAL 提供者恢复后,尽快切换回正常配置。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/overview.md new file mode 100644 index 0000000000..4cdd37ea8c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/overview.md @@ -0,0 +1,60 @@ +--- +keywords: [WAL, 预写日志, 本地 WAL, Remote WAL, GreptimeDB] +description: 介绍 GreptimeDB 中的 WAL(预写日志),包括本地 WAL 和远程 WAL 的优缺点。 +--- +# 概述 + +[预写日志](/contributor-guide/datanode/wal.md#introduction)(WAL) 是 GreptimeDB 的关键组件之一,负责持久化记录每次数据修改操作,以确保内存中的数据在故障发生时不会丢失。GreptimeDB 支持三种 WAL 存储方案: + + +- **本地 WAL**: 使用嵌入式存储引擎 [raft-engine](https://github.com/tikv/raft-engine) ,直接集成在 [Datanode](/user-guide/concepts/why-greptimedb.md) 服务中。 + +- **Remote WAL**: 使用 [Apache Kafka](https://kafka.apache.org/) 作为外部的 WAL 存储组件。 + +- **Noop WAL**: 无操作 WAL 提供者,用于 WAL 暂时不可用的紧急情况,不存储任何数据。 + +## 本地 WAL + +### 优点 + +- **低延迟**: 本地 WAL 运行于 Datanode 进程内,避免了网络传输开销,提供更低的写入延迟。 + +- **易于部署**: 由于 WAL 与 Datanode 紧耦合,无需引入额外组件,部署和运维更加简便。 + +- **零 RPO**: 在云环境中部署 GreptimeDB 时,可以结合云存储服务(如 AWS EBS 或 GCP Persistent Disk)将 WAL 数据持久化存储,从而实现零[恢复点目标](https://en.wikipedia.org/wiki/Disaster_recovery#Recovery_Point_Objective) (RPO),即使发生故障也不会丢失任何已写入的数据。 + +### 缺点 + +- **高 RTO**: 由于 WAL 与 Datanode 紧密耦合,[恢复时间目标](https://en.wikipedia.org/wiki/Disaster_recovery#Recovery_Time_Objective) (RTO) 相对较高。在 Datanode 重启后,必须重放 WAL 以恢复最新数据,在此期间节点保持不可用。 + +- **单点访问限制**: 本地 WAL 与 Datanode 进程紧密耦合,仅支持单个消费者访问,限制了区域热备份和 [Region Migration](/user-guide/deployments-administration/manage-data/region-migration.md) 等功能的实现。 + +## Remote WAL + +### 优点 + +- **低 RTO**: 通过将 WAL 与 Datanode 解耦,[恢复时间目标](https://en.wikipedia.org/wiki/Disaster_recovery#Recovery_Time_Objective) (RTO) 得以最小化。当 Datanode 崩溃时,Metasrv 会发起 [Region Failover](/user-guide/deployments-administration/manage-data/region-failover.md) ,将受影响 Region 迁移至健康节点,无需本地重放 WAL。 + + +- **多消费者订阅**: Remote WAL 支持多个消费者同时订阅 WAL 日志,实现 Region 热备和 [Region Migration](/user-guide/deployments-administration/manage-data/region-migration.md) 等功能,提升系统的高可用性和灵活性。 + + +### 缺点 + +- **外部依赖**: Remote WAL 依赖外部 Kafka 集群,增加了部署和运维复杂度。 + +- **网络开销**: WAL 数据需通过网络传输,需合理规划集群网络带宽,确保低延迟与高吞吐量,尤其在写入密集型负载下。 + +## Noop WAL + +Noop WAL 是一种特殊的 WAL 提供者,用于 WAL 暂时不可用的紧急情况。它不会存储任何 WAL 数据,仅在集群模式下可用。 + +详细配置说明请参阅 [Noop WAL](/user-guide/deployments-administration/wal/noop-wal.md)。 + +## 后续步骤 + +- 如需配置本地 WAL 存储,请参阅[本地 WAL](/user-guide/deployments-administration/wal/local-wal.md)。 + +- 想了解更多 Remote WAL 相关信息,请参阅 [Remote WAL](/user-guide/deployments-administration/wal/remote-wal/configuration.md)。 + +- 想了解更多 Noop WAL 相关信息,请参阅 [Noop WAL](/user-guide/deployments-administration/wal/noop-wal.md)。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/configuration.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/configuration.md new file mode 100644 index 0000000000..2d316c18c4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/configuration.md @@ -0,0 +1,162 @@ +--- +keywords: [GreptimeDB Remote WAL, 配置, Kafka, Metasrv, Datanode, GreptimeDB] +description: 本节介绍如何配置 GreptimeDB 集群的 Remote WAL。 +--- +# 配置 + +GreptimeDB 支持使用 Kafka 实现 Remote WAL 存储。要启用 Remote WAL,需要分别配置 Metasrv 和 Datanode。 + +如果你使用 Helm Chart 部署 GreptimeDB,可以参考[常见 Helm Chart 配置项](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md)了解如何配置 Remote WAL。 + +## Metasrv 配置 + +Metasrv 负责 Kafka topics 的管理及过期 WAL 数据的自动清理。 + +```toml +[wal] +provider = "kafka" +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] + +# WAL 数据清理策略 +auto_prune_interval = "30m" +auto_prune_parallelism = 10 +flush_trigger_size = "512MB" +checkpoint_trigger_size = "128MB" + +# Topic 自动创建配置 +auto_create_topics = true +num_topics = 64 +replication_factor = 1 +topic_name_prefix = "greptimedb_wal_topic" +``` + +### 配置 + +| 配置项 | 说明 | +|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `provider` | 设置为 `"kafka"` 以启用 Remote WAL。 | +| `broker_endpoints` | Kafka broker 的地址列表。 | +| `auto_prune_interval` | 自动清理过期 WAL 的间隔时间,设为 `"0s"` 表示禁用。 | +| `auto_prune_parallelism` | 并发清理任务的最大数量。 | +| `auto_create_topics` | 是否自动创建 Kafka topic,设为 `false` 时需手动预创建。 | +| `num_topics` | 用于存储 WAL 的 Kafka topic 数量。 | +| `replication_factor` | 每个 topic 的副本数量。 | +| `topic_name_prefix` | Kafka topic 名称前缀,必须匹配正则 `[a-zA-Z_:-][a-zA-Z0-9_:\-\.@#]*`。 | +| `flush_trigger_size` | 触发 region flush 操作的预估大小阈值(如 `"512MB"`)。计算公式为 `(latest_entry_id - flushed_entry_id) * avg_record_size`。当此值超过 `flush_trigger_size` 时,MetaSrv 会触发 region flush 操作。设为 `"0"` 时由系统自动控制。该配置还可控制 region 重放期间从 topic 重放的最大数据量,较小的值有助于缩短 Datanode 启动时的重放时间。 | +| `checkpoint_trigger_size` | 触发 region checkpoint 操作的预估大小阈值(如 `"128MB"`)。计算公式为 `(latest_entry_id - last_checkpoint_entry_id) * avg_record_size`。当此值超过 `checkpoint_trigger_size` 时,MetaSrv 会启动检查点操作。设为 `"0"` 时由系统自动控制。较小的值有助于缩短 Datanode 启动时的重放时间。 | + +#### Kafka Topic 与权限要求 + +请确保以下设置正确,以保证 Remote WAL 正常运行: + +- 如果 `auto_create_topics = false`: + - 必须**在启动 Metasrv 之前**手动创建好所有 WAL topics; + - Topic 名称必须符合 `{topic_name_prefix}_{index}` 的格式,其中 index 的取值范围是 `0` 到 `{num_topics - 1}`。例如,默认前缀为 `greptimedb_wal_topic`,且 `num_topics = 64` 时,需要创建从 `greptimedb_wal_topic_0` 到 `greptimedb_wal_topic_63` 的 topic。 + - Topic 必须配置为支持**LZ4 压缩**。 +- Kafka 用户需具备以下权限: + - 对 topics 追加数据; + - 读取 topics 中数据; + - 删除 topics 中数据; + - 若启用自动创建(`auto_create_topics = true`),还需具备 创建 topic 的权限。 + +## Datanode 配置 + +Datanode 负责将数据写入 Kafka 并从中读取数据。 + +```toml +[wal] +provider = "kafka" +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] +max_batch_bytes = "1MB" +overwrite_entry_start_id = true +``` + +### 配置 + +| 配置项 | 说明 | +| -------------------------- | -------------------------------------------------------------------------------------------- | +| `provider` | 设置为 `"kafka"` 以启用 Remote WAL。 | +| `broker_endpoints` | Kafka broker 的地址列表。 | +| `max_batch_bytes` | 每个写入批次的最大大小,默认不能超过 Kafka 配置的单条消息上限(通常为 1MB)。 | +| `overwrite_entry_start_id` | 若设为 `true`,在 WAL 回放时跳过缺失的 entry,避免 out-of-range 错误(但可能掩盖数据丢失)。 | + + +#### 注意事项与限制 + +:::warning 重要:Kafka 保留策略配置 +请非常小心地配置 Kafka 保留策略以避免数据丢失。GreptimeDB 会自动回收不需要的 WAL 数据,因此在大多数情况下你不需要设置保留策略。但是如果你确实需要设置,请确保以下几点: + +- **基于大小的保留策略**:通常不需要设置,因为数据库会管理自己的数据生命周期 +- **基于时间的保留策略**:如果你选择设置此项,请确保保留时间**远大于自动刷新间隔** **(auto-flush-interval)** 以防止过早删除数据。 + +不当的保留设置可能导致数据丢失,如果 WAL 数据在 GreptimeDB 处理之前被删除。 +::: + +- 如果 `overwrite_entry_start_id = true`: + - 确保 Metasrv 中的 `auto_prune_interval` 已启用,以允许自动清理 WAL; + - Kafka topics 不应使用**基于大小保留策略**; + - 如果启用基于时间的保留策略,请确保保留时间**远大于自动刷新间隔(auto-flush-interval)**,至少是它的两倍。 + +- 确保 Datanode 使用的 Kafka 用户具有以下权限: + - 对 topics 追加数据; + - 读取 topics 中数据; +- 确保 `max_batch_bytes` 不超过 Kafka topic 的最大消息大小(通常为 1MB)。 + +## Kafka 认证配置 + +Kafka 的认证参数在 Metasrv 和 Datanode 的 `[wal]` 段中配置。 + +### SASL 认证 + +支持的 SASL 机制包括:`PLAIN`、`SCRAM-SHA-256` 和 `SCRAM-SHA-512`。 + +```toml +[wal] +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] + +[wal.sasl] +type = "SCRAM-SHA-512" +username = "user" +password = "secret" +``` + +### TLS + +要启用 TLS,可在 `[wal.tls]` 段进行配置,支持以下几种方式: + +#### 使用系统 CA 证书 + +无需提供证书路径,自动使用系统信任的 CA: + +```toml +[wal] +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] + +[wal.tls] +``` + +#### 使用自定义 CA 证书 + +用于 Kafka 集群使用私有 CA 的场景: + +```toml +[wal] +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] + +[wal.tls] +server_ca_cert_path = "/path/to/server.crt" +``` + +#### 使用双向 TLS(mTLS) + +同时提供客户端证书与私钥: + +```toml +[wal] +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] +[wal.tls] +server_ca_cert_path = "/path/to/server_cert" +client_cert_path = "/path/to/client_cert" +client_key_path = "/path/to/key" +``` + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/manage-kafka.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/manage-kafka.md new file mode 100644 index 0000000000..be88aba343 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/manage-kafka.md @@ -0,0 +1,110 @@ +--- +keywords: [Kafka, kubernetes, helm, GreptimeDB, remote WAL, 安装, 配置, 管理] +description: 本指南介绍如何安装和管理 Kafka 集群。 +--- + +# 管理 Kafka + +GreptimeDB 集群在启用 [Remote WAL](/user-guide/deployments-administration/wal/remote-wal/configuration.md) 时,会使用 Kafka 作为 WAL 存储。本文介绍如何部署和管理 Kafka 集群,使用的是 Bitnami 提供的 Kafka Helm [chart](https://github.com/bitnami/charts/tree/main/bitnami/kafka)。 + +## 先决条件 + +- [Kubernetes](https://kubernetes.io/docs/setup/) >= v1.23 +- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) >= v1.18.0 +- [Helm](https://helm.sh/docs/intro/install/) >= v3.0.0 + +## 安装 + +将以下内容保存为配置文件 `kafka.yaml`: + +```yaml +global: + security: + allowInsecureImages: true + +image: + registry: docker.io + repository: greptime/kafka + tag: 3.9.0-debian-12-r12 + +controller: + replicaCount: 3 + + resources: + requests: + cpu: 2 + memory: 2Gi + limits: + cpu: 2 + memory: 2Gi + + persistence: + enabled: true + size: 200Gi + +broker: + replicaCount: 3 + + resources: + requests: + cpu: 2 + memory: 2Gi + limits: + cpu: 2 + memory: 2Gi + + persistence: + enabled: true + size: 200Gi + +listeners: + client: + # 部署到生产环境时,通常会使用一个更安全的协议,例如 SASL。 + # 请参考 chart 的文档获取配置方法:https://artifacthub.io/packages/helm/bitnami/kafka#enable-security-for-kafka + # 此处为了例子的简单,我们使用 plaintext 协议(无权限验证)。 + protocol: plaintext +``` + +安装 Kafka 集群: + +```bash +helm upgrade --install kafka \ + oci://registry-1.docker.io/bitnamicharts/kafka \ + --values kafka.yaml \ + --version 32.4.3 \ + --create-namespace \ + -n kafka-cluster +``` + +等待 Kafka 集群启动完成: + +```bash +kubectl wait --for=condition=ready pod \ + -l app.kubernetes.io/instance=kafka \ + -n kafka-cluster +``` + + +```bash +kubectl get pods -n kafka-cluster +``` + +检查 Kafka 集群状态: + +```bash +kubectl get pods -n kafka-cluster +``` + + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +kafka-controller-0 1/1 Running 0 64s +kafka-controller-1 1/1 Running 0 64s +kafka-controller-2 1/1 Running 0 64s +kafka-broker-0 1/1 Running 0 63s +kafka-broker-1 1/1 Running 0 62s +kafka-broker-2 1/1 Running 0 61s +``` +
diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/flow-computation/continuous-aggregation.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/flow-computation/continuous-aggregation.md new file mode 100644 index 0000000000..7ccf01caaa --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/flow-computation/continuous-aggregation.md @@ -0,0 +1,556 @@ +--- +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 INDEX, + `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 语句中的 `EXPIRE AFTER '6h'` 参数确保 flow 计算仅使用过去 6 小时内的源数据。对于 sink 表中超过 6 小时的历史数据,本 flow 不会对其进行修改。有关`EXPIRE AFTER`的详细信息,请参阅[管理 Flow](manage-flow.md#expire-after) + +```sql +CREATE FLOW ngx_aggregation +SINK TO ngx_statistics +EXPIRE AFTER '6h' +COMMENT 'aggregate nginx access logs' +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('1 minutes'::INTERVAL, 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', now() - INTERVAL '1' minute), + ('ios', 'iOS', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 200, 500, 'agent', now() - INTERVAL '1' minute), + ('android', 'Android', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 200, 600, 'agent', now()), + ('ios', 'iOS', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 404, 700, 'agent', now()); +``` + +则 `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 | 2025-04-24 06:46:00 | 2025-04-24 06:47:06.680000 | +| 200 | 1 | 600 | 600 | 600 | 1 | 2025-04-24 06:47:00 | 2025-04-24 06:47:06.680000 | +| 404 | 1 | 700 | 700 | 700 | 1 | 2025-04-24 06:47:00 | 2025-04-24 06:47:06.680000 | ++--------+------------+----------+----------+----------+-----------------+---------------------+----------------------------+ +3 rows in set (0.01 sec) +``` + +尝试向 `ngx_access_log` 表中插入更多数据: + +```sql +INSERT INTO ngx_access_log +VALUES + ('android', 'Android', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 200, 500, 'agent', now()), + ('ios', 'iOS', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 404, 800, 'agent', now()); +``` + +结果表 `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 | 2025-04-24 06:46:00 | 2025-04-24 06:47:06.680000 | +| 200 | 2 | 500 | 600 | 550 | 1 | 2025-04-24 06:47:00 | 2025-04-24 06:47:21.720000 | +| 404 | 2 | 700 | 800 | 750 | 2 | 2025-04-24 06:47:00 | 2025-04-24 06:47:21.720000 | ++--------+------------+----------+----------+----------+-----------------+---------------------+----------------------------+ +3 rows in set (0.01 sec) +``` + +`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) +)WITH( + append_mode = 'true' +); + +/* 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 +EXPIRE AFTER '7days'::INTERVAL +COMMENT 'aggregate for distinct country' +AS +SELECT + DISTINCT country, + date_bin('1 hour'::INTERVAL, access_time) as time_window, +FROM ngx_access_log +GROUP BY + country, + time_window; +``` + +上述查询将 `ngx_access_log` 表中的数据聚合到 `ngx_country` 表中,它计算了每个时间窗口内的不同国家。 +`date_bin` 函数用于将数据聚合到一小时的间隔中。 +`ngx_country` 表将不断更新聚合数据,以监控访问系统的不同国家。`EXPIRE AFTER` 参数将确保流式处理流程自动忽略 `access_time` 超过 7 天的数据且不再参与 flow 计算,详见 请参阅[管理 Flow](manage-flow.md#expire-after) 中的说明。 + +你可以向 source 表 `ngx_access_log` 插入一些数据: + +```sql +INSERT INTO ngx_access_log VALUES + ('client1', 'US', now() - '2 hour'::INTERVAL), + ('client2', 'US', now() - '2 hour'::INTERVAL), + ('client3', 'UK', now() - '2 hour'::INTERVAL), + ('client4', 'UK', now() - '1 hour'::INTERVAL), + ('client5', 'CN', now() - '1 hour'::INTERVAL), + ('client6', 'CN', now() - '1 hour'::INTERVAL), + ('client7', 'JP', now()), + ('client8', 'JP', now()), + ('client9', 'KR', now()), + ('client10', 'KR', now()); +``` + +等待几秒钟,让 flow 将结果写入 sink 表,然后查询: + +```sql +select * from ngx_country; +``` + +```sql ++---------+---------------------+----------------------------+ +| country | time_window | update_at | ++---------+---------------------+----------------------------+ +| CN | 2025-04-24 05:00:00 | 2025-04-24 06:55:17.217000 | +| JP | 2025-04-24 06:00:00 | 2025-04-24 06:55:17.217000 | +| KR | 2025-04-24 06:00:00 | 2025-04-24 06:55:17.217000 | +| UK | 2025-04-24 04:00:00 | 2025-04-24 06:55:17.217000 | +| UK | 2025-04-24 05:00:00 | 2025-04-24 06:55:17.217000 | +| US | 2025-04-24 04:00:00 | 2025-04-24 06:55:17.217000 | ++---------+---------------------+----------------------------+ +``` + +## 实时监控示例 + +假设你有一个来自温度传感器网络的传感器事件流,你希望实时监控这些事件。 +传感器事件包含传感器 ID、温度读数、读数的时间戳和传感器的位置等信息。 +你希望不断聚合这些数据,以便在温度超过某个阈值时提供实时告警。持续聚合的查询如下: + +```sql +/* 创建 source 表 */ +CREATE TABLE temp_sensor_data ( + sensor_id INT, + loc STRING, + temperature DOUBLE, + ts TIMESTAMP TIME INDEX +)WITH( + append_mode = 'true' +); + +/* 创建 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 +EXPIRE AFTER '1h' +SINK TO temp_alerts +AS +SELECT + sensor_id, + loc, + max(temperature) as max_temp, + date_bin('10 seconds'::INTERVAL, 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` 表中的新行)。`EXPIRE AFTER '1h'` 使 flow 仅计算 `ts` 列处于 `(now - 1h, now)` 时间范围内的源数据,详见 [管理 Flow](manage-flow.md#expire-after) 中的说明。 + +现在我们已经创建了 flow 任务,可以向 source 表 `temp_sensor_data` 插入一些数据: + +```sql +INSERT INTO temp_sensor_data VALUES + (1, 'room1', 98.5, now() - '10 second'::INTERVAL), + (2, 'room2', 99.5, now()); +``` + +表现在应该是空的,等待几秒钟让 flow 将结果更新到输出表: + +```sql +SELECT * FROM temp_alerts; +``` + +```sql +Empty set (0.00 sec) +``` + +插入一些会触发警报的数据: + +```sql +INSERT INTO temp_sensor_data VALUES + (1, 'room1', 101.5, now()), + (2, 'room2', 102.5, now()); +``` + +等待几秒钟,让 flow 将结果更新到输出表: + +```sql +SELECT * FROM temp_alerts; +``` + +```sql ++-----------+-------+----------+---------------------+----------------------------+ +| sensor_id | loc | max_temp | time_window | update_at | ++-----------+-------+----------+---------------------+----------------------------+ +| 1 | room1 | 101.5 | 2025-04-24 06:58:20 | 2025-04-24 06:58:32.379000 | +| 2 | room2 | 102.5 | 2025-04-24 06:58:20 | 2025-04-24 06:58:32.379000 | ++-----------+-------+----------+---------------------+----------------------------+ +``` + +## 实时仪表盘 + +假设你需要一个条形图来显示每个状态码的包大小分布,以监控系统的健康状况。持续聚合的查询如下: + +```sql +/* 创建 source 表 */ +CREATE TABLE ngx_access_log ( + client STRING, + stat INT, + size INT, + access_time TIMESTAMP TIME INDEX +)WITH( + append_mode = 'true' +); +/* 创建 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 +EXPIRE AFTER '6h' +AS +SELECT + stat, + trunc(size, -1)::INT as bucket_size, + count(client) AS total_logs, + date_bin('1 minutes'::INTERVAL, 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` 表会不断更新, +提供每个状态代码的数据包大小分布的实时洞察。`EXPIRE AFTER '6h'` 使 flow 仅计算 `access_time` 列处于 `(now - 6h, now)` 时间范围内的源数据,详见 [管理 Flow](manage-flow.md#expire-after)。 + +现在我们已经创建了 flow 任务,可以向 source 表 `ngx_access_log` 插入一些数据: + +```sql +INSERT INTO ngx_access_log VALUES + ('cli1', 200, 100, now()), + ('cli2', 200, 104, now()), + ('cli3', 200, 120, now()), + ('cli4', 200, 124, now()), + ('cli5', 200, 140, now()), + ('cli6', 404, 144, now()), + ('cli7', 404, 160, now()), + ('cli8', 404, 164, now()), + ('cli9', 404, 180, now()), + ('cli10', 404, 184, now()); +``` + +等待几秒钟,让 flow 将结果更新到 sink 表: + +```sql +SELECT * FROM ngx_distribution; +``` + +```sql ++------+-------------+------------+---------------------+----------------------------+ +| stat | bucket_size | total_logs | time_window | update_at | ++------+-------------+------------+---------------------+----------------------------+ +| 200 | 100 | 2 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | +| 200 | 120 | 2 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | +| 200 | 140 | 1 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | +| 404 | 140 | 1 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | +| 404 | 160 | 2 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | +| 404 | 180 | 2 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | ++------+-------------+------------+---------------------+----------------------------+ +6 rows in set (0.00 sec) +``` + +## 将 TQL 与 Flow 结合使用进行高级时序分析 + +:::warning 实验性特性 +此实验性功能可能存在预期外的行为,其功能未来可能发生变化。 +::: + +TQL(时序查询语言)可以与 Flow 无缝集成,以执行高级时序计算,如速率计算、移动平均值和其他复杂的时间窗口操作。这种组合允许你创建连续聚合的 Flow,利用 TQL 强大的分析功能来获取实时洞察。 + + +### 理解 TQL Flow 组件 + +TQL 与 Flow 的集成提供了以下几个优势: + +1. **时间范围指定**:`EVAL (start_time, end_time, step)` 语法允许精确控制计算窗口,详见 [TQL](/reference/sql/tql.md)。 +2. **自动生成表结构**:GreptimeDB 根据 TQL 函数输出创建适当的 Sink 表。 +3. **连续处理**:结合 Flow 的调度,TQL 函数在传入数据上持续运行。 +4. **高级分析**:使用复杂的时序函数,如 `rate()`、`increase()` 和统计聚合。 + +### 设置 Source 表 + +首先,让我们创建一个 Source 表来存储 HTTP 请求指标: + +```sql +CREATE TABLE http_requests_total ( + host STRING, + job STRING, + instance STRING, + byte DOUBLE, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY (host, job, instance) +); +``` + +此表将作为基于 TQL 的 Flow 计算的数据源。`ts` 列作为时间索引, `byte` 表示想要分析的指标值。 + +### 创建速率计算 Flow + +现在我们将创建一个 Flow,它使用 TQL 来计算 `byte` 随时间的速率: + +```sql +CREATE FLOW calc_rate +SINK TO rate_reqs +EVAL INTERVAL '1m' AS +TQL EVAL (now() - '1m'::interval, now(), '30s') rate(http_requests_total{job="my_service"}[1m]); +``` + +此 Flow 定义包含几个关键组件: +- **EVAL INTERVAL '1m'**:每分钟执行 Flow 以进行连续更新。 +- **TQL EVAL**:指定从 1 分钟前到现在的时间范围进行评估,详见 [TQL](/reference/sql/tql.md)。 +- **rate()**:计算变化率的 TQL 函数。 +- **[1m]**:定义速率计算的 1 分钟回溯窗口。 + +### 检查生成的 Sink 表 + +你可以检查自动创建的 Sink 表结构: + +```sql +SHOW CREATE TABLE rate_reqs; +``` + +```sql ++-----------+-------------------------------------+ +| Table | Create Table | ++-----------+-------------------------------------+ +| rate_reqs | CREATE TABLE IF NOT EXISTS `rate_reqs` ( + `ts` TIMESTAMP(3) NOT NULL, + `prom_rate(ts_range,byte,ts,Int64(60000))` DOUBLE NULL, + `host` STRING NULL, + `job` STRING NULL, + `instance` STRING NULL, + TIME INDEX (`ts`), + PRIMARY KEY (`host`, `job`, `instance`) +) + +ENGINE=mito + | ++-----------+-------------------------------------+ +``` + +上述结果展示了 GreptimeDB 自动生成了用于存储 TQL 计算结果的合适 Schema,即创建一个与 PromQL 查询结果具有相同结构的表。 + +### 使用示例数据进行测试 + +现在可以插入一些测试数据,看看 Flow 的实际效果: + +```sql +INSERT INTO TABLE http_requests_total VALUES + ('localhost', 'my_service', 'instance1', 100, now() - INTERVAL '2' minute), + ('localhost', 'my_service', 'instance1', 200, now() - INTERVAL '1' minute), + ('remotehost', 'my_service', 'instance1', 300, now() - INTERVAL '30' second), + ('remotehost', 'their_service', 'instance1', 300, now() - INTERVAL '30' second), + ('localhost', 'my_service', 'instance1', 400, now()); +``` + +这将创建一个随时间递增的简单值序列,当由我们的 TQL Flow 处理时,将产生对应的速率结果。 + +### 触发 Flow 执行 + +要手动触发 Flow 计算并查看即时结果: + +```sql +ADMIN FLUSH_FLOW('calc_rate'); +``` + +此命令强制 Flow 立即处理所有可用数据,而不是等待下一个计划的间隔。 + +### 验证结果 + +最后,验证 Flow 是否已成功处理数据: + +```sql +SELECT count(*) > 0 FROM rate_reqs; +``` + +```sql ++---------------------+ +| count(*) > Int64(0) | ++---------------------+ +| true | ++---------------------+ +``` + +此查询确认速率计算的 FLow 已产生结果并将结果写入了 Sink 表。 + +你还可以查询实际计算出的速率值: + +```sql +SELECT * FROM rate_reqs; +``` + +```sql ++---------------------+------------------------------------------+-----------+------------+-----------+ +| ts | prom_rate(ts_range,byte,ts,Int64(60000)) | host | job | instance | ++---------------------+------------------------------------------+-----------+------------+-----------+ +| 2025-09-01 13:14:34 | 4.166666666666666 | localhost | my_service | instance1 | +| 2025-09-01 13:15:04 | 4.444444444444444 | localhost | my_service | instance1 | ++---------------------+------------------------------------------+-----------+------------+-----------+ +2 rows in set (0.03 sec) +``` + +请注意,时间戳和确切的速率值可能会因你运行示例的时间而不同,但此示例的速率计算是相同的。 + +### 清理 + +完成实验后,清理资源: + +```sql +DROP FLOW calc_rate; +DROP TABLE http_requests; +DROP TABLE rate_reqs; +``` + +## 下一步 + +- [管理 Flow](manage-flow.md):深入了解 Flow 引擎的机制和定义 Flow 的 SQL 语法。 +- [表达式](expressions.md):了解 Flow 引擎支持的数据转换表达式。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/flow-computation/expressions.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/flow-computation/expressions.md new file mode 100644 index 0000000000..7621d45d4b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/flow-computation/expressions.md @@ -0,0 +1,22 @@ +--- +keywords: [聚合函数, 标量函数, count, sum, avg, min, max, date_bin, date_trunc, trunc] +description: 列出了 GreptimeDB 中 flow 支持的聚合函数和标量函数。 +--- + +# 表达式 + +## 聚合函数 + +Flow 支持标准 SQL 查询所支持的所有聚合函数,例如 `COUNT`、`SUM`、`MIN`、`MAX` 等。 + +有关详细的函数列表,请参阅 [聚合函数](/reference/sql/functions/df-functions.md#aggregate-functions)。 + +## 标量函数 + +Flow 支持标准 SQL 查询所支持的所有标量函数,详见我们的 [SQL 参考](/reference/sql/functions/overview.md)。 + +以下是一些 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-1.0/user-guide/flow-computation/manage-flow.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/flow-computation/manage-flow.md new file mode 100644 index 0000000000..8c64873756 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/flow-computation/manage-flow.md @@ -0,0 +1,222 @@ +--- +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('10 seconds'::INTERVAL, 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('10 seconds'::INTERVAL, 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 '1 hour'::INTERVAL +COMMENT 'My first flow in GreptimeDB' +AS +SELECT + max(temperature) as max_temp, + date_bin('10 seconds'::INTERVAL, 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 引擎中过期的时间间隔。 + +source 表中超出指定过期时间的数据将不再被包含在 flow 的计算范围内。 +同理,sink 表中超过过期时间的历史数据也不会被更新。 +这意味着 flow 引擎在聚合计算时会自动忽略早于该时间间隔的数据。这一机制有助于管理有状态查询(例如涉及 `GROUP BY` 的查询)的状态存储规模。 + +需特别注意的是: +- `EXPIRE AFTER` 子句**不会删除** source 表或 sink 表中的数据,它仅控制 flow 引擎对数据的处理范围 +- 若需删除表数据,请在创建表时通过 [`TTL` 策略](/user-guide/manage-data/overview.md#使用-ttl-策略保留数据)实现 + +为 `EXPIRE AFTER` 设置合理的时间间隔,可有效限制 flow 的状态存储规模并避免内存溢出。该机制与流处理中的 ["水位线"](https://docs.risingwave.com/processing/watermarks) 概念有相似之处——两者均通过时间边界定义计算的有效数据范围,过期数据将不再参与流式计算过程。 + +例如,如果 flow 引擎在 10:00:00 处理聚合,并且设置了 `'1 hour'::INTERVAL`, +当前时刻若输入数据的 Time Index 超过 1 小时(即早于 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('10 seconds'::INTERVAL, ts) as time_window +FROM temp_sensor_data +GROUP BY time_window; +``` + +在此示例中,`date_bin('10 seconds'::INTERVAL, ts)` 函数创建从 UTC 00:00:00 开始的 10 秒时间窗口。 +`max(temperature)` 函数计算每个时间窗口内的最大温度值。 + +有关该函数行为的更多详细信息, +请参阅 [`date_bin`](/reference/sql/functions/df-functions.md#date_bin)。 + +:::tip 提示 +目前,flow 依赖时间窗口表达式来确定如何增量更新结果。因此,建议尽可能使用相对较小的时间窗口。 +::: + +## 刷新 flow + +当 source 表中有新数据到达时,flow 引擎会在短时间内(比如数秒)自动处理聚合操作。 +但你依然可以使用 `ADMIN FLUSH_FLOW` 命令手动触发 flow 引擎立即执行聚合操作。 + +```sql +ADMIN FLUSH_FLOW('') +``` + +## 删除 flow + +请使用以下 `DROP FLOW` 子句删除 flow: + +```sql +DROP FLOW [IF EXISTS] +``` + +例如: + +```sql +DROP FLOW IF EXISTS my_flow; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/flow-computation/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/flow-computation/overview.md new file mode 100644 index 0000000000..07c30219b5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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_http_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` 以计算 `ngx_http_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_http_log +GROUP BY + user_agent; +``` + +一旦创建了 Flow, +Flow 引擎将持续处理 `nginx_access_log` 表中的数据,并使用计算结果更新 `user_agent_statistics` 表。 + +要观察 Flow 的结果, +将示例数据插入 `nginx_access_log` 表。 + +```sql +INSERT INTO ngx_http_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-1.0/user-guide/ingest-data/for-iot/emqx.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/emqx.md new file mode 100644 index 0000000000..0faab54160 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/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-1.0/user-guide/ingest-data/for-iot/grpc-sdks/go.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/go.md new file mode 100644 index 0000000000..ac2499f009 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/go.md @@ -0,0 +1,310 @@ +--- +keywords: [Go SDK, 数据写入, 安装 SDK, 连接数据库, 插入数据, 调试日志, 并发安全] +description: 介绍如何使用 GreptimeDB 提供的 Go Ingest SDK 写入数据,包括安装、连接、插入数据和调试日志等内容。 +--- + +# Go + +GreptimeDB 提供了用于高吞吐量数据写入的 ingester 库。 +它使用 gRPC 协议,支持自动生成表结构,无需在写入数据前创建表。 +更多信息请参考 [自动生成表结构](/user-guide/ingest-data/overview.md#自动生成表结构)。 + +GreptimeDB 提供的 Go Ingest SDK 是一个轻量级、并发安全的库,使用起来非常简单。 + +## 快速开始 Demo + +你可以通过 [快速开始 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@VAR::goSdkVersion +``` + +引入到代码中: + +```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" +) +``` + +## 连接数据库 + +如果你在启动 GreptimeDB 时设置了 [`--user-provider`](/user-guide/deployments-administration/authentication/overview.md), +则需要提供用户名和密码才能连接到 GreptimeDB。 +以下示例显示了使用 SDK 连接到 GreptimeDB 时如何设置用户名和密码。 + +```go +cfg := greptime.NewConfig("127.0.0.1"). + // 将数据库名称更改为你的数据库名称 + WithDatabase("public"). + // 默认端口 4001 + // WithPort(4001). + // 如果服务配置了 TLS,设置 TLS 选项来启用安全连接 + // WithInsecure(false). + // 设置鉴权信息 + // 如果数据库不需要鉴权,移除 WithAuth 方法即可 + WithAuth("username", "password") + +cli, _ := greptime.NewClient(cfg) +defer cli.Close() +``` + +## 数据模型 + +表中的每条行数据包含三种类型的列:`Tag`、`Timestamp` 和 `Field`。更多信息请参考 [数据模型](/user-guide/concepts/data-model.md)。 +列值的类型可以是 `String`、`Float`、`Int`、`JSON`, `Timestamp` 等。更多信息请参考 [数据类型](/reference/sql/data-types.md)。 + +## 设置表选项 + +虽然在通过 SDK 向 GreptimeDB 写入数据时会自动创建时间序列表,但你仍然可以配置表选项。 +SDK 支持以下表选项: + +- `auto_create_table`:默认值为 `True`。如果设置为 `False`,则表示表已经存在且不需要自动创建,这可以提高写入性能。 +- `ttl`、`append_mode`、`merge_mode`:更多详情请参考[表选项](/reference/sql/create.md#table-options)。 + +你可以使用 `ingesterContext` 设置表选项。 +例如设置 `ttl` 选项: + +```go +hints := []*ingesterContext.Hint{ + { + Key: "ttl", + Value: "3d", + }, +} + +ctx, cancel := context.WithTimeout(context.Background(), time.Second*3) +ctx = ingesterContext.New(ctx, ingesterContext.WithHint(hints)) +// 使用 ingesterContext 写入数据到 GreptimeDB +// `data` 对象在之后的章节中描述 +resp, err := cli.Write(ctx, data) +if err != nil { + return err +} +``` + +关于如何向 GreptimeDB 写入数据,请参考以下各节。 + +## 低级 API + +GreptimeDB 的低级 API 通过向具有预定义模式的 `table` 对象添加 `row` 来写入数据。 + +### 创建行数据 + +以下代码片段首先构建了一个名为 `cpu_metric` 的表,其中包括 `host`、`cpu_user`、`cpu_sys` 和 `ts` 列。 +随后,它向表中插入了一行数据。 + +该表包含三种类型的列: + +- `Tag`:`host` 列,值类型为 `String`。 +- `Field`:`cpu_user` 和 `cpu_sys` 列,值类型为 `Float`。 +- `Timestamp`:`ts` 列,值类型为 `Timestamp`。 + +```go +// 为 CPU 指标构建表结构 +cpuMetric, err := table.New("cpu_metric") +if err != nil { + // 处理错误 +} + +// 添加一个 'Tag' 列,用于主机标识符 +cpuMetric.AddTagColumn("host", types.STRING) +// 添加一个 'Timestamp' 列,用于记录数据收集的时间 +cpuMetric.AddTimestampColumn("ts", types.TIMESTAMP_MILLISECOND) +// 添加 'Field' 列,用于测量用户和系统 CPU 使用率 +cpuMetric.AddFieldColumn("cpu_user", types.FLOAT) +cpuMetric.AddFieldColumn("cpu_sys", types.FLOAT) + +// 插入示例数据 +// 注意:参数必须按照定义的表结构中的列的顺序排列:host, ts, cpu_user, cpu_sys +err = cpuMetric.AddRow("127.0.0.1", time.Now(), 0.1, 0.12) +err = cpuMetric.AddRow("127.0.0.1", time.Now(), 0.11, 0.13) +if err != nil { + // 处理错误 +} + +``` + +为了提高写入数据的效率,你可以一次创建多行数据以便写入到 GreptimeDB。 + +```go +cpuMetric, err := table.New("cpu_metric") +if err != nil { + // 处理错误 +} +cpuMetric.AddTagColumn("host", types.STRING) +cpuMetric.AddTimestampColumn("ts", types.TIMESTAMP_MILLISECOND) +cpuMetric.AddFieldColumn("cpu_user", types.FLOAT) +cpuMetric.AddFieldColumn("cpu_sys", types.FLOAT) +err = cpuMetric.AddRow("127.0.0.1", time.Now(), 0.1, 0.12) +if err != nil { + // 处理错误 +} + +memMetric, err := table.New("mem_metric") +if err != nil { + // 处理错误 +} +memMetric.AddTagColumn("host", types.STRING) +memMetric.AddTimestampColumn("ts", types.TIMESTAMP_MILLISECOND) +memMetric.AddFieldColumn("mem_usage", types.FLOAT) +err = memMetric.AddRow("127.0.0.1", time.Now(), 112) +if err != nil { + // 处理错误 +} +``` + +### 插入数据 + +下方示例展示了如何向 GreptimeDB 的表中插入行数据。 + +```go +resp, err := cli.Write(context.Background(), cpuMetric, memMetric) +if err != nil { + // 处理错误 +} +log.Printf("affected rows: %d\n", resp.GetAffectedRows().GetValue()) +``` + +### 流式插入 + +当你需要插入大量数据时,例如导入历史数据,流式插入是非常有用的。 + +```go +err := cli.StreamWrite(context.Background(), cpuMetric, memMetric) +if err != nil { + // 处理错误 +} +``` + +在所有数据写入完毕后关闭流式写入。 +一般情况下,连续写入数据时不需要关闭流式写入。 + +```go +affected, err := cli.CloseStream(ctx) +``` + +## 高级 API + +SDK 的高级 API 使用 ORM 风格的对象写入数据, +它允许你以更面向对象的方式创建、插入和更新数据,为开发者提供了更友好的体验。 +然而,高级 API 不如低级 API 高效。 +这是因为 ORM 风格的对象在转换对象时可能会消耗更多的资源和时间。 + +### 创建行数据 + +```go +type CpuMetric struct { + Host string `greptime:"tag;column:host;type:string"` + CpuUser float64 `greptime:"field;column:cpu_user;type:float64"` + CpuSys float64 `greptime:"field;column:cpu_sys;type:float64"` + Ts time.Time `greptime:"timestamp;column:ts;type:timestamp;precision:millisecond"` +} + +func (CpuMetric) TableName() string { + return "cpu_metric" +} + +cpuMetrics := []CpuMetric{ + { + Host: "127.0.0.1", + CpuUser: 0.10, + CpuSys: 0.12, + Ts: time.Now(), + } +} +``` + +### 插入数据 + + +```go +resp, err := cli.WriteObject(context.Background(), cpuMetrics) +log.Printf("affected rows: %d\n", resp.GetAffectedRows().GetValue()) +``` + +### 流式插入 + +当你需要插入大量数据时,例如导入历史数据,流式插入是非常有用的。 + +```go +err := streamClient.StreamWriteObject(context.Background(), cpuMetrics, memMetrics) +``` + +在所有数据写入完毕后关闭流式写入。 +一般情况下,连续写入数据时不需要关闭流式写入。 + +```go +affected, err := cli.CloseStream(ctx) +``` + +## 插入 JSON 类型的数据 + +GreptimeDB 支持使用 [JSON 类型数据](/reference/sql/data-types.md#json-类型) 存储复杂的数据结构。 +使用此 ingester 库,你可以通过字符串值插入 JSON 数据。 +假如你有一个名为 `sensor_readings` 的表,并希望添加一个名为 `attributes` 的 JSON 列, +请参考以下代码片段。 + +在 [低级 API](#低级-api) 中, +你可以使用 `AddFieldColumn` 方法将列类型指定为 `types.JSON` 来添加 JSON 列。 +然后使用 `struct` 或 `map` 插入 JSON 数据。 + +```go +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) + +// 以下省略了写入数据的代码 +// ... +``` + +在 [高级 API](#高级-api) 中,你可以使用 `greptime:"field;column:details;type:json"` 标签将列类型指定为 JSON。 + +```go +type SensorReadings struct { + // 此处省略了创建其他列的代码 + // ... + // 将列类型指定为 JSON + Attributes string `greptime:"field;column:details;type:json"` + // ... +} + +// 使用 struct 插入 JSON 数据 +type Attributes struct { + Location string `json:"location"` + Action string `json:"action"` +} +attributes := Attributes{ Action: "running" } +sensor := SensorReadings{ + // ... + Attributes: attributes, +} + +// 以下省略了写入数据的代码 +// ... +``` + +请参考 SDK 仓库中的 [示例](https://github.com/GreptimeTeam/greptimedb-ingester-go/tree/main/examples/jsondata) 获取插入 JSON 数据的可执行代码。 + +## Ingester 库参考 + +- [API 文档](https://pkg.go.dev/github.com/GreptimeTeam/greptimedb-ingester-go) + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/java.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/java.md new file mode 100644 index 0000000000..621cb5cb6c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/java.md @@ -0,0 +1,486 @@ +--- +keywords: [Java SDK, 数据写入, 安装 JDK, 连接数据库, 插入数据, 调试日志, 性能指标] +description: 介绍如何使用 GreptimeDB 提供的 Java ingester SDK 写入数据,包括安装、连接、插入数据和调试日志等内容。 +--- + +# Java Ingester for GreptimeDB + +GreptimeDB 提供了用于高吞吐量数据写入的 ingester 库。 +它使用 gRPC 协议,支持无 schema 写入,无需在写入数据前创建表。 +更多信息请参考 [自动生成表结构](/user-guide/ingest-data/overview.md#自动生成表结构)。 + +GreptimeDB 提供的 Java ingester SDK 是一个轻量级、高性能的客户端,专为高效的时间序列数据写入而设计。它利用 gRPC 协议提供非阻塞、纯异步的 API,在保持与应用程序无缝集成的同时提供高吞吐数据写入。 + +该客户端提供针对各种性能要求和使用场景优化的多种写入方法。你可以选择最适合你特定需求的方法——无论你需要低延迟操作的简单一元写入,还是处理大量时间序列数据时最大效率的高吞吐量批量流式传输。 + +## 架构 + +``` ++-----------------------------------+ +| Client Applications | +| +------------------+ | +| | Application Code | | +| +------------------+ | ++-------------+---------------------+ + | + v ++-------------+---------------------+ +| API Layer | +| +---------------+ | +| | GreptimeDB | | +| +---------------+ | +| / \ | +| v v | +| +-------------+ +-------------+ | +------------------+ +| | BulkWrite | | Write | | | Data Model | +| | Interface | | Interface | |------->| | +| +-------------+ +-------------+ | | +------------+ | ++-------|----------------|----------+ | | Table | | + | | | +------------+ | + v v | | | ++-------|----------------|----------+ | v | +| Transport Layer | | +------------+ | +| +-------------+ +-------------+ | | | TableSchema| | +| | BulkWrite | | Write | | | +------------+ | +| | Client | | Client | | +------------------+ +| +-------------+ +-------------+ | +| | \ / | | +| | \ / | | +| | v v | | +| | +-------------+ | | +| | |RouterClient | | | ++-----|--+-------------|---+--------+ + | | | | + | | | | + v v v | ++-----|----------------|---|--------+ +| Network Layer | +| +-------------+ +-------------+ | +| | Arrow Flight| | gRPC Client | | +| | Client | | | | +| +-------------+ +-------------+ | +| | | | ++-----|----------------|------------+ + | | + v v + +-------------------------+ + | GreptimeDB Server | + +-------------------------+ +``` + +- **API Layer**:为客户端应用程序提供与 GreptimeDB 交互的上层接口 +- **Data Model**:定义时间序列数据的结构和组织,包括表和 schemas +- **Transport Layer**:处理通信逻辑、请求路由和客户端管理 +- **Network Layer**:使用 Arrow Flight 和 gRPC 底层协议通信 + +## 使用方法 + +### 安装 + +1. 安装 Java 开发工具包(JDK) + +确保你的系统已安装 JDK 8 或更高版本。有关如何检查 Java 版本并安装 JDK 的更多信息,请参见 [Oracle JDK 安装概述文档](https://www.oracle.com/java/technologies/javase-downloads.html) + +2. 将 GreptimeDB Java SDK 添加为依赖项 + +如果你使用的是 [Maven](https://maven.apache.org/),请将以下内容添加到 pom.xml 的依赖项列表中: + +```xml + + io.greptime + ingester-all + VAR::javaSdkVersion + +``` + +最新版本可以在 [这里](https://central.sonatype.com/search?q=io.greptime&name=ingester-all) 查看。 + +配置依赖项后,请确保它们对项目可用。这可能需要在 IDE 中刷新项目或运行依赖项管理器。 + +### 客户端初始化 + +GreptimeDB Ingester Java 客户端的入口点是 `GreptimeDB` 类。你可以通过调用静态创建方法并传入适当的配置选项来创建客户端实例。 + +```java +// GreptimeDB 在默认目录 "greptime" 中有一个名为 "public" 的默认数据库, +// 我们可以将其用作测试数据库 +String database = "public"; +// 默认情况下,GreptimeDB 使用 gRPC 协议在端口 4001 上监听。 +// 我们可以提供多个指向同一 GreptimeDB 集群的端点。 +// 客户端将基于负载均衡策略调用这些端点。 +// 客户端执行定期健康检查并自动将请求路由到健康节点, +// 为你的应用程序提供容错能力和改进的可靠性。 +String[] endpoints = {"127.0.0.1:4001"}; +// 设置认证信息。 +AuthInfo authInfo = new AuthInfo("username", "password"); +GreptimeOptions opts = GreptimeOptions.newBuilder(endpoints, database) + // 如果数据库不需要认证,我们可以使用 `AuthInfo.noAuthorization()` 作为参数。 + .authInfo(authInfo) + // 如果你的服务器由 TLS 保护,请启用安全连接 + //.tlsOptions(new TlsOptions()) + // 好的开始 ^_^ + .build(); + +// 初始化客户端 +// 注意:客户端实例是线程安全的,应作为全局单例重用 +// 以获得更好的性能和资源利用率。 +GreptimeDB client = GreptimeDB.create(opts); +``` + +### 写入数据 + +Ingester 通过 `Table` 抽象为写入数据到 GreptimeDB 提供了统一的方法。所有数据写入操作,包括高级 API,都建立在这个基础结构之上。要写入数据,你需要创建一个 `Table` 为其填充时间序列数据,最后将其写入数据库。 + +#### 创建和写入表 + +定义表结构并创建表: + +```java +// 创建表结构 +TableSchema schema = TableSchema.newBuilder("metrics") + .addTag("host", DataType.String) + .addTag("region", DataType.String) + .addField("cpu_util", DataType.Float64) + .addField("memory_util", DataType.Float64) + .addTimestamp("ts", DataType.TimestampMillisecond) + .build(); + +// 从 schema 创建表数据容器 +Table table = Table.from(schema); + +// 向表中添加行 +// 值必须按照结构中定义的顺序提供 +// 在这种情况下:addRow(host, region, cpu_util, memory_util, ts) +table.addRow("host1", "us-west-1", 0.42, 0.78, System.currentTimeMillis()); +table.addRow("host2", "us-west-2", 0.46, 0.66, System.currentTimeMillis()); +// 添加更多行 +// .. + +// 把表标记为完成以使其不可变。这将最终确定表的数据内容以进行写入。 +// 如果你忘记了调用此方法,它将在表数据写入前自动在内部调用 +table.complete(); + +// 写入数据库 +CompletableFuture> future = client.write(table); +``` + +GreptimeDB 支持使用 [JSON 类型数据](/reference/sql/data-types.md#json-类型) 存储复杂的数据结构。你可以在表结构中定义 JSON 列,并使用 Map 对象插入数据: + +```java +// 为 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); +``` + +##### TableSchema + +`TableSchema` 定义了写入数据到 GreptimeDB 的结构。它指定表结构,包括列名、语义类型和数据类型。有关列语义类型(`Tag`、`Timestamp`、`Field`)的详细信息,请参考 [数据模型](/user-guide/concepts/data-model.md) 文档。 + +##### Table + +`Table` 接口表示可以写入到 GreptimeDB 的数据。它提供添加行和操作数据的方法。本质上,`Table` 将数据临时存储在内存中,允许你在将数据发送到数据库之前累积多行进行批处理,这比写入单个行显著提高了写入效率。 + +表经历几个不同的生命周期阶段: + +1. **创建**:使用 `Table.from(schema)` 从 schema 初始化表 +2. **数据添加**:使用 `addRow()` 方法用行填充表 +3. **完成**:添加所有行后使用 `complete()` 冻结表不允许再修改 +4. **写入**:将完成的表发送到数据库 + +重要提醒: +- 表不是线程安全的,应该单线程访问 +- 写入后不能重用表 - 需要为每个写入操作创建新实例 +- 关联的 `TableSchema` 是不可变的,可以在多个操作中安全地复用 + +### 写入操作 + +虽然在通过 SDK 向 GreptimeDB 写入数据时会自动创建时间序列表, +但你仍然可以配置表选项。 +SDK 支持以下表选项: + +- `auto_create_table`:默认为 `True`。如果设置为 `False`,表示表已经存在且不需要自动创建,这可以提高写入性能。 +- `ttl`、`append_mode`、`merge_mode`:更多详情请参考 [表选项](/reference/sql/create.md#table-options)。 + +你可以使用 `Context` 设置表选项。 +例如,要设置 `ttl` 选项,请使用以下代码: + +```java +Context ctx = Context.newDefault(); +// 添加提示使数据库创建具有指定 TTL(生存时间)的表 +ctx = ctx.withHint("ttl", "3d"); +// 将压缩算法设置为 Zstd。 +ctx = ctx.withCompression(Compression.Zstd); +// 写入数据到 GreptimeDB 时使用 ctx +CompletableFuture> future = client.write(Arrays.asList(table1, table2), WriteOp.Insert, ctx); +``` + +有关如何向 GreptimeDB 写入数据,请参阅以下部分。 + +### 批量写入 + +批量写入允许你在单个请求中向多个表写入数据。它返回 `CompletableFuture>` 是一个典型的异步编程方式。 + +对于大多数使用场景,这是向 GreptimeDB 写入数据的推荐方式。 + +```java +// 批量写入 API +CompletableFuture> future = client.write(table1, table2, table3); + +// 出于性能考虑,SDK 被设计为纯异步的。 +// 返回值是一个 CompletableFuture 对象。如果你想立即获取 +// 结果,可以调用 `future.get()`,这将阻塞直到操作完成。 +// 对于生产环境,建议使用回调或 +// CompletableFuture API 等非阻塞方法。 +Result result = future.get(); +``` + +### 流式写入 + +流式写入 API 维护到 GreptimeDB 的持久连接,以便进行具有速率限制的连续数据写入。它允许通过单个流向多个表写入数据。 + +以下场景推荐使用此 API: +- 中小规模的连续数据收集 +- 通过一个连接管道写入多个表的数据 +- 简单性和便利性比最大吞吐量更重要的情况 + +```java +// 创建流写入器 +StreamWriter writer = client.streamWriter(); + +// 写入多个表 +writer.write(table1) + .write(table2) + .write(table3); + +// 完成流并获取结果 +CompletableFuture result = writer.completed(); +``` + +你还可以为流式写入设置速率限制: + +```java +// 限制为每秒 1000 个数据点 +StreamWriter writer = client.streamWriter(1000); +``` + +### Bulk 写入 + +Bulk 写入 API 提供了一种高性能、内存高效的机制,用于将大量时间序列数据写入到 GreptimeDB 中。它利用堆外内存管理,在写入大批量数据时实现最佳吞吐量。 + +**重要说明**: +1. **需要手动创建表**:Bulk API **不会**自动创建表。你必须事先创建表,使用以下方法之一: + - 常规写入 API(支持自动创建表),或 + - SQL DDL 语句(CREATE TABLE) +2. **Schema 匹配**:Bulk API 中的表模板必须与现有表结构完全匹配。 +3. **列类型**:对于 Bulk API,目前要求使用 `addField()` 而不是 `addTag()`。`Tag` 列是 GreptimeDB 中主键的一部分,但 Bulk API 尚不支持带有 `Tag` 列的表。此限制将在未来版本中得到解决。 + +此 API 仅支持每个流写入一个表,并处理大数据量(每次写入可高达 200MB+),具有自适应流量控制。性能优势包括: +- 使用 Arrow 缓冲区的堆外内存管理减少不必要的内置拷贝 +- 高效的二进制序列化和数据传输 +- 可选压缩选项 +- 批量操作 + +此方法特别适用于: +- 大规模批处理和数据迁移 +- 高吞吐量日志和传感器数据写入 +- 具有苛刻性能要求的时间序列应用程序 +- 处理高频数据收集的系统 + +以下是使用批处理写入 API 的典型模式: + +```java +// 使用表结构创建 BulkStreamWriter +try (BulkStreamWriter writer = greptimeDB.bulkStreamWriter(schema)) { + // 写入多个批次 + for (int batch = 0; batch < batchCount; batch++) { + // 为此批次获取 TableBufferRoot + Table.TableBufferRoot table = writer.tableBufferRoot(1000); // 列缓冲区大小 + + // 向批次添加行 + for (int row = 0; row < rowsPerBatch; row++) { + Object[] rowData = generateRow(batch, row); + table.addRow(rowData); + } + + // 完成表以准备传输 + table.complete(); + + // 发送批次并获取完成的 future + CompletableFuture future = writer.writeNext(); + + // 等待批次被处理(可选) + Integer affectedRows = future.get(); + + System.out.println("Batch " + batch + " wrote " + affectedRows + " rows"); + } + + // 发出流完成信号 + writer.completed(); +} +``` + +#### 配置 + +可以使用多个选项配置 Bulk API 以优化性能: + +```java +BulkWrite.Config cfg = BulkWrite.Config.newBuilder() + .allocatorInitReservation(64 * 1024 * 1024L) // 自定义内存分配:64MB 初始保留 + .allocatorMaxAllocation(4 * 1024 * 1024 * 1024L) // 自定义内存分配:4GB 最大分配 + .timeoutMsPerMessage(60 * 1000) // 每个请求 60 秒超时 + .maxRequestsInFlight(8) // 并发控制:配置 8 个最大并发请求 + .build(); +// 启用 Zstd 压缩 +Context ctx = Context.newDefault().withCompression(Compression.Zstd); + +BulkStreamWriter writer = greptimeDB.bulkStreamWriter(schema, cfg, ctx); +``` + +### 资源管理 + +使用完客户端后正确关闭客户端很重要: + +```java +// 优雅地关闭客户端 +client.shutdownGracefully(); +``` + +### 性能调优 + +#### 压缩选项 + +Ingester 支持各种压缩算法以降低网络带宽占用并提高吞吐量。 + +```java +// 将压缩算法设置为 Zstd +Context ctx = Context.newDefault().withCompression(Compression.Zstd); +``` + +#### 写入操作比较 + +了解不同写入方法的性能特征对于优化数据写入至关重要。 + +| 写入方法 | API | 吞吐量 | 延迟 | 内存效率 | CPU 使用 | 最佳用途 | 限制 | +|----------|-----|---------|------|----------|----------|----------|------| +| Batching Write | `write(tables)` | 较好 | 良好 | 高 | 较高 | 简单应用程序,低延迟需求 | 大量数据的吞吐量较低 | +| Streaming Write | `streamWriter()` | 中等 | 良好 | 中等 | 中等 | 连续数据流,中等吞吐量 | 比常规写入更复杂 | +| Bulk Write | `bulkStreamWriter()` | 最佳 | 较高 | 最佳 | 中等 | 最大吞吐量,大批量操作 | 延迟较高,需要手动创建表 | + +#### 缓冲区大小优化 + +使用 `BulkStreamWriter` 时,你可以配置列缓冲区大小: + +```java +// 获取具有特定列缓冲区大小的表缓冲区 +Table.TableBufferRoot table = bulkStreamWriter.tableBufferRoot(columnBufferSize); +``` + +此选项可以显著提高数据转换为底层格式的速度。为了获得最佳性能,我们建议将列缓冲区大小设置为 1024 或更大,具体取决于你的特定工作负载特征和可用内存。 + +### 导出指标 + +Ingester 公开全面的指标,使你能够监控其性能、健康状况和操作状态。 + +有关可用指标及其使用的详细信息,请参考 [Ingester Prometheus Metrics](https://github.com/GreptimeTeam/greptimedb-ingester-java/tree/main/ingester-prometheus-metrics) 文档。 + +## 主要配置选项 + +`GreptimeOptions` 是 GreptimeDB Java 客户端的主要配置类,用于配置客户端连接、写入选项、RPC 设置和各种其他参数。 + +对于生产环境,你可能需要配置这些常用选项。完整参考:[GreptimeOptions JavaDoc](https://javadoc.io/static/io.greptime/ingester-protocol/VAR::javaSdkVersion/io/greptime/options/GreptimeOptions.html)。 + +**主要选项:** +- `database`:目标数据库名称,格式为 `[catalog-]schema`(默认值:`public`) +- `authInfo`:生产环境的身份验证凭据 +- `rpcOptions.defaultRpcTimeout`:RPC 请求超时时间(默认值:60 秒) +- `writeMaxRetries`:写入失败时的最大重试次数(默认值:1) +- `maxInFlightWritePoints`:写入流控制的最大在途数据点数(默认值:655360) +- `writeLimitedPolicy`:写入流量限制超出时的策略(默认值:AbortOnBlockingTimeoutPolicy 3秒) +- `defaultStreamMaxWritePointsPerSecond`:StreamWriter 的速率限制(默认值:655360) + +```java +// Production-ready configuration +RpcOptions rpcOpts = RpcOptions.newDefault(); +rpcOpts.setDefaultRpcTimeout(30000); // 30 seconds timeout + +AuthInfo authInfo = new AuthInfo("username", "password"); + +GreptimeOptions options = GreptimeOptions.newBuilder("127.0.0.1:4001", "production_db") + .authInfo(authInfo) + .rpcOptions(rpcOpts) + .writeMaxRetries(3) + .maxInFlightWritePoints(1000000) + .writeLimitedPolicy(new LimitedPolicy.AbortOnBlockingTimeoutPolicy(5, TimeUnit.SECONDS)) + .defaultStreamMaxWritePointsPerSecond(50000) + .build(); +``` + +## FAQ + +### 为什么我会遇到一些连接异常? + +使用 GreptimeDB Java ingester SDK 时,你可能会遇到一些连接异常。 +例如,异常是"`Caused by: java.nio.channels.UnsupportedAddressTypeException`"、 +"`Caused by: java.net.ConnectException: connect(..) failed: Address family not supported by protocol`" 或 +"`Caused by: java.net.ConnectException: connect(..) failed: Invalid argument`"。当你确定 +GreptimeDB 服务器正在运行,并且其端点可达时。 + +这些连接异常可能都是因为在打包过程中,gRPC 的 `io.grpc.NameResolverProvider` 服务提供程序没有 +打包到最终的 JAR 中。所以修复方法可以是: + +- 如果你使用 Maven Assembly 插件,请将 `metaInf-services` 容器描述符处理程序添加到你的 assembly + 文件中,如下所示: + ```xml + + ... + + + metaInf-services + + + + ``` +- 如果你使用 Maven Shade 插件,可以添加 `ServicesResourceTransformer`: + ```xml + + ... + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + + shade + + + + + + + + + + + + ... + + ``` + +## API 文档和示例 +- [API 参考](https://javadoc.io/doc/io.greptime/ingester-protocol/latest/index.html) +- [示例](https://github.com/GreptimeTeam/greptimedb-ingester-java/tree/main/ingester-example/) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/overview.md new file mode 100644 index 0000000000..0c35b3815d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/overview.md @@ -0,0 +1,12 @@ +--- +keywords: [SDK, 数据写入, Go 示例, Java 示例, 数据库连接, 数据插入, 调试日志] +description: 演示如何使用 SDK 在 GreptimeDB 中写入数据,提供 Go 和 Java 的示例。 +--- + +# 使用 SDK 写入数据 + +本指南将演示如何使用 SDK 在 GreptimeDB 中写入数据。 + +- [Go](go.md) +- [Java](java.md) + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/influxdb-line-protocol.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/influxdb-line-protocol.md new file mode 100644 index 0000000000..08d027e1e1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/influxdb-line-protocol.md @@ -0,0 +1,208 @@ +--- +keywords: [InfluxDB Line Protocol, 数据写入, Telegraf 集成, 数据模型, 鉴权] +description: 详细介绍如何使用 InfluxDB Line Protocol 将数据写入 GreptimeDB,包括协议、鉴权、Telegraf 集成和数据模型映射。 +--- + +# InfluxDB Line Protocol + +GreptimeDB 支持 HTTP InfluxDB Line 协议。 + +## 写入新数据 + +### 协议 + +#### Post 指标 + +你可以通过 `/influxdb/write` API 写入数据。 +以下是一个示例: + + + + + +```shell +curl -i -XPOST "http://localhost:4000/v1/influxdb/api/v2/write?db=public&precision=ms" \ + -H "authorization: token {{greptime_user:greptimedb_password}}" \ + --data-binary \ + 'monitor,host=127.0.0.1 cpu=0.1,memory=0.4 1667446797450 + monitor,host=127.0.0.2 cpu=0.2,memory=0.3 1667446798450 + monitor,host=127.0.0.1 cpu=0.5,memory=0.2 1667446798450' +``` + + + + +```shell +curl -i -XPOST "http://localhost:4000/v1/influxdb/write?db=public&precision=ms&u=&p=" \ +--data-binary \ +'monitor,host=127.0.0.1 cpu=0.1,memory=0.4 1667446797450 + monitor,host=127.0.0.2 cpu=0.2,memory=0.3 1667446798450 + monitor,host=127.0.0.1 cpu=0.5,memory=0.2 1667446798450' +``` + + + + +`/influxdb/write` 支持查询参数,包括: + +* `db`:指定要写入的数据库。默认值为 `public`。 +* `precision`:定义请求体中提供的时间戳的精度,可接受的值为 `ns`(纳秒)、`us`(微秒)、`ms`(毫秒)和 `s`(秒),默认值为 `ns`(纳秒)。该 API 写入的时间戳类型为 `TimestampNanosecond`,因此默认精度为 `ns`(纳秒)。如果你在请求体中使用了其他精度的的时间戳,需要使用此参数指定精度。该参数确保时间戳能够被准确解释并以纳秒精度存储。 + +你还可以在发送请求时省略 timestamp,GreptimeDB 将使用主机机器的当前系统时间(UTC 时间)作为 timestamp。例如: + + + + + +```shell +curl -i -XPOST "http://localhost:4000/v1/influxdb/api/v2/write?db=public" \ + -H "authorization: token {{greptime_user:greptimedb_password}}" \ + --data-binary \ + 'monitor,host=127.0.0.1 cpu=0.1,memory=0.4 + monitor,host=127.0.0.2 cpu=0.2,memory=0.3 + monitor,host=127.0.0.1 cpu=0.5,memory=0.2' +``` + + + + +```shell +curl -i -XPOST "http://localhost:4000/v1/influxdb/write?db=public&u=&p=" \ +--data-binary \ +'monitor,host=127.0.0.1 cpu=0.1,memory=0.4 + monitor,host=127.0.0.2 cpu=0.2,memory=0.3 + monitor,host=127.0.0.1 cpu=0.5,memory=0.2' +``` + + + + +#### 鉴权 + +GreptimeDB 与 InfluxDB 的行协议鉴权格式兼容,包括 V1 和 V2。 +如果你在 GreptimeDB 中[配置了鉴权](/user-guide/deployments-administration/authentication/overview.md),需要在 HTTP 请求中提供用户名和密码。 + + + + + +InfluxDB 的 [V2 协议](https://docs.influxdata.com/influxdb/v1.8/tools/api/?t=Auth+Enabled#apiv2query-http-endpoint) 使用了类似 HTTP 标准 basic 认证方案的格式。 + +```shell +curl 'http://localhost:4000/v1/influxdb/api/v2/write?db=public' \ + -H 'authorization: token {{username:password}}' \ + -d 'monitor,host=127.0.0.1 cpu=0.1,memory=0.4' +``` + + + + + +对于 InfluxDB 的 [V1 协议](https://docs.influxdata.com/influxdb/v1.8/tools/api/?t=Auth+Enabled#query-string-parameters-1) 的鉴权格式。在 HTTP 查询字符串中添加 `u` 作为用户和 `p` 作为密码,如下所示: + +```shell +curl 'http://localhost:4000/v1/influxdb/write?db=public&u=&p=' \ + -d 'monitor,host=127.0.0.1 cpu=0.1,memory=0.4' +``` + + + + +### Telegraf + +GreptimeDB 支持 [InfluxDB 行协议](../for-iot/influxdb-line-protocol.md)也意味着 GreptimeDB 与 Telegraf 兼容。 +要配置 Telegraf,只需将 GreptimeDB 的 URL 添加到 Telegraf 配置中: + + + + + +```toml +[[outputs.influxdb_v2]] + urls = ["http://:4000/v1/influxdb"] + token = ":" + bucket = "" + ## Leave empty + organization = "" +``` + + + + + +```toml +[[outputs.influxdb]] + urls = ["http://:4000/v1/influxdb"] + database = "" + username = "" + password = "" +``` + + + + + +## 数据模型 + +你可能已经熟悉了 [InfluxDB 的关键概念](https://docs.influxdata.com/influxdb/v2/reference/key-concepts/), +GreptimeDB 的[数据模型](/user-guide/concepts/data-model.md) 是值得了解的新事物。 +下方解释了 GreptimeDB 和 InfluxDB 数据模型的相似和不同之处: + +- 两者都是 [schemaless 写入](/user-guide/ingest-data/overview.md#自动生成表结构)的解决方案,这意味着在写入数据之前无需定义表结构。 +- GreptimeDB 的表在自动创建时会设置表选项 [`merge_mode`](/reference/sql/create.md#创建带有-merge-模式的表)为 `last_non_null`。 + 这意味着表会通过保留每个字段的最新值来合并具有相同主键和时间戳的行,该行为与 InfluxDB 相同。 +- 在 InfluxDB 中,一个点代表一条数据记录,包含一个 measurement、tag 集、field 集和时间戳。 + 在 GreptimeDB 中,它被表示为时间序列表中的一行数据。 + 表名对应于 measurement,列由三种类型组成:Tag、Field 和 Timestamp。 +- GreptimeDB 使用 `TimestampNanosecond` 作为来自 [InfluxDB 行协议 API](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md) 的时间戳数据类型。 +- GreptimeDB 使用 `Float64` 作为来自 InfluxDB 行协议 API 的数值数据类型。 + +以 InfluxDB 文档中的[示例数据](https://docs.influxdata.com/influxdb/v2/reference/key-concepts/data-elements/#sample-data)为例: + +|_time|_measurement|location|scientist|_field|_value| +|---|---|---|---|---|---| +|2019-08-18T00:00:00Z|census|klamath|anderson|bees|23| +|2019-08-18T00:00:00Z|census|portland|mullen|ants|30| +|2019-08-18T00:06:00Z|census|klamath|anderson|bees|28| +|2019-08-18T00:06:00Z|census|portland|mullen|ants|32| + +上述数据的 InfluxDB 行协议格式为: + +```shell +census,location=klamath,scientist=anderson bees=23 1566086400000000000 +census,location=portland,scientist=mullen ants=30 1566086400000000000 +census,location=klamath,scientist=anderson bees=28 1566086760000000000 +census,location=portland,scientist=mullen ants=32 1566086760000000000 +``` + +在 GreptimeDB 数据模型中,上述数据将被表示为 `census` 表中的以下内容: + +```sql ++---------------------+----------+-----------+------+------+ +| greptime_timestamp | location | scientist | bees | ants | ++---------------------+----------+-----------+------+------+ +| 2019-08-18 00:00:00 | klamath | anderson | 23 | NULL | +| 2019-08-18 00:06:00 | klamath | anderson | 28 | NULL | +| 2019-08-18 00:00:00 | portland | mullen | NULL | 30 | +| 2019-08-18 00:06:00 | portland | mullen | NULL | 32 | ++---------------------+----------+-----------+------+------+ +``` + +`census` 表结构如下: + +```sql ++--------------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+----------------------+------+------+---------+---------------+ +| location | String | PRI | YES | | TAG | +| scientist | String | PRI | YES | | TAG | +| bees | Float64 | | YES | | FIELD | +| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| ants | Float64 | | YES | | FIELD | ++--------------------+----------------------+------+------+---------+---------------+ +``` + +## 参考 + +- [InfluxDB Line protocol](https://docs.influxdata.com/influxdb/v2.7/reference/syntax/line-protocol/) + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/kafka.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/kafka.md new file mode 100644 index 0000000000..1aac9b6138 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/kafka.md @@ -0,0 +1,9 @@ +--- +keywords: [Kafka, 数据写入] +description: 将数据从 Kafka 写入到 GreptimeDB. +--- + +# Kafka + +请参考 [Kafka 文档](/user-guide/ingest-data/for-observability/kafka.md)了解如何将数据从 Kafka 写入到 GreptimeDB。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/opentsdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/opentsdb.md new file mode 100644 index 0000000000..19dce41488 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/opentsdb.md @@ -0,0 +1,65 @@ +--- +keywords: [OpenTSDB, HTTP API, 数据写入, 示例代码, 注意事项] +description: 介绍如何使用 OpenTSDB 协议通过 HTTP API 将数据写入 GreptimeDB,包括示例代码和注意事项。 +--- + +# OpenTSDB + +GreptimeDB 支持通过 HTTP API 使用 OpenTSDB 协议。 + +## 写入新数据 + +### HTTP API + +GreptimeDB 还支持通过 HTTP 接口插入 OpenTSDB 数据,接口是 `/opentsdb/api/put`,使用的请求和响应格式与 OpenTSDB 的 `/api/put` 接口相同。 + +GreptimeDB 的 HTTP Server 默认监听 `4000` 端口。例如使用 curl 写入一个指标数据: + +```shell +curl -X POST http://127.0.0.1:4000/v1/opentsdb/api/put \ + -H 'Authorization: Basic {{authentication}}' \ + -d ' + { + "metric": "sys.cpu.nice", + "timestamp": 1667898896, + "value": 18, + "tags": { + "host": "web01", + "dc": "hz" + } + } + ' +``` + +插入多个指标数据: + +```shell +curl -X POST http://127.0.0.1:4000/v1/opentsdb/api/put \ + -H 'Authorization: Basic {{authentication}}' \ + -d ' + [ + { + "metric": "sys.cpu.nice", + "timestamp": 1667898896, + "value": 1, + "tags": { + "host": "web02", + "dc": "hz" + } + }, + { + "metric": "sys.cpu.nice", + "timestamp": 1667898897, + "value": 9, + "tags": { + "host": "web03", + "dc": "sh" + } + } + ] + ' +``` + +:::tip 注意 +记得在路径前加上 GreptimeDB 的 HTTP API 版本 `v1`。 +::: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/overview.md new file mode 100644 index 0000000000..dd1f2ff11c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/overview.md @@ -0,0 +1,20 @@ +--- +keywords: [物联网, 数据写入, SQL, gRPC SDK, InfluxDB Line Protocol, EMQX, OpenTSDB] +description: 概述 GreptimeDB 支持的各种数据写入方法,包括 SQL、gRPC SDK、InfluxDB Line Protocol、EMQX 和 OpenTSDB。 +--- + +# 物联网(IoT)数据写入 + +数据的写入是物联网数据流程的关键部分。 +它从各种来源(如传感器、设备和应用程序)收集数据并将其存储在中央位置以供进一步处理和分析。 +数据写入过程对于确保数据的准确性、可靠性和安全性至关重要。 + +GreptimeDB 可处理并存储超大规模量级的数据以供分析, +支持各种数据格式、协议和接口,以便集成不同的物联网设备和系统。 + +- [SQL INSERT](sql.md):简单直接的数据插入方法。 +- [gRPC SDK](./grpc-sdks/overview.md):提供高效、高性能的数据写入,特别适用于实时数据和复杂的物联网基础设施。 +- [InfluxDB Line Protocol](influxdb-line-protocol.md):一种广泛使用的时间序列数据协议,便于从 InfluxDB 迁移到 GreptimeDB。该文档同样介绍了 Telegraf 的集成方式。 +- [EMQX](emqx.md):支持大规模设备连接的 MQTT 代理,可直接将数据写入到 GreptimeDB。 +- [OpenTSDB](opentsdb.md):使用 OpenTSDB 协议将数据写入到 GreptimeDB。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/sql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/sql.md new file mode 100644 index 0000000000..3023b6632b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-iot/sql.md @@ -0,0 +1,119 @@ +--- +keywords: [pg, pgsql, SQL, 数据写入, 创建表, 插入数据, 时区设置] +description: 介绍如何使用 SQL 将数据写入 GreptimeDB,包括创建表、插入数据和时区设置等内容。 +--- + +# SQL + +你可以使用 [MySQL](/user-guide/protocols/mysql.md) 或 [PostgreSQL](/user-guide/protocols/postgresql.md) 客户端执行 SQL 语句, +使用任何你喜欢的编程语言(如 Java JDBC)通过 MySQL 或 PostgreSQL 协议访问 GreptimeDB。 + +我们将使用 `monitor` 表作为示例来展示如何写入数据。有关如何创建 `monitor` 表的 SQL 示例,请参见[表管理](/user-guide/deployments-administration/manage-data/basic-table-operations.md#创建表)。 + +## 创建表 + +在插入数据之前,你需要创建一个表。例如,创建一个名为 `monitor` 的表: + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64 DEFAULT 0, + memory FLOAT64, + PRIMARY KEY(host)); +``` + +上述语句将创建一个具有以下 schema 的表: + +```sql ++--------+----------------------+------+------+---------------------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------+----------------------+------+------+---------------------+---------------+ +| host | String | PRI | YES | | TAG | +| ts | TimestampMillisecond | PRI | NO | current_timestamp() | TIMESTAMP | +| cpu | Float64 | | YES | 0 | FIELD | +| memory | Float64 | | YES | | FIELD | ++--------+----------------------+------+------+---------------------+---------------+ +4 rows in set (0.01 sec) +``` + +有关 `CREATE TABLE` 语句的更多信息,请参阅[表管理](/user-guide/deployments-administration/manage-data/basic-table-operations.md#create-a-table)。 + +## 插入数据 + +让我们向 `monitor` 表中插入一些测试数据。你可以使用 `INSERT INTO` 语句: + +```sql +INSERT INTO monitor +VALUES + ("127.0.0.1", 1702433141000, 0.5, 0.2), + ("127.0.0.2", 1702433141000, 0.3, 0.1), + ("127.0.0.1", 1702433146000, 0.3, 0.2), + ("127.0.0.2", 1702433146000, 0.2, 0.4), + ("127.0.0.1", 1702433151000, 0.4, 0.3), + ("127.0.0.2", 1702433151000, 0.2, 0.4); +``` + +```sql +Query OK, 6 rows affected (0.01 sec) +``` + +你还可以插入数据时指定列名: + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +VALUES + ("127.0.0.1", 1702433141000, 0.5, 0.2), + ("127.0.0.2", 1702433141000, 0.3, 0.1), + ("127.0.0.1", 1702433146000, 0.3, 0.2), + ("127.0.0.2", 1702433146000, 0.2, 0.4), + ("127.0.0.1", 1702433151000, 0.4, 0.3), + ("127.0.0.2", 1702433151000, 0.2, 0.4); +``` + +通过上面的语句,我们成功的向 `monitor` 表中插入了六条数据。请参考 [`INSERT`](/reference/sql/insert.md) 获得更多写入数据的相关信息。 + +## 时区 + +SQL 客户端中指定的时区将影响没有时区信息的字符串格式的时间戳。 +该时间戳值将会自动添加客户端的时区信息。 + +例如,下面的 SQL 将时区设置为 `+8:00`: + +```sql +SET time_zone = '+8:00'; +``` + +然后向 `monitor` 表中插入值: + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +VALUES + ("127.0.0.1", "2024-01-01 00:00:00", 0.4, 0.1), + ("127.0.0.2", "2024-01-01 00:00:00+08:00", 0.5, 0.1); +``` + +第一个时间戳值 `2024-01-01 00:00:00` 没有时区信息,因此它将自动添加客户端的时区信息。 +在插入数据后,它将等同于第二个值 `2024-01-01 00:00:00+08:00`。 + +`+8:00` 时区下的结果如下: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-01-01 00:00:00 | 0.4 | 0.1 | +| 127.0.0.2 | 2024-01-01 00:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +``` + +`UTC` 时区下的结果如下: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2023-12-31 16:00:00 | 0.4 | 0.1 | +| 127.0.0.2 | 2023-12-31 16:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/alloy.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/alloy.md new file mode 100644 index 0000000000..af2da05da5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/alloy.md @@ -0,0 +1,119 @@ +--- +keywords: [Grafana Alloy, Prometheus Remote Write, OpenTelemetry, 数据管道] +description: 绍了如何将 GreptimeDB 配置为 Grafana Alloy 的数据接收端,包括 Prometheus Remote Write 和 OpenTelemetry 的配置示例。通过这些配置,你可以将 GreptimeDB 集成到可观测性数据管道中,实现对指标和日志的高效管理和分析。 +--- + +# Grafana Alloy + +[Grafana Alloy](https://grafana.com/docs/alloy/latest/) 是一个用于 OpenTelemetry (OTel)、Prometheus、Pyroscope、Loki 等其他指标、日志、追踪和分析工具的可观测性数据管道。 +你可以将 GreptimeDB 集成为 Alloy 的数据接收端。 + +## Prometheus Remote Write + +将 GreptimeDB 配置为远程写入目标: + +```hcl +prometheus.remote_write "greptimedb" { + endpoint { + url = "${GREPTIME_SCHEME:=http}://${GREPTIME_HOST:=greptimedb}:${GREPTIME_PORT:=4000}/v1/prometheus/write?db=${GREPTIME_DB:=public}" + + basic_auth { + username = "${GREPTIME_USERNAME}" + password = "${GREPTIME_PASSWORD}" + } + } +} +``` + +- `GREPTIME_HOST`: GreptimeDB 主机地址,例如 `localhost`。 +- `GREPTIME_DB`: GreptimeDB 数据库名称,默认是 `public`。 +- `GREPTIME_USERNAME` 和 `GREPTIME_PASSWORD`: GreptimeDB 的[鉴权认证信息](/user-guide/deployments-administration/authentication/static.md)。 + +有关从 Prometheus 到 GreptimeDB 的数据模型转换的详细信息,请参阅 Prometheus Remote Write 指南中的[数据模型](/user-guide/ingest-data/for-observability/prometheus.md#数据模型)部分。 + +## OpenTelemetry + +GreptimeDB 也可以配置为 OpenTelemetry Collector 的目标。 + +### 指标 + +```hcl +otelcol.exporter.otlphttp "greptimedb" { + client { + endpoint = "${GREPTIME_SCHEME:=http}://${GREPTIME_HOST:=greptimedb}:${GREPTIME_PORT:=4000}/v1/otlp/" + headers = { + "X-Greptime-DB-Name" = "${GREPTIME_DB:=public}", + } + auth = otelcol.auth.basic.credentials.handler + } +} + +otelcol.auth.basic "credentials" { + username = "${GREPTIME_USERNAME}" + password = "${GREPTIME_PASSWORD}" +} +``` + +- `GREPTIME_HOST`: GreptimeDB 主机地址,例如 `localhost`。 +- `GREPTIME_DB`: GreptimeDB 数据库名称,默认是 `public`。 +- `GREPTIME_USERNAME` 和 `GREPTIME_PASSWORD`: GreptimeDB 的[鉴权认证信息](/user-guide/deployments-administration/authentication/static.md)。 + +有关从 OpenTelemetry 到 GreptimeDB 的指标数据模型转换的详细信息,请参阅 OpenTelemetry 指南中的[数据模型](/user-guide/ingest-data/for-observability/opentelemetry.md#数据模型)部分。 + +### 日志 + +以下示例设置了一个使用 Loki 和 OpenTelemetry Collector (otelcol) 的日志管道,将日志转发到 GreptimeDB: + +```hcl +loki.source.file "greptime" { + targets = [ + {__path__ = "/tmp/foo.txt"}, + ] + forward_to = [otelcol.receiver.loki.greptime.receiver] +} + +otelcol.receiver.loki "greptime" { + output { + logs = [otelcol.exporter.otlphttp.greptimedb_logs.input] + } +} + +otelcol.auth.basic "credentials" { + username = "${GREPTIME_USERNAME}" + password = "${GREPTIME_PASSWORD}" +} + +otelcol.exporter.otlphttp "greptimedb_logs" { + client { + endpoint = "${GREPTIME_SCHEME:=http}://${GREPTIME_HOST:=greptimedb}:${GREPTIME_PORT:=4000}/v1/otlp/" + headers = { + "X-Greptime-DB-Name" = "${GREPTIME_DB:=public}", + "X-Greptime-Log-Table-Name" = "${LOG_TABLE_NAME}", + "X-Greptime-Log-Extract-Keys" = "${EXTRACT_KEYS}", + } + auth = otelcol.auth.basic.credentials.handler + } +} +``` + +- Loki source 配置 + - `loki.source.file "greptime"` 块定义了 source,用于 Loki 从位于 `/tmp/foo.txt` 的文件中读取日志。 + - `forward_to` 数组指示从该文件读取的日志应转发到 `otelcol.receiver.loki.greptime.receiver`。 +- OpenTelemetry Collector Receiver 配置: + - `otelcol.receiver.loki "greptime"` 在 OpenTelemetry Collector 中设置了一个 receiver,以接收来自 Loki 的日志。 + - `output` 指定接收到的日志应转发到 `otelcol.exporter.otlphttp.greptimedb_logs.input`。 +- OpenTelemetry Collector Exporter 配置: + - `otelcol.exporter.otlphttp "greptimedb_logs"` 块配置了一个 HTTP Exporter,将日志发送到 GreptimeDB。 + - `GREPTIME_HOST`: GreptimeDB 主机地址,例如 `localhost`。 + - `GREPTIME_DB`: GreptimeDB 数据库名称,默认是 `public`。 + - `GREPTIME_USERNAME` 和 `GREPTIME_PASSWORD`: GreptimeDB 的[鉴权认证信息](/user-guide/deployments-administration/authentication/static.md)。 + - `LOG_TABLE_NAME`: 存储日志的表名,默认表名为 `opentelemetry_logs`。 + - `EXTRACT_KEYS`: 从属性中提取对应 key 的值到表的顶级字段,用逗号分隔,例如 `filename,log.file.name,loki.attribute.labels`,详情请看 [HTTP API 文档](opentelemetry.md#otlphttp-api-1)。 + +有关从 OpenTelemetry 到 GreptimeDB 的日志数据模型转换的详细信息,请参阅 OpenTelemetry 指南中的[数据模型](/user-guide/ingest-data/for-observability/opentelemetry.md#数据模型-1)部分。 + +:::tip 提示 +上述示例代码可能会过时,请参考 OpenTelemetry 和 Grafana Alloy 的官方文档以获取最新信息。 +::: + +有关示例代码的更多信息,请参阅你首选编程语言的官方文档。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/elasticsearch.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/elasticsearch.md new file mode 100644 index 0000000000..bb768d7097 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/elasticsearch.md @@ -0,0 +1,182 @@ +--- +keywords: [Elasticsearch, log storage, API, configuration, data model, telegraf, logstash, filebeat] +description: 使用 Elasticsearch 协议写入日志数据。 +--- + +# Elasticsearch + +## 概述 + +GreptimeDB 支持使用 Elasticsearch 的 [`_bulk` API](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html) 来写入数据。我们会将 Elasticsearch 中的 Index 概念映射为 GreptimeDB 的 Table,同时用户可在 HTTP 请求的 URL 参数中用 `db` 来指定相应的数据库名。**不同于原生 Elasticsearch,该 API 仅支持数据写入,不支持数据的修改和删除**。在实现层面上,GreptimeDB 会将原生 Elasticsearch `_bulk` API 请求中的 `index` 和 `create` 命令都视为**创建操作**。除此之外,GreptimeDB 仅支持解析原生 `_bulk` API 命令请求中的 `_index` 字段而忽略其他字段。 + +## HTTP API + +在大多数日志收集器(比如下文中的 Logstash 和 Filebeat)的配置中,你只需要将 HTTP endpoint 配置为 `http://${db_host}:${db_http_port}/v1/elasticsearch`,比如 `http://localhost:4000/v1/elasticsearch`。 + +GreptimeDB 支持通过实现以下两个 HTTP endpoint 来实现 Elasticsearch 协议的数据写入: + +- **`/v1/elasticsearch/_bulk`**:用户可使用 POST 方法将数据以 NDJSON 格式写入到 GreptimeDB 中。 + + 以下面请求为例,GreptimeDB 将会创建一个名为 `test` 的表,并写入两条数据: + + ```json + POST /v1/elasticsearch/_bulk + + {"create": {"_index": "test", "_id": "1"}} + {"name": "John", "age": 30} + {"create": {"_index": "test", "_id": "2"}} + {"name": "Jane", "age": 25} + ``` + +- **`/v1/elasticsearch/${index}/_bulk`**:用户可使用 POST 方法将数据以 NDJSON 格式写入到 GreptimeDB 中的 `${index}` 表中。如果 POST 请求中也有 `_index` 字段,则 URL 中的 `${index}` 将被忽略。 + + 以下面请求为例,GreptimeDB 将会创建一个名为 `test` 和 `another_index` 的表,并各自写入相应的数据: + + ```json + POST /v1/elasticsearch/test/_bulk + + {"create": {"_id": "1"}} + {"name": "John", "age": 30} + {"create": {"_index": "another_index", "_id": "2"}} + {"name": "Jane", "age": 25} + ``` + +### HTTP Header 参数 + +- `x-greptime-db-name`:指定写入的数据库名。如不指定,则默认使用 `public` 数据库; +- `x-greptime-pipeline-name`:指定写入的 pipeline 名,如不指定,则默认使用 GreptimeDB 内部的 pipeline `greptime_identity`; +- `x-greptime-pipeline-version`:指定写入的 pipeline 版本,如不指定,则默认对应 pipeline 的最新版本; + +更多关于 Pipeline 的详细信息,请参考 [管理 Pipelines](/user-guide/logs/manage-pipelines.md) 文档。 + +### URL 参数 + +你可以使用以下 HTTP URL 参数: + +- `db`:指定写入的数据库名。如不指定,则默认使用 `public` 数据库; +- `pipeline_name`:指定写入的 pipeline 名,如不指定,则默认使用 GreptimeDB 内部的 pipeline `greptime_identity`; +- `version`:指定写入的 pipeline 版本,如不指定,则默认对应 pipeline 的最新版本; +- `msg_field`:`msg_field` 可指定包含原始日志数据的 JSON 字段名。比如在 Logstash 和 Filebeat 中,该字段通常为 `message`。如果用户指定了该参数,则 GreptimeDB 会尝试将该字段中的数据以 JSON 格式进行展开,如果展开失败,则该字段会被当成字符串进行处理。该配置选项目前仅在 URL 参数中生效。 + +### 鉴权 Header + +关于鉴权 Header 的详细信息,请参考 [Authorization](/user-guide/protocols/http.md#鉴权) 文档。 + +## 使用方法 + +### 使用 HTTP API 写入数据 + +你可以创建一个 `request.json` 文件,其中包含如下内容: + +```json +{"create": {"_index": "es_test", "_id": "1"}} +{"name": "John", "age": 30} +{"create": {"_index": "es_test", "_id": "2"}} +{"name": "Jane", "age": 25} +``` + +然后使用 `curl` 命令将该文件作为请求体发送至 GreptimeDB: + +```bash +curl -XPOST http://localhost:4000/v1/elasticsearch/_bulk \ + -H "Authorization: Basic {{authentication}}" \ + -H "Content-Type: application/json" -d @request.json +``` + +我们可使用 `mysql` 客户端连接到 GreptimeDB,然后执行如下 SQL 语句来查看写入的数据: + +```sql +SELECT * FROM es_test; +``` + +我们将可以看到如下结果: + +``` +mysql> SELECT * FROM es_test; ++------+------+----------------------------+ +| age | name | greptime_timestamp | ++------+------+----------------------------+ +| 30 | John | 2025-01-15 08:26:06.516665 | +| 25 | Jane | 2025-01-15 08:26:06.521510 | ++------+------+----------------------------+ +2 rows in set (0.13 sec) +``` + +### Logstash + +如果你正在使用 [Logstash](https://www.elastic.co/logstash) 来收集日志,可使用如下配置来将数据写入到 GreptimeDB: + +``` +output { + elasticsearch { + hosts => ["http://localhost:4000/v1/elasticsearch"] + index => "my_index" + parameters => { + "pipeline_name" => "my_pipeline" + "msg_field" => "message" + } + } +} +``` + +请关注以下与 GreptimeDB 相关的配置: + +- `hosts`: 指定 GreptimeDB 的 Elasticsearch 协议的 HTTP 地址,即 `http://${db_host}:${db_http_port}/v1/elasticsearch`; +- `index`: 指定写入的表名; +- `parameters`: 指定写入的 URL 参数,上面的例子中指定了 `pipeline_name` 和 `msg_field` 两个参数; + +### Filebeat + +如果你正在使用 [Filebeat](https://github.com/elastic/beats/tree/main/filebeat) 来收集日志,可使用如下配置来将数据写入到 GreptimeDB: + +``` +output.elasticsearch: + hosts: ["http://localhost:4000/v1/elasticsearch"] + index: "my_index" + parameters: + pipeline_name: my_pipeline + msg_field: message +``` + +请关注以下与 GreptimeDB 相关的配置: + +- `hosts`: 指定 GreptimeDB 的 Elasticsearch 协议的 HTTP 地址,即 `http://${db_host}:${db_http_port}/v1/elasticsearch`,可根据实际情况进行调整; +- `index`: 指定写入的表名; +- `parameters`: 指定写入的 URL 参数,上面的例子中指定了 `pipeline_name` 和 `msg_field` 两个参数; + +### Telegraf + +如果你正在使用 [Telegraf](https://github.com/influxdata/telegraf) 来收集日志,你可以使用其 Elasticsearch 插件来将数据写入到 GreptimeDB,如下所示: + +```toml +[[outputs.elasticsearch]] + urls = [ "http://localhost:4000/v1/elasticsearch" ] + index_name = "test_table" + health_check_interval = "0s" + enable_sniffer = false + flush_interval = "1s" + manage_template = false + template_name = "telegraf" + overwrite_template = false + namepass = ["tail"] + + [outputs.elasticsearch.headers] + "X-GREPTIME-DB-NAME" = "public" + "X-GREPTIME-PIPELINE-NAME" = "greptime_identity" + +[[inputs.tail]] + files = ["/tmp/test.log"] + from_beginning = true + data_format = "value" + data_type = "string" + character_encoding = "utf-8" + interval = "1s" + pipe = false + watch_method = "inotify" +``` + +请关注以下与 GreptimeDB 相关的配置: + +- `urls`: 指定 GreptimeDB 的 Elasticsearch 协议的 HTTP 地址,即 `http://${db_host}:${db_http_port}/v1/elasticsearch`; +- `index_name`: 指定写入的表名; +- `outputs.elasticsearch.header`: 指定写入的 HTTP Header,上面的例子中配置了 `X-GREPTIME-DB-NAME` 和 `X-GREPTIME-PIPELINE-NAME` 两个 HTTP Header; diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/fluent-bit.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/fluent-bit.md new file mode 100644 index 0000000000..367c290b02 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/fluent-bit.md @@ -0,0 +1,122 @@ +--- +keywords: [Fluent bit, Prometheus Remote Write, OpenTelemetry, 数据管道] +description: 将 GreptimeDB 与 Fluent bit 集成以实现 Prometheus Remote Write 和 OpenTelemetry 的说明。 +--- + +# Fluent Bit + +[Fluent Bit](http://fluentbit.io/) 是一个快速且轻量级的遥测代理,用于 Linux、macOS、Windows 和 BSD 系列操作系统的日志、指标和跟踪。Fluent Bit 专注于性能,允许从不同来源收集和处理遥测数据而不增加复杂性。 + +你可以将 Fluent Bit 数据转发到 GreptimeDB。本文档介绍如何配置 Fluent Bit 以将日志、指标和跟踪发送到 GreptimeDB。 + +## Http + +使用 Fluent Bit 的 [HTTP 输出插件](https://docs.fluentbit.io/manual/pipeline/outputs/http),你可以将日志发送到 GreptimeDB。Http 接口目前支持日志的写入。 +在配置 Fluent Bit 之前,请确保你已经了解[日志写入流程](/user-guide/logs/overview.md)和[如何使用 pipelines](/user-guide/logs/use-custom-pipelines.md)。 + +``` +[OUTPUT] + Name http + Match * + Host greptimedb + Port 4000 + Uri /v1/ingest?db=public&table=your_table&pipeline_name=greptime_identity + Format json + Json_date_key scrape_timestamp + Json_date_format iso8601 + compress gzip + http_User + http_Passwd +``` + +- `uri`: **发送日志的端点。** +- `format`: 日志的格式,需要是 `json`。 +- `json_date_key`: JSON 对象中包含时间戳的键。 +- `json_date_format`: 时间戳的格式。 +- `compress`: 使用的压缩方法,例如 `gzip`。 +- `header`: 发送请求时的头部信息,例如用于认证的 `Authorization`。如果没有,不要增加 Authorization 头部。 +- `http_user` 和 `http_passwd`: GreptimeDB 的 [认证凭据](/user-guide/deployments-administration/authentication/static.md)。 + +在 `uri` 参数中: + +- `db` 是你要写入日志的数据库名称。 +- `table` 是你要写入日志的表名称。 +- `pipeline_name` 是你要用于处理日志的管道名称。 + +## OpenTelemetry + +GreptimeDB 也可以配置为 OpenTelemetry 收集器。使用 Fluent Bit 的 [OpenTelemetry 输出插件](https://docs.fluentbit.io/manual/pipeline/outputs/opentelemetry),你可以将指标、日志和跟踪发送到 GreptimeDB。 + +``` +[OUTPUT] + Name opentelemetry + Match * + Host 127.0.0.1 + Port 4000 + Metrics_uri /v1/otlp/v1/metrics + Logs_uri /v1/otlp/v1/logs + Traces_uri /v1/otlp/v1/traces + Log_response_payload True + Tls Off + Tls.verify Off +``` + +- `Metrics_uri`, `Logs_uri`, 和 `Traces_uri`: 发送指标、日志和跟踪的端点。 + +我们建议不要在一个 output 同时写入 metrics log 和 trace,因为我们的写入接口它们各自有一些特殊的 header 选项用于指定一些参数,我们建议一个为 metrics log 和 trace 单独创建一个 opentelemetry output 例如: + +``` +# Only for metrics +[OUTPUT] + Name opentelemetry + Alias opentelemetry_metrics + Match * + Host 127.0.0.1 + Port 4000 + Metrics_uri /v1/otlp/v1/metrics + Log_response_payload True + Tls Off + Tls.verify Off + +# Only for logs +[OUTPUT] + Name opentelemetry + Alias opentelemetry_logs + Match * + Host 127.0.0.1 + Port 4000 + Logs_uri /v1/otlp/v1/logs + Log_response_payload True + Tls Off + Tls.verify Off + Header X-Greptime-Log-Table-Name "" + Header X-Greptime-Log-Pipeline-Name "" + Header X-Greptime-DB-Name "" +``` + +本示例中,使用的是 [OpenTelemetry OTLP/HTTP API](/user-guide/ingest-data/for-observability/opentelemetry.md#opentelemetry-collectors) 接口。如需更多信息,请参阅 [OpenTelemetry](/user-guide/ingest-data/for-observability/opentelemetry.md) 文档。 + +## Prometheus Remote Write + +将 GreptimeDB 配置为远程写入目标: + +``` +[OUTPUT] + Name prometheus_remote_write + Match internal_metrics + Host 127.0.0.1 + Port 4000 + Uri /v1/prometheus/write?db= + Tls Off + http_user + http_passwd +``` + +- `Uri`: 发送指标的端点。 +- `http_user` 和 `http_passwd`: GreptimeDB 的 [认证凭据](/user-guide/deployments-administration/authentication/static.md)。 + +在 `Uri` 参数中: + +- `db` 是你要写入指标的数据库名称。 + +有关从 Prometheus 到 GreptimeDB 的数据模型转换的详细信息,请参阅 Prometheus Remote Write 指南中的[数据模型](/user-guide/ingest-data/for-observability/prometheus.md#data-model)部分。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/influxdb-line-protocol.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/influxdb-line-protocol.md new file mode 100644 index 0000000000..5f143b1114 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/influxdb-line-protocol.md @@ -0,0 +1,9 @@ +--- +keywords: [InfluxDB Line Protocol] +description: 使用 InfluxDB Line Protocol 将数据写入到 GreptimeDB +--- + +# InfluxDB Line Protocol + + +请参考 [InfluxDB Line Protocol 文档](../for-iot/influxdb-line-protocol.md) 了解如何使用 InfluxDB Line Protocol 将数据写入到 GreptimeDB。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/kafka.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/kafka.md new file mode 100644 index 0000000000..0940c78491 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/kafka.md @@ -0,0 +1,170 @@ +--- +keywords: [Kafka, 数据提取, 可观察性, 指标, 日志, JSON 日志, 文本日志, Vector, InfluxDB 行协议] +description: 了解如何使用 Vector 将可观察性数据从 Kafka 写入到 GreptimeDB。本指南涵盖指标和日志提取,包括 JSON 和文本日志格式,并附有详细的配置示例。 +--- + +# Kafka + +如果你使用 Kafka 或兼容 Kafka 的消息队列进行可观测性数据传输,可以直接将数据写入到 GreptimeDB 中。 + +这里我们使用 Vector 作为工具将数据从 Kafka 传输到 GreptimeDB。 + +## 指标 + +从 Kafka 写入指标到 GreptimeDB 时,消息应采用 InfluxDB 行协议格式。例如: + +```txt +census,location=klamath,scientist=anderson bees=23 1566086400000000000 +``` + +然后配置 Vector 使用 `influxdb` 解码器来处理这些消息。 + +```toml +[sources.metrics_mq] +# 指定源类型为 Kafka +type = "kafka" +# Kafka 的消费者组 ID +group_id = "vector0" +# 要消费消息的 Kafka 主题列表 +topics = ["test_metric_topic"] +# 要连接的 Kafka 地址 +bootstrap_servers = "kafka:9092" +# `influxdb` 表示消息应采用 InfluxDB 行协议格式 +decoding.codec = "influxdb" + +[sinks.metrics_in] +inputs = ["metrics_mq"] +# 指定接收器类型为 `greptimedb_metrics` +type = "greptimedb_metrics" +# GreptimeDB 服务器的端点 +# 将 替换为实际的主机名或 IP 地址 +endpoint = ":4001" +dbname = "" +username = "" +password = "" +tls = {} +``` + +有关 InfluxDB 行协议指标如何映射到 GreptimeDB 数据的详细信息,请参阅 InfluxDB 行协议文档中的[数据模型](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md#数据模型)部分。 + +## 日志 + +开发人员通常处理两种类型的日志:JSON 日志和纯文本日志。 +例如以下从 Kafka 发送的日志示例。 + +纯文本日志: + +```txt +127.0.0.1 - - [25/May/2024:20:16:37 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" +``` + +或 JSON 日志: + +```json +{ + "timestamp": "2024-12-23T10:00:00Z", + "level": "INFO", + "message": "Service started" +} +``` + +GreptimeDB 将这些日志转换为具有多个列的结构化数据,并自动创建必要的表。 +Pipeline 在写入到 GreptimeDB 之前将日志处理为结构化数据。 +不同的日志格式需要不同的 [Pipeline](/user-guide/logs/quick-start.md#write-logs-by-pipeline) 来解析,详情请继续阅读下面的内容。 + +### JSON 格式的日志 + +对于 JSON 格式的日志(例如 `{"timestamp": "2024-12-23T10:00:00Z", "level": "INFO", "message": "Service started"}`), +你可以使用内置的 [`greptime_identity`](/user-guide/logs/manage-pipelines.md#greptime_identity) pipeline 直接写入日志。 +此 pipeline 根据 JSON 日志消息中的字段自动创建列。 + +你只需要配置 Vector 的 `transforms` 设置以解析 JSON 消息,并使用 `greptime_identity` pipeline,如以下示例所示: + +```toml +[sources.logs_in] +type = "kafka" +# Kafka 的消费者组 ID +group_id = "vector0" +# 要消费消息的 Kafka 主题列表 +topics = ["test_log_topic"] +# 要连接的 Kafka 代理地址 +bootstrap_servers = "kafka:9092" + +# 将日志转换为 JSON 格式 +[transforms.logs_json] +type = "remap" +inputs = ["logs_in"] +source = ''' +. = parse_json!(.message) +''' + +[sinks.logs_out] +# 指定此接收器将接收来自 `logs_json` 源的数据 +inputs = ["logs_json"] +# 指定接收器类型为 `greptimedb_logs` +type = "greptimedb_logs" +# GreptimeDB 服务器的端点 +endpoint = "http://:4000" +compression = "gzip" +# 将 替换为实际值 +dbname = "" +username = "" +password = "" +# GreptimeDB 中的表名,如果不存在,将自动创建 +table = "demo_logs" +# 使用内置的 `greptime_identity` 管道 +pipeline_name = "greptime_identity" +``` + +### 文本格式的日志 + +对于文本格式的日志,例如下面的访问日志格式,你需要创建自定义 pipeline 来解析它们: + +``` +127.0.0.1 - - [25/May/2024:20:16:37 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" +``` + +#### 创建 pipeline + +要创建自定义 pipeline, +请参阅[使用自定义 pipeline](/user-guide/logs/use-custom-pipelines.md)文档获取详细说明。 + +#### 写入数据 + +创建 pipeline 后,将其配置到 Vector 配置文件中的 `pipeline_name` 字段。 + +```toml +# sample.toml +[sources.log_mq] +# 指定源类型为 Kafka +type = "kafka" +# Kafka 的消费者组 ID +group_id = "vector0" +# 要消费消息的 Kafka 主题列表 +topics = ["test_log_topic"] +# 要连接的 Kafka 地址 +bootstrap_servers = "kafka:9092" + +[sinks.sink_greptime_logs] +# 指定接收器类型为 `greptimedb_logs` +type = "greptimedb_logs" +# 指定此接收器将接收来自 `log_mq` 源的数据 +inputs = [ "log_mq" ] +# 使用 `gzip` 压缩以节省带宽 +compression = "gzip" +# GreptimeDB 服务器的端点 +# 将 替换为实际的主机名或 IP 地址 +endpoint = "http://:4000" +dbname = "" +username = "" +password = "" +# GreptimeDB 中的表名,如果不存在,将自动创建 +table = "demo_logs" +# 你创建的自定义管道名称 +pipeline_name = "your_custom_pipeline" +``` + +## Demo + +有关数据转换和写入的可运行演示,请参阅 [Kafka Ingestion Demo](https://github.com/GreptimeTeam/demo-scene/tree/main/kafka-ingestion)。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/loki.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/loki.md new file mode 100644 index 0000000000..dd398e9325 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/loki.md @@ -0,0 +1,267 @@ +--- +keywords: [Loki, 日志数据, API 信息, 示例代码, 数据模型] +description: 介绍如何使用 Loki 将日志数据发送到 GreptimeDB,包括 API 信息、示例代码和数据模型映射。 +--- + +# Loki + +## 使用方法 + +### API + +要通过原始 HTTP API 将日志发送到 GreptimeDB,请使用以下信息: + +* **URL**: `http{s}:///v1/loki/api/v1/push` +* **Headers**: + * `X-Greptime-DB-Name`: `` + * `Authorization`: `Basic` 认证,这是一个 Base64 编码的 `:` 字符串。更多信息,请参考 [认证](https://docs.greptime.com/user-guide/deployments-administration/authentication/static/) 和 [HTTP API](https://docs.greptime.com/user-guide/protocols/http#authentication)。 + * `X-Greptime-Log-Table-Name`: ``(可选)- 存储日志的表名。如果未提供,默认表名为 `loki_logs`。 + +请求使用二进制 protobuf 编码负载。定义的格式与 [logproto.proto](https://github.com/grafana/loki/blob/main/pkg/logproto/logproto.proto) 相同。 + +### 示例代码 + +[Grafana Alloy](https://grafana.com/docs/alloy/latest/) 是一个供应商中立的 OpenTelemetry (OTel) Collector 发行版。Alloy 独特地结合了社区中最好的开源可观测性信号。 + +它提供了一个 Loki 导出器,可以用来将日志发送到 GreptimeDB。以下是一个配置示例: + +``` +loki.source.file "greptime" { + targets = [ + {__path__ = "/tmp/foo.txt"}, + ] + forward_to = [loki.write.greptime_loki.receiver] +} + +loki.write "greptime_loki" { + endpoint { + url = "${GREPTIME_SCHEME:=http}://${GREPTIME_HOST:=greptimedb}:${GREPTIME_PORT:=4000}/v1/loki/api/v1/push" + headers = { + "x-greptime-db-name" = "${GREPTIME_DB:=public}", + "x-greptime-log-table-name" = "${GREPTIME_LOG_TABLE_NAME:=loki_demo_logs}", + } + } + external_labels = { + "job" = "greptime", + "from" = "alloy", + } +} +``` + +此配置从文件 `/tmp/foo.txt` 读取日志并将其发送到 GreptimeDB。日志存储在表 `loki_demo_logs` 中,并带有 label `job` 和 `from`。 + +更多信息,请参考 [Grafana Alloy loki.write 文档](https://grafana.com/docs/alloy/latest/reference/components/loki/loki.write/)。 + +你可以运行以下命令来检查表中的数据: + +```sql +SELECT * FROM loki_demo_logs; ++----------------------------+------------------------+--------------+-------+----------+ +| greptime_timestamp | line | filename | from | job | ++----------------------------+------------------------+--------------+-------+----------+ +| 2024-11-25 11:02:31.256251 | Greptime is very cool! | /tmp/foo.txt | alloy | greptime | ++----------------------------+------------------------+--------------+-------+----------+ +1 row in set (0.01 sec) +``` + +## 数据模型 + +Loki 日志数据模型根据以下规则映射到 GreptimeDB 数据模型: + +**没有 label 的默认表结构:** + +```sql +DESC loki_demo_logs; ++--------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+---------------------+------+------+---------+---------------+ +| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| line | String | | YES | | FIELD | ++--------------------+---------------------+------+------+---------+---------------+ +5 rows in set (0.00 sec) +``` + +- `greptime_timestamp`: 日志条目的时间戳 +- `line`: 日志消息内容 + +如果 Loki 请求数据中含有 label,它们将作为 tag 添加到表结构中(如上例中的 `job` 和 `from`)。 + +**重要说明:** +- 所有 label 都被视为字符串类型的 tag +- 请不要尝试使用 SQL 预先创建表来指定 tag 列,这会导致类型不匹配和写入失败 + +### 表结构示例 + +以下是带有 label 的表结构示例: + +```sql +DESC loki_demo_logs; ++--------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+---------------------+------+------+---------+---------------+ +| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| line | String | | YES | | FIELD | +| filename | String | PRI | YES | | TAG | +| from | String | PRI | YES | | TAG | +| job | String | PRI | YES | | TAG | ++--------------------+---------------------+------+------+---------+---------------+ +5 rows in set (0.00 sec) +``` + +```sql +SHOW CREATE TABLE loki_demo_logs\G +*************************** 1. row *************************** + Table: loki_demo_logs +Create Table: CREATE TABLE IF NOT EXISTS `loki_demo_logs` ( + `greptime_timestamp` TIMESTAMP(9) NOT NULL, + `line` STRING NULL, + `filename` STRING NULL, + `from` STRING NULL, + `job` STRING NULL, + TIME INDEX (`greptime_timestamp`), + PRIMARY KEY (`filename`, `from`, `job`) +) + +ENGINE=mito +WITH( + append_mode = 'true' +) +1 row in set (0.00 sec) +``` + +## 在 Loki Push API 中使用 pipeline + +:::warning 实验性特性 +此实验性功能可能存在预期外的行为,其功能未来可能发生变化。 +::: + +从 `v0.15` 版本开始,GreptimeDB 支持使用 pipeline 来处理 Loki Push 请求。 +你可以简单地设置 HTTP 头 `x-greptime-pipeline-name` 为目标 pipeline 名称来启用 pipeline 处理。 + +**注意:** 当请求数据通过 pipeline 引擎时,GreptimeDB 会为 label 和元数据列名添加前缀: +- 每个 label 名前添加 `loki_label_` 前缀 +- 每个结构化元数据名前添加 `loki_metadata_` 前缀 +- 原始的 Loki 日志行被命名为 `loki_line` + +### Pipeline 示例 + +以下是一个完整的示例,演示如何在 Loki Push API 中使用 Pipeline。 + +**步骤 1:准备日志文件** + +假设我们有一个名为 `logs.json` 的日志文件,包含 JSON 格式的日志条目: +```json +{"timestamp":"2025-08-21 14:23:17.892","logger":"sdk.tool.DatabaseUtil","level":"ERROR","message":"Connection timeout exceeded for database pool","trace_id":"a7f8c92d1e4b4c6f9d2e5a8b3f7c1d9e","source":"application"} +{"timestamp":"2025-08-21 14:23:18.156","logger":"core.scheduler.TaskManager","level":"WARN","message":"Task queue capacity reached 85% threshold","trace_id":"b3e9f4a6c8d2e5f7a1b4c7d9e2f5a8b3","source":"scheduler"} +{"timestamp":"2025-08-21 14:23:18.423","logger":"sdk.tool.NetworkUtil","level":"INFO","message":"Successfully established connection to remote endpoint","trace_id":"c5d8e7f2a9b4c6d8e1f4a7b9c2e5f8d1","source":"network"} +``` + +每一行都是一个独立的 JSON 对象,包含日志信息。 + +**步骤 2:创建 Pipeline 配置** + +以下是解析 JSON 日志条目的 pipeline 配置: +```yaml +# pipeline.yaml +version: 2 +processors: + - vrl: + source: | + message = parse_json!(.loki_line) + target = { + "log_time": parse_timestamp!(message.timestamp, "%Y-%m-%d %T%.3f"), + "log_level": message.level, + "log_source": message.source, + "logger": message.logger, + "message": message.message, + "trace_id": message.trace_id, + } + . = target +transform: + - field: log_time + type: time, ms + index: timestamp +``` + +pipeline 的配置相对直观: 使用 `vrl` 处理器将日志行解析为 JSON 对象,然后将其中的字段提取到根目录。 +`log_time` 在 transform 部分中被指定为时间索引,其他字段将由 pipeline 引擎自动推导,详见 [pipeline version 2](/reference/pipeline/pipeline-config.md#版本-2-中的-transform)。 + +请注意,输入字段名为 `loki_line`,它包含来自 Loki 的原始日志行。 + +**步骤 3:配置 Grafana Alloy** + +准备一个 Alloy 配置文件来读取日志文件并将其发送到 GreptimeDB: +``` +loki.source.file "greptime" { + targets = [ + {__path__ = "/logs.json"}, + ] + forward_to = [loki.write.greptime_loki.receiver] +} + +loki.write "greptime_loki" { + endpoint { + url = "http://127.0.0.1:4000/v1/loki/api/v1/push" + headers = { + "x-greptime-pipeline-name" = "pp", + } + } + external_labels = { + "job" = "greptime", + "from" = "alloy", + } +} +``` + +在 `greptime_loki` 中,通过 `x-greptime-pipeline-name` 的 HTTP 头来指示写入的数据需要被 pipeline 引擎处理。 + +**步骤 4:部署和运行** + +1. 首先,启动你的 GreptimeDB 实例。参见[这里](/getting-started/installation/overview.md)快速启动。 + +2. [上传](/user-guide/logs/manage-pipelines.md#create-a-pipeline) pipeline 配置到数据库: + +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/pp" -F "file=@pipeline.yaml" +``` + +3. 启动 Alloy Docker 容器来处理日志: +```shell +docker run --rm \ + -v ./config.alloy:/etc/alloy/config.alloy \ + -v ./logs.json:/logs.json \ + --network host \ + grafana/alloy:latest \ + run --server.http.listen-addr=0.0.0.0:12345 --storage.path=/var/lib/alloy/data \ + /etc/alloy/config.alloy +``` + +**步骤 5:验证结果** + +日志处理完成后,您可以验证它们是否已成功摄取和解析。数据库日志将显示摄取活动。 + +使用 MySQL 客户端查询表以查看解析的日志数据: +```sql +mysql> show tables; ++-----------+ +| Tables | ++-----------+ +| loki_logs | +| numbers | ++-----------+ +2 rows in set (0.00 sec) + +mysql> select * from loki_logs limit 1 \G +*************************** 1. row *************************** + log_time: 2025-08-21 14:23:17.892000 + log_level: ERROR +log_source: application + logger: sdk.tool.DatabaseUtil + message: Connection timeout exceeded for database pool + trace_id: a7f8c92d1e4b4c6f9d2e5a8b3f7c1d9e +1 row in set (0.01 sec) +``` + +此输出演示了 pipeline 引擎已成功解析原始 JSON 日志行,并将结构化数据提取到单独的列中。 + +有关 pipeline 配置和功能的更多详细信息,请参考[pipeline 文档](/reference/pipeline/pipeline-config.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/opentelemetry.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/opentelemetry.md new file mode 100644 index 0000000000..a78f3dc36e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/opentelemetry.md @@ -0,0 +1,292 @@ +--- +keywords: [OpenTelemetry, OTLP, metrics, logs, 数据模型] +description: 介绍如何使用 OpenTelemetry Protocol (OTLP) 将观测数据(如 metrics 和 logs)导出到 GreptimeDB,包括示例代码和数据模型的映射规则。 +--- + +# OpenTelemetry Protocol (OTLP) + +[OpenTelemetry](https://opentelemetry.io/) 是一个供应商中立的开源可观测性框架,用于检测、生成、收集和导出观测数据,例如 traces, metrics 和 logs。 +OpenTelemetry Protocol (OTLP) 定义了观测数据在观测源和中间进程(例如收集器和观测后端)之间的编码、传输机制。 + +## OpenTelemetry Collectors + +你可以很简单地将 GreptimeDB 配置为 OpenTelemetry 采集器写入的目标。 +有关更多信息,请参阅 [OTel Collector](otel-collector.md) 和[Grafana Alloy](alloy.md) 示例。 + +## HTTP 基础端点 + +适用于所有信号类型的[HTTP 基础端点](https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/#otel_exporter_otlp_endpoint) URL:`http{s}:///v1/otlp` + +当需要将多种信号类型(指标、日志和链路追踪)发送到同一目标数据库时,这个统一端点非常有用,可以简化你的 OpenTelemetry 配置。 + +## Metrics + +GreptimeDB 通过原生支持 [OTLP/HTTP](https://opentelemetry.io/docs/specs/otlp/#otlphttp) 协议,可以作为后端存储服务来接收 OpenTelemetry 指标数据。 + +### OTLP/HTTP API + +使用下面的信息通过 Opentelemetry SDK 库发送 Metrics 到 GreptimeDB: + +- URL: `https:///v1/otlp/v1/metrics` +- Headers: + - `X-Greptime-DB-Name`: `` +- `Authorization`: `Basic` 认证,是 `:` 的 Base64 编码字符串。更多信息请参考 [鉴权](https://docs.greptime.cn/user-guide/deployments-administration/authentication/static/) 和 [HTTP API](https://docs.greptime.cn/user-guide/protocols/http#authentication)。 + +请求中使用 binary protobuf 编码 payload,因此你需要使用支持 `HTTP/protobuf` 的包。例如,在 Node.js 中,可以使用 [`exporter-trace-otlp-proto`](https://www.npmjs.com/package/@opentelemetry/exporter-trace-otlp-proto);在 Go 中,可以使用 [`go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`](https://pkg.go.dev/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp);在 Java 中,可以使用 [`io.opentelemetry:opentelemetry-exporter-otlp`](https://mvnrepository.com/artifact/io.opentelemetry/opentelemetry-exporter-otlp);在 Python 中,可以使用 [`opentelemetry-exporter-otlp-proto-http`](https://pypi.org/project/opentelemetry-exporter-otlp-proto-http/)。 + +:::tip 注意 +包名可能会根据 OpenTelemetry 的发展发生变化,因此建议你参考 OpenTelemetry 官方文档以获取最新信息。 +::: + +请参考 Opentelementry 的官方文档获取它所支持的编程语言的更多信息。 + +### 示例代码 + +下面是一些编程语言设置请求的示例代码: + + + + + +```ts +const auth = Buffer.from(`${username}:${password}`).toString('base64') +const exporter = new OTLPMetricExporter({ + url: `https://${dbHost}/v1/otlp/v1/metrics`, + headers: { + Authorization: `Basic ${auth}`, + 'X-Greptime-DB-Name': db, + }, + timeoutMillis: 5000, +}) +``` + + + + + +```Go +auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", *username, *password))) +exporter, err := otlpmetrichttp.New( + context.Background(), + otlpmetrichttp.WithEndpoint(*dbHost), + otlpmetrichttp.WithURLPath("/v1/otlp/v1/metrics"), + otlpmetrichttp.WithHeaders(map[string]string{ + "X-Greptime-DB-Name": *dbName, + "Authorization": "Basic " + auth, + }), + otlpmetrichttp.WithTimeout(time.Second*5), +) +``` + + + + + +```Java +String endpoint = String.format("https://%s/v1/otlp/v1/metrics", dbHost); +String auth = username + ":" + password; +String b64Auth = new String(Base64.getEncoder().encode(auth.getBytes())); +OtlpHttpMetricExporter exporter = OtlpHttpMetricExporter.builder() + .setEndpoint(endpoint) + .addHeader("X-Greptime-DB-Name", db) + .addHeader("Authorization", String.format("Basic %s", b64Auth)) + .setTimeout(Duration.ofSeconds(5)) + .build(); +``` + + + + + +```python +auth = f"{username}:{password}" +b64_auth = base64.b64encode(auth.encode()).decode("ascii") +endpoint = f"https://{host}/v1/otlp/v1/metrics" +exporter = OTLPMetricExporter( + endpoint=endpoint, + headers={"Authorization": f"Basic {b64_auth}", "X-Greptime-DB-Name": db}, + timeout=5) +``` + + + + + +你可以在 Github 中找到可执行的 Demo:[Go](https://github.com/GreptimeCloudStarters/quick-start-go), [Java](https://github.com/GreptimeCloudStarters/quick-start-java), [Python](https://github.com/GreptimeCloudStarters/quick-start-python), and [Node.js](https://github.com/GreptimeCloudStarters/quick-start-node-js). + +:::tip 注意 +示例代码可能会根据 OpenTelemetry 的发展发生变化,因此建议你参考 OpenTelemetry 官方文档以获取最新信息。 +::: + +关于示例代码,请参考 Opentelementry 的官方文档获取它所支持的编程语言获取更多信息。 + +### 兼容 Prometheus + +从 `v0.16` 开始,GreptimeDB 为 OTLP 指标写入引入了一种 Prometheus 兼容模式。 +如果指标以这种兼容模式写入,你可以像查询 Prometheus 原生指标一样使用 PromQL 直接查询这些指标。 + +如果你之前没有使用过 OTLP 指标写入,那么 GreptimeDB 会默认使用新的兼容模式。 +否则,GreptimeDB 会对已经存在的表保留原有的数据模型,只有对新创建的指标表使用兼容模式写入。 + +GreptimeDB 会首先对数据进行预处理,包括: +1. 将指标名(表名)和标签名转换成 Prometheus 风格的命名(例如:将 `.` 替换为 `_`)。具体信息请参考[这里](https://opentelemetry.io/docs/specs/otel/compatibility/prometheus_and_openmetrics/#metric-metadata-1) +2. 默认丢弃一些 resource 属性和全部的 scope 属性。默认保存的 resource 属性列表可以参考[这里](https://prometheus.io/docs/guides/opentelemetry/#promoting-resource-attributes)。你可以通过配置项对这个行为进行调整 + +注意: OTLP 的 `Sum` 和 `Histogram` 指标的数据可能是增量时序(delta temporality)类型的。 +GreptimeDB 将会直接保存它们,不会进行累计值(cumulative value)的计算。 +参考[这里](https://grafana.com/blog/2023/09/26/opentelemetry-metrics-a-guide-to-delta-vs.-cumulative-temporality-trade-offs/)获取更多背景信息。 + +你可以通过设置 HTTP 请求头来调整预处理的行为。以下是选项列表: +You can set the HTTP headers to configure the pre-process behaviors. Here are the options: +1. `x-greptime-otlp-metric-promote-all-resource-attrs`: 保存所有 resource 资源。默认是 `false`。 +2. `x-greptime-otlp-metric-promote-resource-attrs`: 如果不保存所有 resource 资源,需要保存的资源名称列表,用 `;` 连接。 +3. `x-greptime-otlp-metric-ignore-resource-attrs`: 如果保存所有的 resource 资源,需要丢弃的资源名称列表,用 `;` 连接。 +4. `x-greptime-otlp-metric-promote-scope-attrs`: 是否需要保存 scope 资源。默认是 `false`。 + +### 数据模型 + +兼容 Prometheus 的 OTLP 指标数据模型按照下方的规则被映射到 GreptimeDB 数据模型中: + +- Metric 的名称将被作为 GreptimeDB 表的名称,当表不存在时会自动创建。 +- 只有特定 resource 属性会被默认保留。详情和配置选项见上一小节。属性在 GreptimeDB 表中会被作为 tag 列。 +- 参考 [Prometheus 数据模型](./prometheus.md#数据模型)了解更多数据模型信息。 +- ExponentialHistogram 暂时未被支持。 + +如果你在 `v0.16` 之前使用 OTLP 指标,那么数据将以非兼容模式保存。以下是数据模型在映射上的差别: + +- 所有的 Attribute,包含 resource 级别、scope 级别和 data_point 级别,都被作为 GreptimeDB 表的 tag 列。 +- Summary 类型的每个 quantile 被作为单独的数据列,列名 `greptime_pxx`,其中 xx 是 quantile 的数据,如 90 / 99 等。 + +## Logs + +GreptimeDB 是能够通过 [OTLP/HTTP](https://opentelemetry.io/docs/specs/otlp/#otlphttp) 协议原生地消费 OpenTelemetry 日志。 + +### OTLP/HTTP API + +要通过 OpenTelemetry SDK 库将 OpenTelemetry 日志发送到 GreptimeDB,请使用以下信息: + +- **URL:** `https:///v1/otlp/v1/logs` +- **Headers:** + - `X-Greptime-DB-Name`: `` + - `Authorization`: `Basic` 认证,这是一个 Base64 编码的 `:` 字符串。更多信息,请参考 [鉴权](/user-guide/deployments-administration/authentication/static.md) 和 [HTTP API](/user-guide/protocols/http.md#鉴权)。 + - `X-Greptime-Log-Table-Name`: ``(可选)- 存储日志的表名。如果未提供,默认表名为 `opentelemetry_logs`。 + - `X-Greptime-Log-Extract-Keys`: ``(可选)- 从属性中提取对应 key 的值到表的顶级字段。key 应以逗号(`,`)分隔。例如,`key1,key2,key3` 将从属性中提取 `key1`、`key2` 和 `key3`,并将它们提升到日志的顶层,设置为标签。如果提取的字段类型是数组、浮点数或对象,将返回错误。如果提供了 pipeline name,此设置将被忽略。 + - `X-Greptime-Log-Pipeline-Name`: ``(可选)- 处理日志的 pipeline 名称。如果未提供,将使用 `X-Greptime-Log-Extract-Keys` 来处理日志。 + - `X-Greptime-Log-Pipeline-Version`: ``(可选)- 处理日志的 pipeline 的版本。如果未提供,将使用 pipeline 的最新版本。 + +请求使用二进制 protobuf 编码负载,因此您需要使用支持 `HTTP/protobuf` 的包。 + +:::tip 提示 +包名可能会根据 OpenTelemetry 的更新而变化,因此我们建议您参考官方 OpenTelemetry 文档以获取最新信息。 +::: + +有关 OpenTelemetry SDK 的更多信息,请参考您首选编程语言的官方文档。 + +### 示例代码 + +请参考 [opentelemetry-collector](#opentelemetry-collector) 中的示例代码,里面包含了如何将 OpenTelemetry 日志发送到 GreptimeDB。 +也可参考 [Alloy 文档](alloy.md#日志)中的示例代码,了解如何将 OpenTelemetry 日志发送到 GreptimeDB。 + +### 数据模型 + +OTLP 日志数据模型根据以下规则映射到 GreptimeDB 数据模型: + +默认表结构: + +```sql ++-----------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-----------------------+---------------------+------+------+---------+---------------+ +| timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| trace_id | String | | YES | | FIELD | +| span_id | String | | YES | | FIELD | +| severity_text | String | | YES | | FIELD | +| severity_number | Int32 | | YES | | FIELD | +| body | String | | YES | | FIELD | +| log_attributes | Json | | YES | | FIELD | +| trace_flags | UInt32 | | YES | | FIELD | +| scope_name | String | PRI | YES | | TAG | +| scope_version | String | | YES | | FIELD | +| scope_attributes | Json | | YES | | FIELD | +| scope_schema_url | String | | YES | | FIELD | +| resource_attributes | Json | | YES | | FIELD | +| resource_schema_url | String | | YES | | FIELD | ++-----------------------+---------------------+------+------+---------+---------------+ +17 rows in set (0.00 sec) +``` + +- 您可以使用 `X-Greptime-Log-Table-Name` 指定存储日志的表名。如果未提供,默认表名为 `opentelemetry_logs`。 +- 所有属性,包括资源属性、范围属性和日志属性,将作为 JSON 列存储在 GreptimeDB 表中。 +- 日志的时间戳将用作 GreptimeDB 中的时间戳索引,列名为 `timestamp`。建议使用 `time_unix_nano` 作为时间戳列。如果未提供 `time_unix_nano`,将使用 `observed_time_unix_nano`。 + +### Append 模式 + +通过此接口创建的表,默认为[Append 模式](/user-guide/deployments-administration/performance-tuning/design-table.md#何时使用-append-only-表). + +## Traces + +GreptimeDB 支持直接写入 OpenTelemetry 协议的 traces 数据,并内置 OpenTelemetry 的 traces 的表模型来让用户方便地查询和分析 traces 数据。 + +### OTLP/HTTP API + +你可以使用 [OpenTelemetry SDK](https://opentelemetry.io/docs/languages/) 或其他类似的技术方案来为应用添加 traces 数据。你还可以用 [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) 来收集 traces 数据,并使用 GreptimeDB 作为后端存储。 + +要通过 OpenTelemetry SDK 库将 OpenTelemetry 的 traces 数据发送到 GreptimeDB,请使用以下信息: + +- URL: `http{s}:///v1/otlp/v1/traces` +- Headers: headers 与 [Logs](#Logs) 部分相同,你可以参考 [Logs](#Logs) 部分获取更多信息。 + +默认地,GreptimeDB 会将 traces 数据写入到 `public` 数据库中的 `opentelemetry_traces` 表中。如果想要将 traces 数据写入到不同的表中,你可以使用 `X-Greptime-DB-Name` 和 `X-Greptime-Log-Table-Name` 头部信息来指定数据库和表名。 + +GreptimeDB 会接受 **protobuf 编码的 traces 数据** 通过 **HTTP 协议** 发送,其中对 HTTP header 有如下要求: + +- `content-type` 应配置为 `application/x-protobuf`; +- `x-greptime-pipeline-name` 应配置为 `greptime_trace_v1`; + +### 示例代码 + +你可以直接将 OpenTelemetry traces 数据发送到 GreptimeDB,也可以使用 OpenTelemetry Collector 来收集 traces 数据,并使用 GreptimeDB 作为后端存储,请参考 [OpenTelemetry Collector 文档](/user-guide/traces/read-write.md#opentelemetry-collector)中的示例代码,了解如何将 OpenTelemetry traces 数据发送到 GreptimeDB。 + +### 数据模型 + +OTLP traces 数据模型根据以下规则映射到 GreptimeDB 数据模型: + +默认表结构: + +```sql ++------------------------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++------------------------------------+---------------------+------+------+---------+---------------+ +| timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| timestamp_end | TimestampNanosecond | | YES | | FIELD | +| duration_nano | UInt64 | | YES | | FIELD | +| parent_span_id | String | | YES | | FIELD | +| trace_id | String | | YES | | FIELD | +| span_id | String | | YES | | FIELD | +| span_kind | String | | YES | | FIELD | +| span_name | String | | YES | | FIELD | +| span_status_code | String | | YES | | FIELD | +| span_status_message | String | | YES | | FIELD | +| trace_state | String | | YES | | FIELD | +| scope_name | String | | YES | | FIELD | +| scope_version | String | | YES | | FIELD | +| service_name | String | PRI | YES | | TAG | +| span_attributes.net.sock.peer.addr | String | | YES | | FIELD | +| span_attributes.peer.service | String | | YES | | FIELD | +| span_events | Json | | YES | | FIELD | +| span_links | Json | | YES | | FIELD | ++------------------------------------+---------------------+------+------+---------+---------------+ +``` + +- 每一行代表一个单一的 span; +- 核心的 OpenTelemetry 字段,如 `trace_id`, `span_id`, 和 `service_name` 等将被单独作为表的列; +- Resource Attributes 和 Span Attributes 将被自动展平为单独的列,列名为其 JSON 格式表示时的 key(多层嵌套时将用 `.` 连接); +- `span_events` 和 `span_links` 默认存储为 JSON 数据类型; + +注意: +1. `greptime_trace_v1` 处理方式默认通过 `trace_id` 字段将数据切分成不同的分区以提升性能。**请确保 `trace_id` 的第一个字符是分布均匀的**。 +2. 在非测试的场合下,可以通过设置 `ttl` 以避免持久化数据量过大。通过设置 `x-greptime-hints: ttl=7d` HTTP 请求头,在创建 trace 表时会添加一个 7 天的 `ttl` 表选项。见[此文档](/reference/sql/create.md#表选项)了解更多关于表选项 `ttl` 的信息。 + +### Append 模式 + +通过此接口创建的表,默认为[Append 模式](/user-guide/deployments-administration/performance-tuning/design-table.md#何时使用-append-only-表). diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/otel-collector.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/otel-collector.md new file mode 100644 index 0000000000..d18aa60f49 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/otel-collector.md @@ -0,0 +1,80 @@ +--- +keywords: [OpenTelemetry, OTLP, metrics, logs, traces, integration, 'otel-collector', 集成] +description: 与 GreptimeDB 集成 OpenTelemetry Collector 的指南。 +--- + +# OTel Collector + +[OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) 提供了一种与供应商无关的 OTEL 实现,用于接收、处理和导出可观测数据。它可以作为数据的中间层,将数据从不同的源发送到 GreptimeDB。 +以下是使用 OpenTelemetry Collector 将数据发送到 GreptimeDB 的配置示例。 + +```yaml +extensions: + basicauth/client: + client_auth: + username: + password: + +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +exporters: + otlphttp/traces: + endpoint: 'http://127.0.0.1:4000/v1/otlp' + # auth: + # authenticator: basicauth/client + headers: + # x-greptime-db-name: '' + x-greptime-pipeline-name: 'greptime_trace_v1' + tls: + insecure: true + otlphttp/logs: + endpoint: 'http://127.0.0.1:4000/v1/otlp' + # auth: + # authenticator: basicauth/client + headers: + # x-greptime-db-name: '' + # x-greptime-log-table-name: '' + # x-greptime-pipeline-name: '' + tls: + insecure: true + + otlphttp/metrics: + endpoint: 'http://127.0.0.1:4000/v1/otlp' + # auth: + # authenticator: basicauth/client + headers: + # x-greptime-db-name: '' + tls: + insecure: true + +service: + # extensions: [basicauth/client] + pipelines: + traces: + receivers: [otlp] + exporters: [otlphttp/traces] + logs: + receivers: [otlp] + exporters: [otlphttp/logs] + metrics: + receivers: [otlp] + exporters: [otlphttp/metrics] +``` + +在上面的配置中,我们定义了一个接收器 `otlp`,它可以接收来自 OpenTelemetry 的数据。我们还定义了三个导出器 `otlphttp/traces`、`otlphttp/logs` 和 `otlphttp/metrics`,它们将数据发送到 GreptimeDB 的 OTLP 路径。 + +在 otlphttp 协议的基础上,我们增加了一些 header 用来指定一些参数,比如 `x-greptime-pipeline-name` 和 `x-greptime-log-table-name`: +* `x-greptime-pipeline-name` 用来指定要使用的 pipeline 名称 +* `x-greptime-log-table-name` 用来指定数据将要写入 GreptimeDB 的表名。 + +如果你在 GreptimeDB 设置了[鉴权](/user-guide/deployments-administration/authentication/overview.md)。则需要使用 `basicauth/client` 扩展来处理基本的身份验证。 + +这里我们强烈建议使用不同的导出器来分别处理 traces、logs 和 metrics 数据,一方面是因为 GreptimeDB 会支持一些特定的 header 来自定义一些处理流程,另一方面也可以做好数据隔离。 + +关于 OpenTelemetry 协议的更多信息,请阅读[文档](/user-guide/ingest-data/for-observability/opentelemetry.md)。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/overview.md new file mode 100644 index 0000000000..6520dca683 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/overview.md @@ -0,0 +1,17 @@ +--- +keywords: [可观测性, Prometheus, Vector, OpenTelemetry, InfluxDB Line Protocol] +description: 介绍 GreptimeDB 在可观测性场景中的应用,包括与 Prometheus、Vector、OpenTelemetry 和 InfluxDB Line Protocol 的集成。 +--- + +# 可观测场景数据写入 + +在可观测性场景中,实时监控和分析系统性能的能力至关重要。 +GreptimeDB 与领先的可观测性工具无缝集成,为你提供系统健康和性能指标的全面视图。 + +- [在 GreptimeDB 中存储万亿级日志,并快速获得分析结果](/user-guide/logs/overview.md). +- [Prometheus Remote Write](prometheus.md):将 GreptimeDB 作为 Prometheus 的远程存储,适用于实时监控和警报。 +- [Vector](vector.md):将 GreptimeDB 用作 Vector 的接收端,适用于复杂的数据流水线和多样化的数据源。 +- [OpenTelemetry](opentelemetry.md):将 telemetry 数据收集并导出到 GreptimeDB,以获取详细的可观测性洞察。 +- [InfluxDB Line Protocol](influxdb-line-protocol.md):一种广泛使用的时间序列数据协议,便于从 InfluxDB 迁移到 GreptimeDB。该文档同样介绍了 Telegraf 的集成方式。 +- [Loki](loki.md):一种广泛使用的日志写入协议,便于从 Loki 迁移到 GreptimeDB。本文档还介绍了 Alloy 集成方法。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/prometheus.md new file mode 100644 index 0000000000..4665963543 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/prometheus.md @@ -0,0 +1,330 @@ +--- +keywords: [Prometheus, 长期存储, Remote Write, 数据模型, 配置示例] +description: 介绍如何将 GreptimeDB 作为 Prometheus 的长期存储解决方案,包括配置 Remote Write 和数据模型的映射规则。 +--- + +# Prometheus + +GreptimeDB 可以作为 Prometheus 的长期存储解决方案,提供无缝集成体验。 + +## 配置 Remote Write + +### Prometheus 配置文件 + +要将 GreptimeDB 集成到 Prometheus 中, +请按照以下步骤更新你的 [Prometheus 配置文件](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#configuration-file)(`prometheus.yml`): + +```yaml +remote_write: +- url: http://localhost:4000/v1/prometheus/write?db=public +# 如果启用了身份验证,请取消注释并设置鉴权信息 +# basic_auth: +# username: greptime_user +# password: greptime_pwd + +remote_read: +- url: http://localhost:4000/v1/prometheus/read?db=public +# 如果启用了身份验证,请取消注释并设置鉴权信息 +# basic_auth: +# username: greptime_user +# password: greptime_pwd +``` + +- URL 中的 host 和 port 表示 GreptimeDB 服务器。在此示例中,服务器运行在 `localhost:4000` 上。你可以将其替换为你自己的服务器地址。有关 GreptimeDB 中 HTTP 协议的配置,请参阅 [协议选项](/user-guide/deployments-administration/configuration.md#protocol-options)。 +- URL 中的 `db` 参数表示要写入的数据库。它是可选的。默认情况下,数据库设置为 `public`。 +- `basic_auth` 是身份鉴权配置。如果 GreptimeDB 启用了鉴权,请填写用户名和密码。请参阅 [鉴权认证文档](/user-guide/deployments-administration/authentication/overview.md)。 + +### Grafana Alloy 配置文件 + +如果你使用 Grafana Alloy,请在 Alloy 配置文件(`config.alloy`)中配置 Remote Write。有关更多信息,请参阅 [Alloy 文档](alloy.md#prometheus-remote-write)。 + +### Vector 配置文件 + +如果你使用 Vector ,请在 Vector 配置文件(`vector.toml`)中配置 Remote Write。有关更多信息,请参阅 [Vector 文档](vector.md#使用-prometheus-remote-write-协议). + +## 数据模型 + +在 GreptimeDB 的[数据模型](/user-guide/concepts/data-model.md)中,数据被组织成具有 tag、time index 和 field 的表。 +GreptimeDB 可以被视为多值数据模型,自动将多个 Prometheus 指标分组到相应的表中。 +这样可以实现高效的数据管理和查询。 + +![数据模型](/PromQL-multi-value-data-model.png) + +当指标通过远程写入端点写入 GreptimeDB 时,它们将被转换为以下形式: + +| Sample Metrics | In GreptimeDB | GreptimeDB Data Types | +| -------------- | ------------------------- | --------------------- | +| Name | Table (Auto-created) Name | String | +| Value | Column (Field) | Double | +| Timestamp | Column (Time Index) | Timestamp | +| Label | Column (Tag) | String | + +例如,以下 Prometheus 指标: + +```txt +prometheus_remote_storage_samples_total{instance="localhost:9090", job="prometheus", +remote_name="648f0c", url="http://localhost:4000/v1/prometheus/write"} 500 +``` + +将被转换为表 `prometheus_remote_storage_samples_total` 中的一行: + +| Column | Value | Column Data Type | +| :----------------- | :------------------------------------------ | :----------------- | +| instance | localhost:9090 | String | +| job | prometheus | String | +| remote_name | 648f0c | String | +| url | `http://localhost:4000/v1/prometheus/write` | String | +| greptime_value | 500 | Double | +| greptime_timestamp | The sample's unix timestamp | Timestamp | + + +## 通过使用 metric engine 提高效率 + +Prometheus Remote Write 写入数据的方式经常会创建大量的小表,这些表在 GreptimeDB 中被归类为逻辑表。 +然而,拥有大量的小表对于数据存储和查询性能来说是低效的。 +为了解决这个问题,GreptimeDB 引入了 [metric engine](/contributor-guide/datanode/metric-engine.md) 功能,将逻辑表表示的数据存储在单个物理表中。 +这种方法减少了存储开销并提高了列式压缩效率。 + +GreptimeDB 默认启用 metric engine,你不需要指定任何额外的配置。 +默认情况下,使用的物理表为 `greptime_physical_table`。 +如果你想使用特定的物理表,可以在 Remote Write URL 中指定 `physical_table` 参数。 +如果指定的物理表不存在,它将被自动创建。 + +```yaml +remote_write: +- url: http://localhost:4000/v1/prometheus/write?db=public&physical_table=greptime_physical_table +``` + +虽然数据被存储在物理表中,但查询可以在逻辑表上执行以提供从指标角度的直观视角。 +例如,当成功写入数据时,你可以使用以下命令显示逻辑表: + +```sql +show tables; +``` + +```sql ++---------------------------------------------------------------+ +| Tables | ++---------------------------------------------------------------+ +| prometheus_remote_storage_enqueue_retries_total | +| prometheus_remote_storage_exemplars_pending | +| prometheus_remote_storage_read_request_duration_seconds_count | +| prometheus_rule_group_duration_seconds | +| ...... | ++---------------------------------------------------------------+ +``` + +物理表本身也可以进行查询。 +它包含了所有逻辑表的列,方便进行多表连接分析和计算。 + +要查看物理表的 schema,请使用 `DESC TABLE` 命令: + +```sql +DESC TABLE greptime_physical_table; +``` + +物理表包含了所有逻辑表的列: + +```sql ++--------------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+----------------------+------+------+---------+---------------+ +| greptime_timestamp | TimestampMillisecond | PRI | NO | | TIMESTAMP | +| greptime_value | Float64 | | YES | | FIELD | +| __table_id | UInt32 | PRI | NO | | TAG | +| __tsid | UInt64 | PRI | NO | | TAG | +| device | String | PRI | YES | | TAG | +| instance | String | PRI | YES | | TAG | +| job | String | PRI | YES | | TAG | +| error | String | PRI | YES | | TAG | +... +``` + +你可以使用 `SELECT` 语句根据需要从物理表中过滤数据。 +例如,根据逻辑表 A 的 `device` 条件和逻辑表 B 的 `job` 条件来过滤数据: + +```sql +SELECT * +FROM greptime_physical_table +WHERE greptime_timestamp > "2024-08-07 03:27:26.964000" + AND device = "device1" + AND job = "job1"; +``` + +### 在 GreptimeDB 集群上使用 metric engine + +在使用 Prometheus remote write 写入 GreptimeDB 集群时,用户可能注意到集群中只有 +一 个 datanode 承载写入压力,其他节点没有流量。这是由于在默认配置下,集群中只有 +一个 metric engine 物理表,且该表只有一个分区。承载此分区的节点将承担所有写入流 +量。 + +为什么我们没有创建更多的分区呢?[GreptimeDB 的表分 +区](/user-guide/deployments-administration/manage-data/table-sharding.md)基于预 +定义的分区列。然而在 Prometheus 生态中并没有普遍存在的列(Prometheus 中的标签) +适合作为默认分区列。 + +因此,我们推荐用户基于自己的数据模型创建分区规则。例如,在监控 Kubernetes 集群的 +场景下,`namespace` 可能是一个比较好的分区键。这个分区键应当具备一定的基数用于区 +分数据。并且我们推荐用户在初始时创建 datanode 数量大约 2 倍至 3 倍的分区数量,为日后 +集群扩容负载均衡做准备。 + +以下是一个分区的物理表例子: + +```sql +CREATE TABLE greptime_physical_table ( + greptime_timestamp TIMESTAMP(3) NOT NULL, + greptime_value DOUBLE NULL, + namespace STRING PRIMARY KEY, + TIME INDEX (greptime_timestamp), +) +PARTITION ON COLUMNS (namespace) ( + namespace <'g', + namespace >= 'g' AND namespace < 'n', + namespace >= 'n' AND namespace < 't', + namespace >= 't' +) +ENGINE = metric +with ( + "physical_metric_table" = "", +); +``` + +注意这里用户并不需要手动指定所有可能的主键(标签),metric engine 将会自动添加。 +只有涉及到分区规则的列需要进行提前指定。 + +## 特殊标签 + +:::warning 实验性特性 +此实验性功能可能存在预期外的行为,其功能未来可能发生变化。 +::: + +一般来说,一次 Remote write 请求的全部数据会以同样的配置项被写入到数据库中,例如,开启 metric engine 后使用的同一个物理表配置。 +即使指标的数量在增长,所有的逻辑表(即指标们)都会保存到同一张物理表中。 +对于写入这可能是没问题的。但是对于需要查询一小部分指标的场景,这种设置可能会拖慢查询速度,因为所有的指标都聚集在一张物理表上,而数据库需要对全表的数据进行扫描。 + +如果你可以预见大量的数据写入和每次只需查询小部分指标的场景,那么可以在写入时对存储位置进行划分以减缓后续查询的压力。 +对于一个 Remote write 请求中的每个指标,这种精细的控制可以通过写入时的配置项来达成。 + +从 `v0.15` 开始,GreptimeDB 新增了对特殊标签的支持。 +这些标签(与它们的值)会在解析阶段被转换成写入时的配置项,使请求内的单个指标可以被更精细地控制。 +这些标签不是互斥的,它们可以通过组合的方式达成更多样化的控制选择。 + +以下是指标特殊标签的一个示例,注意这不是实际的数据模型。 +| `__name__` | `__database__` | `__physical_table__` | `pod_name_label` | `__normal_label_with_underscore_prefix__` | `timestamp` | `value` | +|------------------|----------------|----------------------|---------------------|-------------------------------------------|-------------------------|---------| +| some_metric_name | public | p_1 | random_k8s_pod_name | true | 2025-06-17 16:31:52.000 | 12.1 | + +上述特殊标签只是在 Prometheus 中的普通有效标签。 +GreptimeDB 可以识别一些标签的名称,并将它们转换成写入时的配置项。 +就像自定义的 HTTP header 一样,你可以通过设定一些有效的 HTTP header 键值对来指示后续的操作,只是这些 header 键值对在特定的程序之外不起任何作用。 + +以下是所有 GreptimeDB 支持的标签名称: +- `__database__` +- `__physical_table__` + +### 设置标签 + +如何将标签设置到指标上,与你所使用的收集指标并发送到数据库的工具(或者代码)相关。 + +如果你使用 Prometheus 从源获取指标并使用 Remote write 将他们发送到 GreptimeDB 中,可以在全局设定中增加 `external_labels` 的配置。 +参考这个[文档](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#configuration-file)。 +对于其他的收集工具也是一样的。对于你所使用的工具,你可能需要查找相应的设置。 + +### `__database__` + +这个选项决定指标数据会被保存到哪个数据库中,该数据库需要被提前创建好(例如通过 `create database xxx` SQL 语句)。 + +一般来说,同样的技术栈会产生同样名称的指标。 +例如你有两个 Kubernetes 集群,但是运行了不同的应用,然后通过一个指标收集工具同时收集两个集群的指标。 +这两个集群会产生名称一样但是标签和值完全不同的指标。 +如果这些指标被写入到同一个数据库中,那么在使用 Grafana 大盘浏览这些指标的时候,就需要对大盘的每个图表手动设置标签值,才能区分集群进行查看。 +这样既繁琐又低效。 + +在这种情况下,你可以在写入时将指标保存到两个不同的数据库中,然后使用两个大盘分别浏览这些指标。 + +### `__physical_table__` + +如果指标通过 metric engine 进行存储,那么每个指标的逻辑表背后是一张物理表。 +默认下,所有的指标都使用同一张物理表。 +随着指标数量的增长,这张物理表会变成一张超级宽表。如果指标的写入频率不同,那么物理表的数据将会是稀疏的。 +在全量指标数据集中查找一个特定的指标或者标签将会消耗大量时间,因为数据库需要扫描所有不相关的数据。 + +这种场景下,将指标写入到不同的物理表可以减轻单一物理表的压力,这对通过写入频率来聚合指标的场景非常有用。 + +注意,指标的逻辑表在创建时就与物理表一一关联。在同一数据库下为同一指标设定不同的物理表不会生效。 + +## 在 Remote write 中使用 pipeline + +:::warning 实验性特性 +此实验性功能可能存在预期外的行为,其功能未来可能发生变化。 +::: + +从 `v0.15` 开始,GreptimeDB 支持在 Prometheus Remote Write 协议入口使用 pipeline 处理数据。 +你可以通过在 HTTP header 中将 `x-greptime-pipeline-name` 的值设置为需要执行的 pipeline 名称来使用 pipeline 处理流程。 + +以下是一个非常简单的 pipeline 配置例子,使用 `vrl` 处理器来对每个指标增加一个 `source` 标签: +```YAML +version: 2 +processors: + - vrl: + source: | + .source = "local_laptop" + . + +transform: + - field: greptime_timestamp + type: time, ms + index: timestamp +``` + +结果如下所示 +``` +mysql> select * from `go_memstats_mcache_inuse_bytes`; ++----------------------------+----------------+--------------------+---------------+--------------+ +| greptime_timestamp | greptime_value | instance | job | source | ++----------------------------+----------------+--------------------+---------------+--------------+ +| 2025-07-11 07:42:03.064000 | 1200 | node_exporter:9100 | node-exporter | local_laptop | +| 2025-07-11 07:42:18.069000 | 1200 | node_exporter:9100 | node-exporter | local_laptop | ++----------------------------+----------------+--------------------+---------------+--------------+ +2 rows in set (0.01 sec) +``` + +更多配置详情请参考 [pipeline 相关文档](/reference/pipeline/pipeline-config.md)。 + +## 性能优化 + +默认情况下,metric engine 会自动创建一个名为 `greptime_physical_table` 的物理表。 +为了优化性能,你可以选择创建一个具有自定义配置的物理表。 + +### 启用跳数索引 + +默认情况下,metric engine 不会为列创建索引。你可以通过设置 `index.type` 为 `skipping` 来设置索引类型。 + +创建一个带有跳数索引的物理表。所有自动添加的列都将应用跳数索引。 + +```sql +CREATE TABLE greptime_physical_table ( + greptime_timestamp TIMESTAMP(3) NOT NULL, + greptime_value DOUBLE NULL, + TIME INDEX (greptime_timestamp), +) +engine = metric +with ( + "physical_metric_table" = "", + "index.type" = "skipping" +); +``` +有关更多配置,请参阅 [create table](/reference/sql/create.md#create-table) 部分。 + + +## VictoriaMetrics Remote Write + +VictoriaMetrics 对 Prometheus 远程写入协议进行了轻微修改,以实现更好的压缩效果。 +当你使用 `vmagent` 将数据发送到兼容的后端时,该协议会被自动启用。 + +GreptimeDB 也支持这个变种。只需将 GreptimeDB 的 Remote Write URL 配置为 `vmagent`。 +例如,如果你在本地安装了 GreptimeDB: + +```shell +vmagent -remoteWrite.url=http://localhost:4000/v1/prometheus/write +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/vector.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/vector.md new file mode 100644 index 0000000000..166f075399 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/for-observability/vector.md @@ -0,0 +1,211 @@ +--- +keywords: [Vector, 数据写入, gRPC 通信, 数据模型, 配置示例] +description: 介绍如何使用 Vector 将数据写入 GreptimeDB,包括最小配置示例和数据模型的映射规则。 +--- + +# Vector + +:::tip 注意 +本文档基于 Vector v0.49.0 版本编写。 +以下的所有示例配置均基于此版本。对于各个 sink 的 host 和 port 配置请根据自己 GreptimeDB 实例的实际情况进行调整。 +下文中的所有 port 值均为默认值。 +::: + +Vector 是高性能的可观测数据管道。 +它原生支持 GreptimeDB 指标数据接收端。 +通过 Vector,你可以从各种来源接收指标数据,包括 Prometheus、OpenTelemetry、StatsD 等。 +GreptimeDB 可以作为 Vector 的 Sink 组件来接收指标数据。 + +## 写入指标数据 + +GreptimeDB 支持多种指标数据写入方式,包括: + +- 使用 [`greptimedb_metrics` sink](https://vector.dev/docs/reference/configuration/sinks/greptimedb_metrics/) +- 使用 InfluxDB 行协议格式将指标数据写入 GreptimeDB +- 使用 Prometheus Remote Write 协议将指标数据写入 GreptimeDB + +### 使用 `greptimedb_metrics` sink + +#### 示例 + +以下是一个使用 `greptimedb_metrics` sink 写入宿主机指标的示例配置: + +```toml +# sample.toml + +[sources.in] +type = "host_metrics" + +[sinks.my_sink_id] +inputs = ["in"] +type = "greptimedb_metrics" +endpoint = ":4001" +dbname = "" +username = "" +password = "" +new_naming = true +``` + +Vector 使用 gRPC 与 GreptimeDB 进行通信,因此 Vector sink 的默认端口是 `4001`。 +如果你在使用 [自定义配置](/user-guide/deployments-administration/configuration.md#configuration-file) 启动 GreptimeDB 时更改了默认的 gRPC 端口,请使用你自己的端口。 + +如有更多需求请前往 [Vector GreptimeDB Configuration](https://vector.dev/docs/reference/configuration/sinks/greptimedb_metrics/) 查看更多配置项。 + +#### 数据模型 + +我们使用这样的规则将 Vector 指标存入 GreptimeDB: + +- 使用 `_` 作为 GreptimeDB 的表名,例如 `host_cpu_seconds_total`; +- 将指标中的时间戳作为 GreptimeDB 的时间索引,默认列名 `ts`; +- 指标所关联的 tag 列将被作为 GreptimeDB 的 tag 字段; +- Vector 的指标,和其他指标类似,有多种子类型: + - Counter 和 Gauge 类型的指标,数值直接被存入 `val` 列; + - Set 类型,我们将集合的数据个数存入 `val` 列; + - Distribution 类型,各个百分位数值点分别存入 `pxx` 列,其中 xx 是 quantile 数值,此外我们还会记录 `min/max/avg/sum/count` 列; + - AggregatedHistoragm 类型,每个 bucket 的数值将被存入 `bxx` 列,其中 xx 是 bucket 数值的上限,此外我们还会记录 `sum/count` 列; + - AggregatedSummary 类型,各个百分位数值点分别存入 `pxx` 列,其中 xx 是 quantile 数值,此外我们还会记录 `sum/count` 列; + - Sketch 类型,各个百分位数值点分别存入 `pxx` 列,其中 xx 是 quantile 数值,此外我们还会记录 `min/max/avg/sum` 列; + +### 使用 InfluxDB 行协议格式 + +可以使用 `influx` sink 来写入指标数据。我们推荐使用 v2 版本的 InfluxDB 行协议格式。 + +以下是一个使用 `influx` sink 写入宿主机指标的示例配置: + +```toml +# sample.toml + +[sources.my_source_id] +type = "internal_metrics" + +[sinks.my_sink_id] +type = "influxdb_metrics" +inputs = [ "my_source_id" ] +bucket = "public" +endpoint = "http://:4000/v1/influxdb" +org = "" +token = "" +``` + +上述配置使用的是 InfluxDB 行协议的 v2 版本。Vector 会根据 TOML 配置中的的字段来判断 InfluxDB 协议的版本,所以请务必确保配置中存在 `bucket`、`org` 和 `token` 字段。具体字段的解释如下: + +- `type`: InfluxDB 行协议的值为 `influxdb_metrics`. +- `bucket`: GreptimeDB 中的 database 名称。 +- `org`: GreptimeDB 中的组织名称(需置空)。 +- `token`: 用于身份验证的令牌(需置空)。由于 Influx 行协议的 token 有特殊形式,必须以 `Token ` 开头。这和 GreptimeDB 的鉴权方式有所不同,且目前不兼容。如果使用的是含有鉴权的 GreptimeDB 实例,请使用 `greptimedb_metrics`。 + +更多细节请参考 [InfluxDB Line Protocol 文档](../for-iot/influxdb-line-protocol.md) 了解如何使用 InfluxDB Line Protocol 将数据写入到 GreptimeDB。 + +### 使用 Prometheus Remote Write 协议 + +以下是一个使用 Prometheus Remote Write 协议写入宿主机指标的示例配置: + +```toml +# sample.toml + +[sources.my_source_id] +type = "internal_metrics" + +[sinks.prometheus_remote_write] +type = "prometheus_remote_write" +inputs = [ "my_source_id" ] +endpoint = "http://:4000/v1/prometheus/write?db=" +compression = "snappy" +auth = { strategy = "basic", username = "", password = "" } +``` + +## 写入日志数据 + +GreptimeDB 支持多种日志数据写入方式,包括: + +- 使用 [`greptimedb_logs` sink](https://vector.dev/docs/reference/configuration/sinks/greptimedb_logs/) 将日志数据写入 GreptimeDB。 +- 使用 Loki 协议将日志数据写入 GreptimeDB。 + +我们强烈建议所有的用户使用 `greptimedb_logs` sink 来写入日志数据,因为它是为 GreptimeDB 优化的,能够更好地支持 GreptimeDB 的特性。 +并且推荐开启各种协议的压缩功能,以提高数据传输效率。 + +### 使用 `greptimedb_logs` sink (推荐) + +```toml +# sample.toml + +[sources.my_source_id] +type = "demo_logs" +count = 10 +format = "apache_common" +interval = 1 + +[sinks.my_sink_id] +type = "greptimedb_logs" +inputs = [ "my_source_id" ] +compression = "gzip" +dbname = "public" +endpoint = "http://:4000" +extra_headers = { "skip_error" = "true" } +pipeline_name = "greptime_identity" +table = "" +username = "" +password = "" + +[sinks.my_sink_id.extra_params] +source = "vector" +x-greptime-pipeline-params = "max_nested_levels=10" +``` + +此示例展示了如何使用 `greptimedb_logs` sink 将生成的 demo 日志数据写入 GreptimeDB。更多信息请参考 [Vector greptimedb_logs sink](https://vector.dev/docs/reference/configuration/sinks/greptimedb_logs/) 文档。 + +### 使用 Loki 协议 + +#### 示例 + +```toml +[sources.generate_syslog] +type = "demo_logs" +format = "syslog" +count = 100 +interval = 1 + + +[transforms.remap_syslog] +inputs = ["generate_syslog"] +type = "remap" +source = """ +.labels = { + "host": .host, + "service": .service, +} +.structured_metadata = { + "source_type": .source_type +} +""" + + +[sinks.my_sink_id] +type = "loki" +inputs = ["remap_syslog"] +compression = "snappy" +endpoint = "http://:4000" +out_of_order_action = "accept" +path = "/v1/loki/api/v1/push" +encoding = { codec = "raw_message" } +labels = { "*" = "{{labels}}" } +structured_metadata = { "*" = "{{structured_metadata}}" } +auth = {strategy = "basic", user = "", password = ""} +``` + +上述配置为使用 Loki 协议将日志数据写入 GreptimeDB。具体的配置项说明如下: + +- `compression`:设置了数据传输时的压缩算法,这里使用了 `snappy`。 +- `endpoint`:指定了 Loki 的接收地址。 +- `out_of_order_action`:设置了如何处理乱序的日志,这里选择了 `accept`,表示接受乱序日志。GreptimeDB 支持乱序日志的写入。 +- `path`:指定了 Loki 的 API 路径。 +- `encoding`:设置了数据的编码方式,这里使用了 `raw_message`。 +- `labels`:指定了日志的标签,这里将 `labels` 的内容映射为 `{{labels}}`。即 remap_syslog 中的 `labels` 字段。 +- `structured_metadata`:指定了结构化元数据,这里将 `structured_metadata` 的内容映射为 `{{structured_metadata}}`。即 remap_syslog 中的 `structured_metadata` 字段。 + +关于 `labels` 和 `structured_metadata` 的含义,请参考 [Loki 文档](https://grafana.com/docs/loki/latest/get-started/labels/bp-labels/)。 + +对于 loki 协议,`labels` 默认会使用时序场景下的 Tag 类型,请注意这部分字段不要使用高基数字段。 +`structured_metadata` 将会整体存储为一个 json 字段。 +请注意,由于 Vector 的配置里不允许设置 header 所以无法指定 pipeline。 +如果需要使用 pipeline 功能,请考虑使用 `greptimedb_logs` sink。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/overview.md new file mode 100644 index 0000000000..9ce0df81da --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/ingest-data/overview.md @@ -0,0 +1,29 @@ +--- +keywords: [自动生成表结构, schema 写入, 数据写入方法, 数据管理, 数据集成] +description: 介绍 GreptimeDB 的自动生成表结构功能和推荐的数据写入方法,并提供下一步学习的链接。 +--- + +# 写入数据 + +GreptimeDB 支持自动生成表结构和灵活的数据写入方法, +使你能够轻松地根据特定场景写入数据。 + +## 自动生成表结构 + +GreptimeDB 支持无 schema 写入,即在数据写入时自动创建表格并添加必要的列。 +这种能力确保你无需事先手动定义 schema,从而更容易管理和集成各种数据源。 + +此功能适用于所有协议和集成,除了 [SQL](./for-iot/sql.md)。 + +## 推荐的数据写入方法 + +GreptimeDB 支持针对特定场景的各种数据写入方法,以确保最佳性能和集成灵活性。 + +- [可观测场景](./for-observability/overview.md):适用于实时监控和警报。 +- [物联网场景](./for-iot/overview.md):适用于实时数据和复杂的物联网基础设施。 + +## 下一步 + +- [查询数据](/user-guide/query-data/overview.md): 学习如何通过查询 GreptimeDB 数据库来探索数据。 +- [管理数据](/user-guide/manage-data/overview.md): 学习如何更新和删除数据等,确保数据完整性和高效的数据管理。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/alloy.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/alloy.md new file mode 100644 index 0000000000..26e807fa70 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/alloy.md @@ -0,0 +1,9 @@ +--- +keywords: [Alloy, Grafana Alloy, GreptimeDB] +description: 将 GreptimeDB 与 Grafana Alloy 集成。 +--- + +# Grafana Alloy + +你可以将 GreptimeDB 设置为 Grafana Alloy 的数据接收端。 +更多信息,请参考[通过 Grafana Alloy 写入数据](/user-guide/ingest-data/for-observability/alloy.md)指南。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/coroot.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/coroot.md new file mode 100644 index 0000000000..3d3d6b7369 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/coroot.md @@ -0,0 +1,44 @@ +--- +keywords: [Coroot, APM, Observability, Prometheus, integration] +description: 将 GreptimeDB 与 Coroot 集成。 +--- + +# Coroot + +Coroot 是一个开源的 APM 和可观测性工具, +是 DataDog 和 NewRelic 的替代方案。 +预定义的仪表板具备指标、日志、链路追踪、持续性能分析 +和基于 SLO 的告警功能。 + +GreptimeDB 可以配置为 Coroot 中的 Prometheus 数据存储。 +要将 GreptimeDB 集成到 Coroot 中, +需要在 Coroot 仪表板中导航到 Settings, +选择 Prometheus 配置,然后输入以下信息: + +- Prometheus URL: `http{s}:///v1/prometheus` +- 如果你在 GreptimeDB 上[启用了身份验证](/user-guide/deployments-administration/authentication/static.md),请勾选 HTTP basic auth 并输入 GreptimeDB 用户名和密码。如果没有启用身份认证,保留未勾选状态即可。 +- Remote Write URL: `http{s}:///v1/prometheus/write?db=` + +## 示例配置 + +如果你的 GreptimeDB 被部署在 `localhost`,HTTP 服务端口为 `4000`,已启用身份验证, +并且使用默认数据库 `public`, +请使用以下配置: + +- Prometheus URL: `http://localhost:4000/v1/prometheus` +- 启用 HTTP basic auth 选项并输入 GreptimeDB 用户名和密码 +- Remote Write URL: `http://localhost:4000/v1/prometheus/write?db=public` + +下图是 Coroot 的配置示例: + +

+ Coroot 配置示例 +

+ +配置保存成功后, +你就可以开始使用 Coroot 监控实例了。 +下图展示了使用 GreptimeDB 作为数据源的 Coroot 仪表板示例: + +![coroot-cpu](/coroot-cpu.png) + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/dbeaver.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/dbeaver.md new file mode 100644 index 0000000000..ca694629fb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/dbeaver.md @@ -0,0 +1,27 @@ +--- +keywords: [DBeaver, MySQL Driver, 数据库工具, 连接 GreptimeDB, 配置连接, 数据库管理] +description: 介绍如何使用 DBeaver 通过 MySQL Driver 连接到 GreptimeDB,包括配置连接的详细步骤。 +--- + +# DBeaver + +[DBeaver](https://dbeaver.io/) 是一个免费、开源且跨平台的数据库工具,支持所有流行的数据库。 +由于其易用性和丰富的功能集,它在开发人员和数据库管理员中非常受欢迎。 +你可以使用 DBeaver 通过 MySQL Driver 连接到 GreptimeDB。 + +点击 DBeaver 工具栏中的“New Database Connection”按钮,以创建 GreptimeDB 的新连接。 + +选择 MySQL 并点击“下一步”以配置连接。 +如果你还没有安装 MySQL Driver,请先安装。 +接下来输入以下连接信息: + +- Connect by Host +- Host:如果 GreptimeDB 运行在本机,则为 `localhost` +- Port:如果使用默认的 GreptimeDB 配置,则为 `4002` +- Database:`public`,你也可以使用你创建的其他数据库名称 +- 如果你的 GreptimeDB 启用了身份验证,请输入 username 和 password,否则留空 + +点击“Test Connection”以验证连接设置,然后点击“Finish”以保存连接。 + +有关 MySQL 与 GreptimeDB 交互的更多信息,请参阅 [MySQL 协议文档](/user-guide/protocols/mysql.md)。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/emqx.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/emqx.md new file mode 100644 index 0000000000..c25768dbc8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/emqx.md @@ -0,0 +1,4 @@ +# EMQX + +GreptimeDB 可以作为 EMQX 的数据系统。 +更多信息请参考 [通过 EMQX 写入数据](/user-guide/ingest-data/for-iot/emqx.md) 指南。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/fluent-bit.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/fluent-bit.md new file mode 100644 index 0000000000..54674cca10 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/fluent-bit.md @@ -0,0 +1,9 @@ +--- +keywords: [Fluent bit, Prometheus Remote Write, OpenTelemetry, 数据管道] +description: 将 GreptimeDB 与 Fluent Bit 集成。 +--- + +# Fluent Bit + +你可以将 GreptimeDB 设置为 Fluent Bit 的数据接收端。 +更多信息,请参考[通过 Fluent Bit 写入数据](../ingest-data/for-observability/fluent-bit.md)指南。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/grafana.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/grafana.md new file mode 100644 index 0000000000..91f9635942 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/grafana.md @@ -0,0 +1,173 @@ +--- +keywords: [Grafana, 数据源, GreptimeDB 插件, Prometheus 数据源, MySQL 数据源, 仪表盘, 数据可视化] +description: 介绍如何将 GreptimeDB 配置为 Grafana 数据源,包括使用 GreptimeDB 数据源插件、Prometheus 数据源和 MySQL 数据源的方法。 +--- + +# Grafana + +GreptimeDB 服务可以配置为 [Grafana 数据源](https://grafana.com/docs/grafana/latest/datasources/add-a-data-source/)。 +你可以选择使用以下三个数据源之一连接 GreptimeDB 与 Grafana:GreptimeDB、Prometheus 或 MySQL。 + +## GreptimeDB 数据源插件 + +[GreptimeDB 数据源插件(v2.x)](https://github.com/GreptimeTeam/greptimedb-grafana-datasource)基于 ClickHouse 插件开发并附加了特定于 GreptimeDB 的功能。 +该插件完美适配了 GreptimeDB 的数据模型, +从而提供了更好的用户体验。 + + +### 安装 + +GreptimeDB 数据源插件目前仅支持在本地 Grafana 中的安装, +在安装插件前请确保 Grafana 已经安装并运行。 + +你可以任选以下一种安装方式: + +- 下载安装包并解压到相关目录:从[发布页面](https://github.com/GreptimeTeam/greptimedb-grafana-datasource/releases/latest/)获取最新版本,解压文件到你的 [grafana 插件目录](https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#plugins)。 +- 使用 Grafana Cli 下载并安装: + ```shell + grafana cli --pluginUrl https://github.com/GreptimeTeam/greptimedb-grafana-datasource/releases/latest/download/info8fcc-greptimedb-datasource.zip plugins install info8fcc + ``` +- 使用我们 [预构建的 Grafana 镜 + 像](https://hub.docker.com/r/greptime/grafana-greptimedb),已经提前包含了 + GreptimeDB 数据源插件 `docker run -p 3000:3000 + greptime/grafana-greptimedb:latest` + +注意,安装插件后可能需要重新启动 Grafana 服务器。 + + +### Connection 配置 + +在 Grafana 中单击 Add data source 按钮,选择 GreptimeDB 作为类型。 + +![grafana-add-greptimedb-data-source](/grafana-add-greptimedb-data-source.png) + + +在 GreptimeDB server URL 中填写以下地址: + +```txt +http://:4000 +``` + +在 Auth 部分中单击 basic auth,并在 Basic Auth Details 中填写 GreptimeDB 的用户名和密码。未设置可留空: + +- User: `` +- Password: `` + +然后单击 Save & Test 按钮以测试连接。 + + +### 基础查询设置 +在进行所有类型查询选择前,需要先设置要查询的数据库和表 + +| 设置项 | 对应值 | +|-----------|-------------| +| Database| 选择数据库 +| Table | 选择表格 + +![DB Table Config](/grafana/dbtable.png) + +--- + +### Table 查询 +当查询结果不包含`时间列`时可以选择 `Table` 类型进行查询 + +| 设置项 | 对应值 | +|-----------|-------------| +| Columns | 选择要查询的列,可多选 +| Filters | 设置筛选条件 + +![Table Query](/grafana/table.png) + +--- + +### Metrics 查询 +当查询结果包含`时间列`和`数值列`时可以选择 `Time Series` 类型进行查询 + +| 主要设置项 | 对应值 | +|-----------|-------------| +| Time | 选择时间列 +| Columns | 选择数值列 + +![Time Series](/grafana/series1.png) + +--- + +### Logs 查询 +当要查询 Logs 数据时选择 `Logs` 类型进行查询 +* Logs: 对日志数据进行查询。需要设置 `Time` 列和 `Message` 列。 + +| 主要设置项 | 对应值 | +|-----------|--------------------| +| Time | 选择时间列 +| Message | 选择日志内容列 +| Log Level| 日志等级(非必填) + +![Logs](/grafana/logs.png) + +#### logs Context 查询 +根据日志行的 context 列的值进行近似时间范围查询 +* 需要先设置 context 相关的列。 +![Context Config](/grafana/context2.png) +* 然后查询的时候包含 context 相关列。 +![Logs Query Config](/grafana/context1.png) +--- + +### Traces 查询 +当要查询 Traces 数据时选择 `Traces` 类型进行查询 + +| 主要设置项 | 对应值 | +|-----------|---------------------| +| Trace Model | 选择 `Trace Search` 以查询 Trace 列表 +| Trace Id Column | 初始值 `trace_id` +| Span Id Column | 初始值 `span_id` +| Parent Span ID Column | 初始值 `parent_span_id` +| Service Name Column | 初始值 `service_name` +| Operation Name Column | 初始值 `span_name` +| Start Time Column | 初始值 `timestamp` +| Duration Time Column | 初始值 `duration_nano` +| Duration Unit | 初始值 `nano_seconds` +| Tags Column | 可多选,对应以 `span_attributes` 开头的列 +| Service Tags Column| 可多选,对应以 `resource_attributes` 开头的列 + +![Traces](/grafana/traceconfig.png) + +## Prometheus 数据源 + +单击 Add data source 按钮,然后选择 Prometheus 作为类型。 + +在 HTTP 中填写 Prometheus server URL + +```txt +http://:4000/v1/prometheus +``` + +在 Auth 部分中单击 basic auth,并在 Basic Auth Details 中填写 GreptimeDB 的用户名和密码: + +- User: `` +- Password: `` + +在 Custom HTTP Headers 部分中点击 Add header: + +- Header: `x-greptime-db-name` +- Value: `` + +然后单击 Save & Test 按钮以测试连接。 + +有关如何使用 PromQL 查询数据,请参阅 [Prometheus 查询语言](/user-guide/query-data/promql.md)文档。 + +## MySQL 数据源 + +单击 Add data source 按钮,然后选择 MySQL 作为类型。在 MySQL Connection 中填写以下信息: + +- Host: `:4002` +- Database: `` +- User: `` +- Password: `` +- Session timezone: `UTC` + +然后单击 Save & Test 按钮以测试连接。 + +注意目前我们只能使用 raw SQL 创建 Grafana Panel。由于时间戳数据类型的区别,Grafana +的 SQL Builder 暂时无法选择时间戳字段。 + +关于如何用 SQL 查询数据,请参考[使用 SQL 查询数据](/user-guide/query-data/sql.md)文档。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/kafka.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/kafka.md new file mode 100644 index 0000000000..088fc3f8a4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/kafka.md @@ -0,0 +1,9 @@ +--- +keywords: [Kafka, 数据传输, 可观测性, 指标, 日志] +description: 从 Kafka 写入数据到 GreptimeDB。 +--- + +# Kafka + +你可以使用 Vector 作为从 Kafka 到 GreptimeDB 的数据传输工具。 +请前往[通过 Kafka 写入数据](/user-guide/ingest-data/for-observability/kafka.md)了解更多信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/mcp.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/mcp.md new file mode 100644 index 0000000000..a050f587b8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/mcp.md @@ -0,0 +1,69 @@ +--- +keywords: [MCP, Model Context Protocol, AI助手, Claude, 数据库集成] +description: 了解如何将 GreptimeDB 与模型上下文协议(MCP)集成,让 AI 助手能够探索和分析您的时序数据。 +--- + +# Model Context Protocol (MCP) + +:::warning 实验性功能 +GreptimeDB MCP Server 目前处于实验阶段并在积极开发中。API 和功能可能会在没有通知的情况下发生变化。请在生产环境中谨慎使用。 +::: + +[GreptimeDB MCP Server](https://github.com/GreptimeTeam/greptimedb-mcp-server) 提供了模型上下文协议的实现,使 Claude 等 AI 助手能够安全地探索和分析您的 GreptimeDB 数据库。 + +查看我们的[演示视频和文章](https://mp.weixin.qq.com/s/gbTuMLoG4b151Hs8KCSGxg),了解 MCP Server 的实际应用效果,更直观地理解其功能。 + +## 什么是 MCP? + +模型上下文协议(MCP)是一种标准协议,允许 AI 助手与外部数据源和工具进行交互。通过 GreptimeDB MCP Server,您可以让 AI 助手实现: + +- 列出和探索数据库表 +- 读取表数据和模式 +- 执行 SQL 查询 +- 通过自然语言分析时序数据 + +## 安装 + +使用 pip 安装 GreptimeDB MCP Server: + +```bash +pip install greptimedb-mcp-server +``` + +## 配置 + +MCP 服务器可以通过环境变量或命令行参数进行配置。主要配置选项包括: + +- 数据库连接设置(主机、端口、用户名、密码) +- 数据库名称 +- 时区设置 + +### 示例:Claude Desktop 集成 + +要与 Claude Desktop 集成,请在您的 `claude_desktop_config.json` 中添加以下配置: + +```json +{ + "mcpServers": { + "greptimedb": { + "command": "python", + "args": ["-m", "greptimedb_mcp_server"], + "env": { + "GREPTIMEDB_HOST": "localhost", + "GREPTIMEDB_PORT": "4002", + "GREPTIMEDB_USERNAME": "your_username", + "GREPTIMEDB_PASSWORD": "your_password", + "GREPTIMEDB_DATABASE": "your_database" + } + } + } +} +``` + +## 了解更多 + +有关详细的配置选项、高级用法和故障排除,请参阅 [GreptimeDB MCP Server 文档](https://github.com/GreptimeTeam/greptimedb-mcp-server)。 + +:::note +GreptimeDB MCP Server 是一个仍在开发中的实验性项目。在处理敏感数据时请谨慎使用。 +::: \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/metabase.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/metabase.md new file mode 100644 index 0000000000..c6b6284c70 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/metabase.md @@ -0,0 +1,30 @@ +--- +keywords: [Metabase, 数据源, 安装 Driver, 添加数据库, BI 工具, 数据分析] +description: 介绍如何将 GreptimeDB 添加到 Metabase 作为数据源,包括安装 Driver 和添加 GreptimeDB 数据库的方法。 +--- + +# Metabase + +[Metabase](https://github.com/metabase/metabase) 是一个用 Clojure 编写的开源 BI +工具,可以通过社区维护的数据库驱动将 GreptimeDB 添加到 Metabase。 + +## 安装 + +从 [发布 +页](https://github.com/greptimeteam/greptimedb-metabase-driver/releases/latest/) +下载最新的驱动插件文件 `greptimedb.metabase-driver.jar`,并将文件拷贝到 Metabase +的工作目录下 `plugins/` 目录中(如果不存在需要创建 `plugins/`)。当 Metabase 启 +动时,会自动检测到插件。 + +## 添加 GreptimeDB 数据库 + +选择 *设置* / *管理员设置* / *数据库*, 点击 *添加数据库* 按钮并选择 GreptimeDB +作为 *数据库类型*. + +进一步添加其他数据库信息: + +- 端口请填写 GreptimeDB 的 Postgres 协议端口 `4003`。 +- 如果没有开启[认证](/user-guide/deployments-administration/authentication/overview.md),用户名和密码字段 + 是可选的。 +- 默认填写 `public` 作为 *数据库名*。如果是使用 GreptimeCloud 的实例,可以从控制 + 台复制数据库名称。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/mindsdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/mindsdb.md new file mode 100644 index 0000000000..83efb79fb7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/mindsdb.md @@ -0,0 +1,33 @@ +--- +keywords: [MindsDB, 机器学习平台, 数据库集成, 配置示例, SQL] +description: 介绍如何使用 MindsDB 将 GreptimeCloud 实例集成到机器学习平台,并提供了配置示例。 +--- + +# MindsDB + +[MindsDB](https://mindsdb.com/) 是一个开源的机器学习平台,使开发人员能够轻松地将 +先进的机器学习能力与现有数据库集成。 + +使用 MindsDB 扩展,你的 GreptimeDB 实例可以开箱即用。 +你可以使用 MySQL 协议将 GreptimeDB 配置为 MindsDB 中的数据源: + +```sql +CREATE DATABASE greptime_datasource +WITH ENGINE = 'greptimedb', +PARAMETERS = { + "host": "", + "port": 4002, + "database": "", + "user": "", + "password": "", + "ssl": True +}; + +``` + +- `` 是你的 GreptimeDB 实例的主机名或 IP 地址。 +- `` 是你想要连接的数据库名称。 +- `` 和 `` 是你 [GreptimeDB 的鉴权信息](/user-guide/deployments-administration/authentication/static.md)。 + +MindsDB 是许多机器学习功能的优秀门户,包括您存储在我们实例中的时间序列数据的时间序列预测。 +访问 [MindsDB docs](https://docs.mindsdb.com/what-is-mindsdb) 了解更多。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/overview.md new file mode 100644 index 0000000000..7701db3311 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/overview.md @@ -0,0 +1,14 @@ +--- +keywords: [数据写入, 查询, 可视化, 集成] +description: 将 GreptimeDB 与流行的数据写入、查询和可视化工具无缝集成的概述 +--- + +# 工具集成 + +GreptimeDB 可以与流行的数据写入、查询和可视化工具无缝集成。 +本章节提供了将 GreptimeDB 与以下工具集成的指导: + +import DocCardList from '@theme/DocCardList'; + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/prometheus.md new file mode 100644 index 0000000000..9f80172b66 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/prometheus.md @@ -0,0 +1,16 @@ +--- +keywords: [Prometheus, 远程存储, PromQL, 查询数据, 数据写入, 监控工具] +description: 介绍如何将 GreptimeDB 作为 Prometheus 的远程存储后端,并支持使用 Prometheus 查询语言 (PromQL) 查询数据。 +--- + +# Prometheus + +## Remote Write + +GreptimeDB 可以用作 Prometheus 的远程存储后端。 +详细信息请参考[使用 Prometheus Remote Write 写入数据](/user-guide/ingest-data/for-observability/prometheus.md)。 + +## Prometheus Query Language (PromQL) + +GreptimeDB 支持使用 Prometheus 查询语言 (PromQL) 来查询数据。 +更多信息请参考[使用 PromeQL 查询数据](/user-guide/query-data/promql.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/streamlit.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/streamlit.md new file mode 100644 index 0000000000..adec9028e1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/streamlit.md @@ -0,0 +1,29 @@ +--- +keywords: [Streamlit, 数据应用, SQL 连接, MySQL 协议, Python] +description: 使用 GreptimeCloud 和 Streamlit 构建数据应用的说明,包括创建 SQL 连接和运行 SQL 查询。 +--- + +# Streamlit + +[Streamlit](https://streamlit.io/) 是一种更快的构建和分享数据应用的方式。 +可以基于 GreptimeDB 构建基于 Streamlit 的数据应用。 + +你需要创建一个 SQL 连接在应用程序中使用 GreptimeDB 数据。 +由于 GreptimeDB 的 [MySQL 协议兼容性](/user-guide/protocols/mysql.md),你可以在连接时将 GreptimeDB 视为 MySQL。 + +以下是从 Streamlit 连接到 GreptimeDB 的示例代码片段: + +```python +import streamlit as st + +st.title('GreptimeDB Streamlit 演示') +conn = st.connection("greptimedb", type="sql", url="mysql://:@:4002/") + +df = conn.query("SELECT * FROM ...") +``` + +- `` 是 GreptimeDB 实例的主机名或 IP 地址。 +- `` 是要连接的数据库的名称。 +- `` 和 `` 是 [GreptimeDB 鉴权认证信息](/user-guide/deployments-administration/authentication/static.md)。 + +创建连接后,你可以对 GreptimeDB 实例运行 SQL 查询。结果集会自动转换为 Pandas dataframe,就像在 Streamlit 中使用普通数据源一样。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/superset.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/superset.md new file mode 100644 index 0000000000..a9d5a28482 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/superset.md @@ -0,0 +1,56 @@ +--- +keywords: [Superset, 数据源, Docker Compose, 本地运行, 添加数据库, SQLAlchemy URI, BI 工具] +description: 介绍如何将 GreptimeDB 作为 Apache Superset 的数据源,包括使用 Docker Compose 和本地运行 Superset 的安装步骤,以及添加 GreptimeDB 数据库的方法。 +--- + +# Superset + +[Apache Superset](https://superset.apache.org) 是开源的 BI 工具,用 Python 编写。 +以下内容可以帮助你把 GreptimeDB 作为 Superset 的数据源。 + +## 安装 + +### 用 Docker Compose 运行 Superset + +[Docker compose](https://superset.apache.org/docs/installation/docker-compose) +是 Superset 的推荐使用方式。在这种运行方式下,需要在 Superset 代码目录下的 +`docker/` 中添加一个 `requirements-local.txt`。 + +并将 GreptimeDB 依赖加入到 `requirements-local.txt`: + +```txt +greptimedb-sqlalchemy +``` + +启动 Supertset 服务: + +```bash +docker compose -f docker-compose-non-dev.yml up +``` + +### 本地运行 Superset + +假如你通过 [Pypi 包安装和运行 +Superset](https://superset.apache.org/docs/installation/pypi),需要将 GreptimeDB +的依赖安装到相同的 Python 环境。 + +```bash +pip install greptimedb-sqlalchemy +``` + +## 添加 GreptimeDB 数据库 + +准备添加,选择 *设置* / *数据库连接*. + +添加数据库,并在支持的数据库列表中选择 *GreptimeDB*。 + +根据 SQLAlchemy URI 的规范,填写以下格式的数据库连接地址。 + +``` +greptimedb://:@:/ +``` + +- 如果没有启动[认证](/user-guide/deployments-administration/authentication/overview.md),可以忽略 + `:@` 部分。 +- 默认端口 `4003` (我们用 PostgresSQL 协议通信)。 +- 默认数据库 `public`。如果是使用 GreptimeCloud 实例,可以从控制台复制数据库名称。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/telegraf.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/telegraf.md new file mode 100644 index 0000000000..973281e642 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/telegraf.md @@ -0,0 +1,9 @@ +--- +keywords: [Telegraf, Telegraf 写入数据, InfluxDB 行协议] +description: 使用 Telegraf 向 GreptimeDB 写入数据 +--- + +# Telegraf + +请参考 InfluxDB 行协议文档中的 [Telegraf 部分](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md#telegraf) 了解如何使用 Telegraf 向 GreptimeDB 写入数据。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/vector.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/vector.md new file mode 100644 index 0000000000..06fb084ca7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/integrations/vector.md @@ -0,0 +1,8 @@ +--- +keywords: [Vector, Vector sink] +description: 使用 Vector 将数据传输到 GreptimeDB +--- + +# Vector + +请前往[使用 Vector 写入数据](/user-guide/ingest-data/for-observability/vector.md)查看如何使用 Vector 将数据传输到 GreptimeDB。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/fulltext-search.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/fulltext-search.md new file mode 100644 index 0000000000..0ed21f74f7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/fulltext-search.md @@ -0,0 +1,153 @@ +--- +keywords: [日志查询, GreptimeDB 查询语言, matches_term, 模式匹配, 查询语句示例] +description: 详细介绍如何利用 GreptimeDB 的查询语言对日志数据进行高效搜索和分析,包括使用 matches_term 函数进行精确匹配。 +--- + +# 全文搜索 + +本文档详细介绍如何利用 GreptimeDB 的查询语言对日志数据进行高效搜索和分析。 + +GreptimeDB 支持通过 SQL 语句灵活查询数据。本节将介绍特定的搜索功能和查询语句,帮助你提升日志查询效率。 + +## 使用 `matches_term` 函数进行精确匹配 + +在 SQL 查询中,你可以使用 `matches_term` 函数执行精确的词语/短语匹配,这在日志分析中尤其实用。`matches_term` 函数支持对 `String` 类型列进行精确匹配。你也可以使用 `@@` 操作符作为 `matches_term` 的简写形式。下面是一个典型示例: + +```sql +-- 使用 matches_term 函数 +SELECT * FROM logs WHERE matches_term(message, 'error') OR matches_term(message, 'fail'); + +-- 使用 @@ 操作符(matches_term 的简写形式) +SELECT * FROM logs WHERE message @@ 'error' OR message @@ 'fail'; +``` + +`matches_term` 函数专门用于精确匹配,使用方式如下: + +- `text`:需要进行匹配的文本列,该列应包含 `String` 类型的文本数据。 +- `term`:要匹配的词语或短语,遵循以下规则: + - 区分大小写 + - 匹配项必须由非字母数字字符(包括空格、标点符号等)或文本开头/结尾界定 + - 支持完整词语匹配和短语匹配 + +## 查询语句示例 + +### 简单词语匹配 + +`matches_term` 函数执行精确词语匹配,这意味着它只会匹配由非字母数字字符或文本开头/结尾界定的完整词语。这对于在日志中查找特定的错误消息或状态码特别有用。 + +```sql +-- 使用 matches_term 函数 +SELECT * FROM logs WHERE matches_term(message, 'error'); + +-- 使用 @@ 操作符 +SELECT * FROM logs WHERE message @@ 'error'; +``` + +此查询将返回所有 `message` 列中包含完整词语 "error" 的记录。该函数确保你不会得到部分匹配或词语内的匹配。 + +匹配和不匹配的示例: +- ✅ "An error occurred!" - 匹配,因为 "error" 是一个完整词语 +- ✅ "Critical error: system failure" - 匹配,因为 "error" 由空格和冒号界定 +- ✅ "error-prone" - 匹配,因为 "error" 由连字符界定 +- ❌ "errors" - 不匹配,因为 "error" 是更大词语的一部分 +- ❌ "error123" - 不匹配,因为 "error" 后面跟着数字 +- ❌ "errorLogs" - 不匹配,因为 "error" 是驼峰命名词语的一部分 + +### 多关键词搜索 + +你可以使用 `OR` 运算符组合多个 `matches_term` 条件来搜索包含多个关键词中任意一个的日志。当你想要查找可能包含不同错误变体或不同类型问题的日志时,这很有用。 + +```sql +-- 使用 matches_term 函数 +SELECT * FROM logs WHERE matches_term(message, 'critical') OR matches_term(message, 'error'); + +-- 使用 @@ 操作符 +SELECT * FROM logs WHERE message @@ 'critical' OR message @@ 'error'; +``` + +此查询将查找包含完整词语 "critical" 或 "error" 的日志。每个词语都是独立匹配的,结果包括匹配任一条件的日志。 + +匹配和不匹配的示例: +- ✅ "critical error: system failure" - 匹配两个词语 +- ✅ "An error occurred!" - 匹配 "error" +- ✅ "critical failure detected" - 匹配 "critical" +- ❌ "errors" - 不匹配,因为 "error" 是更大词语的一部分 +- ❌ "critical_errors" - 不匹配,因为词语是更大词语的一部分 + +### 排除条件搜索 + +你可以使用 `NOT` 运算符与 `matches_term` 结合来从搜索结果中排除某些词语。当你想要查找包含一个词语但不包含另一个词语的日志时,这很有用。 + +```sql +-- 使用 matches_term 函数 +SELECT * FROM logs WHERE matches_term(message, 'error') AND NOT matches_term(message, 'critical'); + +-- 使用 @@ 操作符 +SELECT * FROM logs WHERE message @@ 'error' AND NOT message @@ 'critical'; +``` + +此查询将查找包含词语 "error" 但不包含词语 "critical" 的日志。这对于过滤掉某些类型的错误或专注于特定的错误类别特别有用。 + +匹配和不匹配的示例: +- ✅ "An error occurred!" - 匹配,因为它包含 "error" 但不包含 "critical" +- ❌ "critical error: system failure" - 不匹配,因为它包含两个词语 +- ❌ "critical failure detected" - 不匹配,因为它包含 "critical" + +### 多条件必要搜索 + +你可以使用 `AND` 运算符要求日志消息中必须存在多个词语。这对于查找包含特定词语组合的日志很有用。 + +```sql +-- 使用 matches_term 函数 +SELECT * FROM logs WHERE matches_term(message, 'critical') AND matches_term(message, 'error'); + +-- 使用 @@ 操作符 +SELECT * FROM logs WHERE message @@ 'critical' AND message @@ 'error'; +``` + +此查询将查找同时包含完整词语 "critical" 和 "error" 的日志。两个条件都必须满足,日志才会包含在结果中。 + +匹配和不匹配的示例: +- ✅ "critical error: system failure" - 匹配,因为它包含两个词语 +- ❌ "An error occurred!" - 不匹配,因为它只包含 "error" +- ❌ "critical failure detected" - 不匹配,因为它只包含 "critical" + +### 短语匹配 + +`matches_term` 函数也可以匹配精确的短语,包括带空格的短语。这对于查找包含多个词语的特定错误消息或状态更新很有用。 + +```sql +-- 使用 matches_term 函数 +SELECT * FROM logs WHERE matches_term(message, 'system failure'); + +-- 使用 @@ 操作符 +SELECT * FROM logs WHERE message @@ 'system failure'; +``` + +此查询将查找包含精确短语 "system failure" 的日志。整个短语必须完全匹配,包括词语之间的空格。 + +匹配和不匹配的示例: +- ✅ "Alert: system failure detected" - 匹配,因为短语被正确界定 +- ✅ "system failure!" - 匹配,因为短语被正确界定 +- ❌ "system-failure" - 不匹配,因为词语由连字符而不是空格分隔 +- ❌ "system failure2023" - 不匹配,因为短语后面跟着数字 + +### 不区分大小写匹配 + +虽然 `matches_term` 默认区分大小写,但你可以通过在匹配前将文本转换为小写来实现不区分大小写的匹配。 + +```sql +-- 使用 matches_term 函数 +SELECT * FROM logs WHERE matches_term(lower(message), 'warning'); + +-- 使用 @@ 操作符 +SELECT * FROM logs WHERE lower(message) @@ 'warning'; +``` + +此查询将查找包含词语 "warning" 的日志,无论其大小写如何。`lower()` 函数在匹配前将整个消息转换为小写。 + +匹配和不匹配的示例: +- ✅ "Warning: high temperature" - 匹配,因为大小写转换后匹配 +- ✅ "WARNING: system overload" - 匹配,因为大小写转换后匹配 +- ❌ "warned" - 不匹配,因为它是不同的词语 +- ❌ "warnings" - 不匹配,因为它是不同的词语 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/manage-pipelines.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/manage-pipelines.md new file mode 100644 index 0000000000..db41a932c0 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/manage-pipelines.md @@ -0,0 +1,453 @@ +--- +keywords: [管理 Pipeline, 创建 Pipeline, 删除 Pipeline, 查询 Pipeline, 内置 Pipeline, 数据处理, 日志解析, 日志转换] +description: 介绍如何在 GreptimeDB 中管理 Pipeline,包括创建、删除和查询 Pipeline 的方法,以及内置 Pipeline 的使用。 +--- + +# 管理 Pipeline + +在 GreptimeDB 中,每个 `pipeline` 是一个数据处理单元集合,用于解析和转换写入的日志内容。本文档旨在指导你如何创建和删除 Pipeline,以便高效地管理日志数据的处理流程。 + + +有关 Pipeline 的具体配置,请阅读 [Pipeline 配置](/reference/pipeline/pipeline-config.md)。 + +## 鉴权 + +在使用 HTTP API 进行 Pipeline 管理时,你需要提供有效的鉴权信息。 +请参考[鉴权](/user-guide/protocols/http.md#鉴权)文档了解详细信息。 + +## 上传 Pipeline + +GreptimeDB 提供了专用的 HTTP 接口用于创建 Pipeline。 +假设你已经准备好了一个 Pipeline 配置文件 pipeline.yaml,使用以下命令上传配置文件,其中 `test` 是你指定的 Pipeline 的名称: + +```shell +## 上传 pipeline 文件。test 为 Pipeline 的名称 +curl -X "POST" "http://localhost:4000/v1/pipelines/test" \ + -H "Authorization: Basic {{authentication}}" \ + -F "file=@pipeline.yaml" +``` + +你可以在所有 Database 中使用创建的 Pipeline。 + +## Pipeline 版本 + +你可以使用相同的名称上传多个版本的 pipeline。 +每次你使用现有名称上传 pipeline 时,都会自动创建一个新版本。 +你可以在[写入日志](/reference/pipeline/write-log-api.md#http-api)、[查询](#查询-pipeline)或[删除](#删除-pipeline) pipeline 时指定要使用的版本。 +如果未指定版本,默认使用最后上传的版本。 + +成功上传 pipeline 后,响应将包含版本信息: + +```json +{"name":"nginx_pipeline","version":"2024-06-27 12:02:34.257312110Z"} +``` + +版本是 UTC 格式的时间戳,表示 pipeline 的创建时间。 +此时间戳作为每个 pipeline 版本的唯一标识符。 + +## 删除 Pipeline + +可以使用以下 HTTP 接口删除 Pipeline: + +```shell +## test 为 Pipeline 的名称 +curl -X "DELETE" "http://localhost:4000/v1/pipelines/test?version=2024-06-27%2012%3A02%3A34.257312110Z" \ + -H "Authorization: Basic {{authentication}}" +``` + +上面的例子中,我们删除了名为 `test` 的 Pipeline。`version` 参数是必须的,用于指定要删除的 Pipeline 的版本号。 + +## 查询 Pipeline + +可以使用以下 HTTP 接口查询 Pipeline: + +```shell +## test 是 Pipeline 的名称,该查询将返回最新版本的 Pipeline。 +curl "http://localhost:4000/v1/pipelines/test" \ + -H "Authorization: Basic {{authentication}}" +``` + +```shell +## 如果你想查询某个 Pipeline 的历史版本,可以在 URL 中添加 `version` 参数 +curl "http://localhost:4000/v1/pipelines/test?version=2025-04-01%2006%3A58%3A31.335251882%2B0000" \ + -H "Authorization: Basic {{authentication}}" +``` + + 如果这个 pipeline 存在,输出会如下所示: + +```json +{ + "pipelines": [ + { + "name": "test", + "version": "2025-04-01 06:58:31.335251882", + "pipeline": "version: 2\nprocessors:\n - dissect:\n fields:\n - message\n patterns:\n - '%{ip_address} - - [%{timestamp}] \"%{http_method} %{request_line}\" %{status_code} %{response_size} \"-\" \"%{user_agent}\"'\n ignore_missing: true\n - date:\n fields:\n - timestamp\n formats:\n - \"%d/%b/%Y:%H:%M:%S %z\"\n - select:\n type: exclude\n fields:\n - message\n\ntransform:\n - fields:\n - ip_address\n type: string\n index: inverted\n tag: true\n - fields:\n - status_code\n type: int32\n index: inverted\n tag: true\n - fields:\n - request_line\n - user_agent\n type: string\n index: fulltext\n - fields:\n - response_size\n type: int32\n - fields:\n - timestamp\n type: time\n index: timestamp\n" + } + ], + "execution_time_ms": 7 +} +``` + +在上面的输出中,pipeline 字段是 YAML 格式的字符串。 +JSON 格式无法很好地展示 YMAL 字符串,使用 echo 命令可以将其以阅读友好的方式展示出来: + +```shell +echo -e "version: 2\nprocessors:\n - dissect:\n fields:\n - message\n patterns:\n - '%{ip_address} - - [%{timestamp}] \"%{http_method} %{request_line}\" %{status_code} %{response_size} \"-\" \"%{user_agent}\"'\n ignore_missing: true\n - date:\n fields:\n - timestamp\n formats:\n - \"%d/%b/%Y:%H:%M:%S %z\"\n - select:\n type: exclude\n fields:\n - message\n\ntransform:\n - fields:\n - ip_address\n type: string\n index: inverted\n tag: true\n - fields:\n - status_code\n type: int32\n index: inverted\n tag: true\n - fields:\n - request_line\n - user_agent\n type: string\n index: fulltext\n - fields:\n - response_size\n type: int32\n - fields:\n - timestamp\n type: time\n index: timestamp\n" +``` + +```yml +version: 2 +processors: + - dissect: + fields: + - message + patterns: + - '%{ip_address} - - [%{timestamp}] "%{http_method} %{request_line}" %{status_code} %{response_size} "-" "%{user_agent}"' + ignore_missing: true + - date: + fields: + - timestamp + formats: + - "%d/%b/%Y:%H:%M:%S %z" + - select: + type: exclude + fields: + - message + +transform: + - fields: + - ip_address + type: string + index: inverted + tag: true + - fields: + - status_code + type: int32 + index: inverted + tag: true + - fields: + - request_line + - user_agent + type: string + index: fulltext + - fields: + - response_size + type: int32 + - fields: + - timestamp + type: time + index: timestamp +``` + +或者使用 SQL 来查询 Pipeline: + +```sql +SELECT * FROM greptime_private.pipelines; +``` + +请注意,如果你使用 MySQL 或者 PostgreSQL 协议作为连接 GreptimeDB 的方式,查询出来的 Pipeline 时间信息精度可能有所不同,可能会丢失纳秒级别的精度。 + +为了解决这个问题,可以将 `created_at` 字段强制转换为 timestamp 来查看 Pipeline 的创建时间。例如,下面的查询将 `created_at` 以 `bigint` 的格式展示: + +```sql +SELECT name, pipeline, created_at::bigint FROM greptime_private.pipelines; +``` + +查询结果如下: + +``` + name | pipeline | greptime_private.pipelines.created_at +------+-----------------------------------+--------------------------------------- + test | processors: +| 1719489754257312110 + | - date: +| + | field: time +| + | formats: +| + | - "%Y-%m-%d %H:%M:%S%.3f"+| + | ignore_missing: true +| + | +| + | transform: +| + | - fields: +| + | - id1 +| + | - id2 +| + | type: int32 +| + | - fields: +| + | - type +| + | - logger +| + | type: string +| + | index: inverted +| + | - fields: +| + | - log +| + | type: string +| + | index: fulltext +| + | - field: time +| + | type: time +| + | index: timestamp +| + | | +(1 row) +``` + +然后可以使用程序将 SQL 结果中的 bigint 类型的时间戳转换为时间字符串。 + +```shell +timestamp_ns="1719489754257312110"; readable_timestamp=$(TZ=UTC date -d @$((${timestamp_ns:0:10}+0)) +"%Y-%m-%d %H:%M:%S").${timestamp_ns:10}Z; echo "Readable timestamp (UTC): $readable_timestamp" +``` + +输出: + +```shell +Readable timestamp (UTC): 2024-06-27 12:02:34.257312110Z +``` + +输出的 `Readable timestamp (UTC)` 即为 Pipeline 的创建时间同时也是版本号。 + +## 问题调试 + +首先,请参考 [快速入门示例](/user-guide/logs/quick-start.md#使用-pipeline-写入日志)来查看 Pipeline 正确的执行情况。 + +### 调试创建 Pipeline + +在创建 Pipeline 的时候你可能会遇到错误,例如使用如下配置创建 Pipeline: + +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/test" \ + -H "Content-Type: application/x-yaml" \ + -H "Authorization: Basic {{authentication}}" \ + -d $'processors: + - date: + field: time + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + ignore_missing: true + - gsub: + fields: + - message + pattern: "\\\." + replacement: + - "-" + ignore_missing: true + +transform: + - fields: + - message + type: string + - field: time + type: time + index: timestamp +``` + +Pipeline 配置存在错误。`gsub` processor 期望 `replacement` 字段为字符串,但当前配置提供了一个数组。因此,该 Pipeline 创建失败,并显示以下错误消息: + + +```json +{"error":"Failed to parse pipeline: 'replacement' must be a string"} +``` + +因此,你需要修改 `gsub` processor 的配置,将 `replacement` 字段的值更改为字符串类型。 + +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/test" \ + -H "Content-Type: application/x-yaml" \ + -H "Authorization: Basic {{authentication}}" \ + -d $'processors: + - date: + field: time + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + ignore_missing: true + - gsub: + fields: + - message + pattern: "\\\." + replacement: "-" + ignore_missing: true + +transform: + - fields: + - message + type: string + - field: time + type: time + index: timestamp +``` + +此时 Pipeline 创建成功,可以使用 `dryrun` 接口测试该 Pipeline。 + +### 调试日志写入 + +我们可以使用 `dryrun` 接口测试 Pipeline。我们将使用错误的日志数据对其进行测试,其中消息字段的值为数字格式,会导致 Pipeline 在处理过程中失败。 + +**此接口仅仅用于测试 Pipeline 的处理结果,不会将日志写入到 GreptimeDB 中。** + +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/dryrun?pipeline_name=test" \ + -H "Content-Type: application/json" \ + -H "Authorization: Basic {{authentication}}" \ + -d $'{"message": 1998.08,"time":"2024-05-25 20:16:37.217"}' + +{"error":"Failed to execute pipeline, reason: gsub processor: expect string or array string, but got Float64(1998.08)"} +``` + +输出显示 Pipeline 处理失败,因为 `gsub` Processor 期望的是字符串类型,而不是浮点数类型。我们需要修改日志数据的格式,确保 Pipeline 能够正确处理。 +我们再将 message 字段的值修改为字符串类型,然后再次测试该 Pipeline。 + +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/dryrun?pipeline_name=test" \ + -H "Content-Type: application/json" \ + -H "Authorization: Basic {{authentication}}" \ + -d $'{"message": "1998.08","time":"2024-05-25 20:16:37.217"}' +``` + +此时 Pipeline 处理成功,输出如下: + +```json +{ + "rows": [ + [ + { + "data_type": "STRING", + "key": "message", + "semantic_type": "FIELD", + "value": "1998-08" + }, + { + "data_type": "TIMESTAMP_NANOSECOND", + "key": "time", + "semantic_type": "TIMESTAMP", + "value": "2024-05-25 20:16:37.217+0000" + } + ] + ], + "schema": [ + { + "column_type": "FIELD", + "data_type": "STRING", + "fulltext": false, + "name": "message" + }, + { + "column_type": "TIMESTAMP", + "data_type": "TIMESTAMP_NANOSECOND", + "fulltext": false, + "name": "time" + } + ] +} +``` + +可以看到,`1998.08` 字符串中的 `.` 已经被替换为 `-`,Pipeline 处理成功。 + +## 从 Pipeline 配置生成表的建表语句 + +使用 Pipeline 时,GreptimeDB 默认会在首次数据写入时自动创建目标表。 +但是,你可能希望预先手动创建表以添加自定义表选项,例如添加分区规则以获得更好的性能。 + +虽然自动创建的表结构对于给定的 Pipeline 配置是确定的, +但根据配置手动编写表的建表语句可能会很繁琐。`/ddl` API 简化了这一过程。 + +对于现有的 Pipeline,你可以使用 `/v1/pipelines/{pipeline_name}/ddl` 来生成建表语句。 +此 API 会检查 Pipeline 配置中的 transform 定义并推断出相应的表结构。 +你可以在第一次写入数据之前使用此 API 来生成基础的建表语句,进行参数调整并手动建表。 +常见的调整选项包括: +- 增加[数据分区规则](/user-guide/deployments-administration/manage-data/table-sharding.md) +- 调整[索引的参数](/user-guide/manage-data/data-index.md) +- 增加其他[表选项](/reference/sql/create.md#表选项) + +以下是演示如何使用此 API 的示例。考虑以下 Pipeline 配置: +```YAML +# pipeline.yaml +processors: +- dissect: + fields: + - message + patterns: + - '%{ip_address} - %{username} [%{timestamp}] "%{http_method} %{request_line} %{protocol}" %{status_code} %{response_size}' + ignore_missing: true +- date: + fields: + - timestamp + formats: + - "%d/%b/%Y:%H:%M:%S %z" + +transform: + - fields: + - timestamp + type: time + index: timestamp + - fields: + - ip_address + type: string + index: skipping + - fields: + - username + type: string + tag: true + - fields: + - http_method + type: string + index: inverted + - fields: + - request_line + type: string + index: fulltext + - fields: + - protocol + type: string + - fields: + - status_code + type: int32 + index: inverted + tag: true + - fields: + - response_size + type: int64 + on_failure: default + default: 0 + - fields: + - message + type: string +``` + +首先,使用以下命令将 Pipeline 上传到数据库: +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/pp" -F "file=@pipeline.yaml" +``` +然后,使用以下命令查询表的建表语句: +```bash +curl -X "GET" "http://localhost:4000/v1/pipelines/pp/ddl?table=test_table" +``` +API 返回以下 JSON 格式的输出: +```JSON +{ + "sql": { + "sql": "CREATE TABLE IF NOT EXISTS `test_table` (\n `timestamp` TIMESTAMP(9) NOT NULL,\n `ip_address` STRING NULL SKIPPING INDEX WITH(false_positive_rate = '0.01', granularity = '10240', type = 'BLOOM'),\n `username` STRING NULL,\n `http_method` STRING NULL INVERTED INDEX,\n `request_line` STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'bloom', case_sensitive = 'false', false_positive_rate = '0.01', granularity = '10240'),\n `protocol` STRING NULL,\n `status_code` INT NULL INVERTED INDEX,\n `response_size` BIGINT NULL,\n `message` STRING NULL,\n TIME INDEX (`timestamp`),\n PRIMARY KEY (`username`, `status_code`)\n)\nENGINE=mito\nWITH(\n append_mode = 'true'\n)" + }, + "execution_time_ms": 3 +} +``` +格式化响应中的 `sql` 字段后,你可以看到推断出的表结构: +```SQL +CREATE TABLE IF NOT EXISTS `test_table` ( + `timestamp` TIMESTAMP(9) NOT NULL, + `ip_address` STRING NULL SKIPPING INDEX WITH(false_positive_rate = '0.01', granularity = '10240', type = 'BLOOM'), + `username` STRING NULL, + `http_method` STRING NULL INVERTED INDEX, + `request_line` STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'bloom', case_sensitive = 'false', false_positive_rate = '0.01', granularity = '10240'), + `protocol` STRING NULL, + `status_code` INT NULL INVERTED INDEX, + `response_size` BIGINT NULL, + `message` STRING NULL, + TIME INDEX (`timestamp`), + PRIMARY KEY (`username`, `status_code`) + ) +ENGINE=mito +WITH( + append_mode = 'true' +) +``` + +你可以将推断出的表的建表语句作为起点。 +根据你的需求自定义建表语句后,在通过 Pipeline 写入数据之前手动执行它。 + +**注意事项:** +1. 该 API 仅从 Pipeline 配置推断表结构;它不会检查表是否已存在。 +2. 该 API 不考虑表后缀。如果你在 Pipeline 配置中使用 `dispatcher`、`table_suffix` 或表后缀 hint,你需要手动调整表名。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/overview.md new file mode 100644 index 0000000000..e59f8d3a59 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/overview.md @@ -0,0 +1,105 @@ +--- +keywords: [log service, quick start, pipeline configuration, manage pipelines, query logs] +description: GreptimeDB 日志管理功能的综合指南,包括日志收集架构、Pipeline 处理、与 Vector 和 Kafka 等流行的日志收集器的集成以及使用全文搜索的高级查询。 +--- + +# 日志 + +GreptimeDB 提供了专为满足现代可观测需求而设计的日志管理解决方案, +它可以和主流日志收集器无缝集成, +提供了灵活的使用 pipeline 转换日志的功能 +和包括全文搜索的查询功能。 + +核心功能点包括: + +- **统一存储**:将日志与指标和 Trace 数据一起存储在单个数据库中 +- **Pipeline 处理数据**:使用可自定义的 pipeline 转换和丰富原始日志,支持多种日志收集器和格式 +- **高级查询**:基于 SQL 的分析,并具有全文搜索功能 +- **实时数据处理**:实时处理和查询日志以进行监控和警报 + +## 日志收集流程 + +![log-collection-flow](/log-collection-flow.drawio.svg) + +上图展示了日志收集的整体架构, +它包括四阶段流程:日志源、日志收集器、Pipeline 处理和在存储到 GreptimeDB 中。 + +### 日志源 + +日志源是基础设施中产生日志数据的基础层。 +GreptimeDB 支持从各种源写入数据以满足全面的可观测性需求: + +- **应用程序**:来自微服务架构、Web 应用程序、移动应用程序和自定义软件组件的应用程序级日志 +- **IoT 设备**:来自物联网生态系统的设备日志、传感器事件日志和运行状态日志 +- **基础设施**:云平台日志、容器编排日志(Kubernetes、Docker)、负载均衡器日志以及网络基础设施组件日志 +- **系统组件**:操作系统日志、内核事件、系统守护进程日志以及硬件监控日志 +- **自定义源**:特定于你环境或应用程序的任何其他日志源 + +### 日志收集器 + +日志收集器负责高效地从各种源收集日志数据并转发到存储后端。 +GreptimeDB 可以与行业标准的日志收集器无缝集成, +包括 Vector、Fluent Bit、Apache Kafka、OpenTelemetry Collector 等。 + +GreptimeDB 作为这些收集器的 sink 后端, +提供强大的数据写入能力。 +在写入过程中,GreptimeDB 的 pipeline 系统能够实时转换和丰富日志数据, +确保在存储前获得最佳的结构和质量。 + +### Pipeline 处理 + +GreptimeDB 的 pipeline 机制将原始日志转换为结构化、可查询的数据: + +- **解析**:从非结构化日志消息中提取结构化数据 +- **转换**:使用额外的上下文和元数据丰富日志 +- **索引**:配置必要的索引以提升查询性能,例如全文索引、时间索引等 + +### 存储日志到 GreptimeDB + +通过 pipeline 处理后,日志存储在 GreptimeDB 中,支持灵活的分析和可视化: + +- **SQL 查询**:使用熟悉的 SQL 语法分析日志数据 +- **基于时间的分析**:利用时间序列功能进行时间分析 +- **全文搜索**:在日志消息中执行高级文本搜索 +- **实时分析**:实时查询日志进行监控和告警 + +## 快速开始 + +你可以使用内置的 `greptime_identity` pipeline 快速开始日志写入。更多信息请参考[快速开始](./quick-start.md)指南。 + +## 集成到日志收集器 + +GreptimeDB 与各种日志收集器无缝集成,提供全面的日志记录解决方案。集成过程包括以下关键步骤: + +1. **选择合适的日志收集器**:根据你的基础设施要求、数据源和性能需求选择收集器 +2. **分析输出格式**:了解你选择的收集器产生的日志格式和结构 +3. **配置 Pipeline**:在 GreptimeDB 中创建和配置 pipeline 来解析、转换和丰富传入的日志数据 +4. **存储和查询**:在 GreptimeDB 中高效存储处理后的日志,用于实时分析和监控 + +要成功将你的日志收集器与 GreptimeDB 集成,你需要: +- 首先了解 pipeline 在 GreptimeDB 中的工作方式 +- 然后在你的日志收集器中配置 sink 设置,将数据发送到 GreptimeDB + +请参考以下指南获取将 GreptimeDB 集成到日志收集器的详细说明: + +- [Vector](/user-guide/ingest-data/for-observability/vector.md#using-greptimedb_logs-sink-recommended) +- [Kafka](/user-guide/ingest-data/for-observability/kafka.md#logs) +- [Fluent Bit](/user-guide/ingest-data/for-observability/fluent-bit.md#http) +- [OpenTelemetry Collector](/user-guide/ingest-data/for-observability/otel-collector.md) +- [Loki](/user-guide/ingest-data/for-observability/loki.md#using-pipeline-with-loki-push-api) + +## 了解更多关于 Pipeline 的信息 + +- [使用自定义 Pipeline](./use-custom-pipelines.md):解释如何创建和使用自定义 pipeline 进行日志写入。 +- [管理 Pipeline](./manage-pipelines.md):解释如何创建和删除 pipeline。 + +## 查询日志 + +- [全文搜索](./fulltext-search.md):使用 GreptimeDB 查询语言有效搜索和分析日志数据的指南。 + +## 参考 + +- [内置 Pipeline](/reference/pipeline/built-in-pipelines.md):GreptimeDB 为日志写入提供的内置 pipeline 详细信息。 +- [写入日志的 API](/reference/pipeline/write-log-api.md):描述向 GreptimeDB 写入日志的 HTTP API。 +- [Pipeline 配置](/reference/pipeline/pipeline-config.md):提供 GreptimeDB 中 pipeline 各项具体配置的信息。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/quick-start.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/quick-start.md new file mode 100644 index 0000000000..c365e6d1dd --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/quick-start.md @@ -0,0 +1,122 @@ +--- +keywords: [logs, log service, pipeline, greptime_identity, quick start, JSON logs] +description: GreptimeDB 日志服务快速入门指南,包括使用内置 greptime_identity pipeline 的基本日志写入和与日志收集器的集成。 +--- + +# 快速入门 + +本指南将引导你完成使用 GreptimeDB 日志服务的基本步骤。 +你将学习如何使用内置的 `greptime_identity` pipeline 写入日志并集成日志收集器。 + +GreptimeDB 提供了强大的基于 pipeline 的日志写入系统。 +你可以使用内置的 `greptime_identity` pipeline 快速写入 JSON 格式的日志, +该 pipeline 具有以下特点: + +- 自动处理从 JSON 到表列的字段映射 +- 如果表不存在则自动创建表 +- 灵活支持变化的日志结构 +- 需要最少的配置即可开始使用 + +## 直接通过 HTTP 写入日志 + +GreptimeDB 日志写入最简单的方法是通过使用 `greptime_identity` pipeline 发送 HTTP 请求。 + +例如,你可以使用 `curl` 发送带有 JSON 日志数据的 POST 请求: + +```shell +curl -X POST \ + "http://localhost:4000/v1/ingest?db=public&table=demo_logs&pipeline_name=greptime_identity" \ + -H "Content-Type: application/json" \ + -H "Authorization: Basic {{authentication}}" \ + -d '[ + { + "timestamp": "2024-01-15T10:30:00Z", + "level": "INFO", + "service": "web-server", + "message": "用户登录成功", + "user_id": 12345, + "ip_address": "192.168.1.100" + }, + { + "timestamp": "2024-01-15T10:31:00Z", + "level": "ERROR", + "service": "database", + "message": "连接超时", + "error_code": 500, + "retry_count": 3 + } + ]' +``` + +关键参数包括: + +- `db=public`:目标数据库名称(你的数据库名称) +- `table=demo_logs`:目标表名称(如果不存在则自动创建) +- `pipeline_name=greptime_identity`:使用 `greptime_identity` pipeline 进行 JSON 处理 +- `Authorization` 头:使用 base64 编码的 `username:password` 进行基本身份验证,请参阅 [HTTP 鉴权指南](/user-guide/protocols/http.md#authentication) + +成功的请求返回: + +```json +{ + "output": [{"affectedrows": 2}], + "execution_time_ms": 15 +} +``` + +成功写入日志后, +相应的表 `demo_logs` 会根据 JSON 字段自动创建相应的列,其 schema 如下: + +```sql ++--------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+---------------------+------+------+---------+---------------+ +| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| ip_address | String | | YES | | FIELD | +| level | String | | YES | | FIELD | +| message | String | | YES | | FIELD | +| service | String | | YES | | FIELD | +| timestamp | String | | YES | | FIELD | +| user_id | Int64 | | YES | | FIELD | +| error_code | Int64 | | YES | | FIELD | +| retry_count | Int64 | | YES | | FIELD | ++--------------------+---------------------+------+------+---------+---------------+ +``` + +## 与日志收集器集成 + +对于生产环境, +你通常会使用日志收集器自动将日志转发到 GreptimeDB。 +以下是如何配置 Vector 使用 `greptime_identity` pipeline 向 GreptimeDB 发送日志的示例: + +```toml +[sinks.my_sink_id] +type = "greptimedb_logs" +dbname = "public" +endpoint = "http://:4000" +pipeline_name = "greptime_identity" +table = "
" +username = "" +password = "" +# 根据需要添加其他配置 +``` + +关键配置参数包括: +- `type = "greptimedb_logs"`:指定 GreptimeDB 日志接收器 +- `dbname`:目标数据库名称 +- `endpoint`:GreptimeDB HTTP 端点 +- `pipeline_name`:使用 `greptime_identity` pipeline 进行 JSON 处理 +- `table`:目标表名称(如果不存在则自动创建) +- `username` 和 `password`:HTTP 基本身份验证的凭证 + +有关 Vector 配置和选项的详细信息, +请参阅 [Vector 集成指南](/user-guide/ingest-data/for-observability/vector.md#使用-greptimedb_logs-sink-推荐)。 + +## 下一步 + +你已成功写入了第一批日志,以下是推荐的后续步骤: + +- **了解更多关于内置 Pipeline 的行为**:请参阅[内置 Pipeline](/reference/pipeline/built-in-pipelines.md)指南,了解可用的内置 pipeline 及其配置的详细信息 +- **与流行的日志收集器集成**:有关将 GreptimeDB 与 Fluent Bit、Fluentd 等各种日志收集器集成的详细说明,请参阅[日志概览](./overview.md)中的[集成到日志收集器](./overview.md#集成到日志收集器)部分 +- **使用自定义 Pipeline**:要了解使用自定义 pipeline 进行高级日志处理和转换的信息,请参阅[使用自定义 Pipeline](./use-custom-pipelines.md)指南 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/use-custom-pipelines.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/use-custom-pipelines.md new file mode 100644 index 0000000000..cea036a4d6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/logs/use-custom-pipelines.md @@ -0,0 +1,318 @@ +--- +keywords: [快速开始, 写入日志, 查询日志, pipeline, 结构化数据, 日志写入, 日志收集, 日志管理工具] +description: 在 GreptimeDB 中快速写入和查询日志的全面指南,包括直接日志写入和使用 pipeline 处理结构化数据。 +--- + +# 使用自定义 Pipeline + +基于你的 pipeline 配置, +GreptimeDB 能够将日志自动解析和转换为多列的结构化数据, +当内置 pipeline 无法处理特定的文本日志格式时, +你可以创建自定义 pipeline 来定义如何根据你的需求解析和转换日志数据。 + +## 识别你的原始日志格式 + +在创建自定义 pipeline 之前,了解原始日志数据的格式至关重要。 +如果你正在使用日志收集器且不确定日志格式, +有两种方法可以检查你的日志: + +1. **阅读收集器的官方文档**:配置你的收集器将数据输出到控制台或文件以检查日志格式。 +2. **使用 `greptime_identity` pipeline**:使用内置的 `greptime_identity` pipeline 将示例日志直接写入到 GreptimeDB 中。 + `greptime_identity` pipeline 将整个文本日志视为单个 `message` 字段,方便你直接看到原始日志的内容。 + +一旦了解了要处理的日志格式, +你就可以创建自定义 pipeline。 +本文档使用以下 Nginx 访问日志条目作为示例: + +```txt +127.0.0.1 - - [25/May/2024:20:16:37 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" +``` + +## 创建自定义 Pipeline + +GreptimeDB 提供 HTTP 接口用于创建 pipeline。 +以下是创建方法。 + +首先,创建一个示例 pipeline 配置文件来处理 Nginx 访问日志, +将其命名为 `pipeline.yaml`: + +```yaml +version: 2 +processors: + - dissect: + fields: + - message + patterns: + - '%{ip_address} - - [%{timestamp}] "%{http_method} %{request_line}" %{status_code} %{response_size} "-" "%{user_agent}"' + ignore_missing: true + - date: + fields: + - timestamp + formats: + - "%d/%b/%Y:%H:%M:%S %z" + - select: + type: exclude + fields: + - message + - vrl: + source: | + .greptime_table_ttl = "7d" + . + +transform: + - fields: + - ip_address + type: string + index: inverted + tag: true + - fields: + - status_code + type: int32 + index: inverted + tag: true + - fields: + - request_line + - user_agent + type: string + index: fulltext + - fields: + - response_size + type: int32 + - fields: + - timestamp + type: time + index: timestamp +``` + +上面的 pipeline 配置使用 [version 2](/reference/pipeline/pipeline-config.md#transform-in-version-2) 格式, +包含 `processors` 和 `transform` 部分来结构化你的日志数据: + +**Processors**:用于在转换前预处理日志数据: +- **数据提取**:`dissect` 处理器使用 pattern 匹配来解析 `message` 字段并提取结构化数据,包括 `ip_address`、`timestamp`、`http_method`、`request_line`、`status_code`、`response_size` 和 `user_agent`。 +- **时间戳处理**:`date` 处理器使用格式 `%d/%b/%Y:%H:%M:%S %z` 解析提取的 `timestamp` 字段并将其转换为适当的时间戳数据类型。 +- **字段选择**:`select` 处理器从最终输出中排除原始 `message` 字段,同时保留所有其他字段。 +- **表选项**:`vrl` 处理器根据提取的字段设置表选项,例如向表名添加后缀和设置 TTL。`greptime_table_ttl = "7d"` 配置表数据的保存时间为 7 天。 + +**Transform**:定义如何转换和索引提取的字段: +- **字段转换**:每个提取的字段都转换为适当的数据类型并根据需要配置相应的索引。像 `http_method` 这样的字段在没有提供显式配置时保留其默认数据类型。 +- **索引策略**: + - `ip_address` 和 `status_code` 使用倒排索引作为标签进行快速过滤 + - `request_line` 和 `user_agent` 使用全文索引以获得最佳文本搜索能力 + - `timestamp` 是必需的时间索引列 + +有关 pipeline 配置选项的详细信息, +请参考 [Pipeline 配置](/reference/pipeline/pipeline-config.md) 文档。 + +## 上传 Pipeline + +执行以下命令上传 pipeline 配置: + +```shell +curl -X "POST" \ + "http://localhost:4000/v1/pipelines/nginx_pipeline" \ + -H 'Authorization: Basic {{authentication}}' \ + -F "file=@pipeline.yaml" +``` + +成功执行后,将创建一个名为 `nginx_pipeline` 的 pipeline 并返回以下结果: + +```json +{"name":"nginx_pipeline","version":"2024-06-27 12:02:34.257312110Z"}. +``` + +你可以为同一个 pipeline 名称创建多个版本。 +所有 pipeline 都存储在 `greptime_private.pipelines` 表中。 +参考[查询 Pipeline](manage-pipelines.md#查询-pipeline) 来查看 pipeline 数据。 + +## 使用 Pipeline 写入日志 + +以下示例使用 `nginx_pipeline` pipeline 将日志写入 `custom_pipeline_logs` 表来格式化和转换日志消息: + +```shell +curl -X POST \ + "http://localhost:4000/v1/ingest?db=public&table=custom_pipeline_logs&pipeline_name=nginx_pipeline" \ + -H "Content-Type: application/json" \ + -H "Authorization: Basic {{authentication}}" \ + -d '[ + { + "message": "127.0.0.1 - - [25/May/2024:20:16:37 +0000] \"GET /index.html HTTP/1.1\" 200 612 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\"" + }, + { + "message": "192.168.1.1 - - [25/May/2024:20:17:37 +0000] \"POST /api/login HTTP/1.1\" 200 1784 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36\"" + }, + { + "message": "10.0.0.1 - - [25/May/2024:20:18:37 +0000] \"GET /images/logo.png HTTP/1.1\" 304 0 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0\"" + }, + { + "message": "172.16.0.1 - - [25/May/2024:20:19:37 +0000] \"GET /contact HTTP/1.1\" 404 162 \"-\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1\"" + } + ]' +``` + +命令执行成功后将返回以下输出: + +```json +{"output":[{"affectedrows":4}],"execution_time_ms":79} +``` + +`custom_pipeline_logs` 表内容根据 pipeline 配置自动创建: + +```sql ++-------------+-------------+-------------+---------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+ +| ip_address | http_method | status_code | request_line | user_agent | response_size | timestamp | ++-------------+-------------+-------------+---------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+ +| 10.0.0.1 | GET | 304 | /images/logo.png HTTP/1.1 | Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0 | 0 | 2024-05-25 20:18:37 | +| 127.0.0.1 | GET | 200 | /index.html HTTP/1.1 | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 | 612 | 2024-05-25 20:16:37 | +| 172.16.0.1 | GET | 404 | /contact HTTP/1.1 | Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1 | 162 | 2024-05-25 20:19:37 | +| 192.168.1.1 | POST | 200 | /api/login HTTP/1.1 | Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 | 1784 | 2024-05-25 20:17:37 | ++-------------+-------------+-------------+---------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+ +``` + +有关日志写入 API 端点 `/ingest` 的更详细信息, +包括附加参数和配置选项, +请参考[日志写入 API](/reference/pipeline/write-log-api.md) 文档。 + +## 查询日志 + +我们使用 `custom_pipeline_logs` 表作为示例来查询日志。 + +### 通过 tag 查询日志 + +通过 `custom_pipeline_logs` 中的多个 tag 列, +你可以灵活地通过 tag 查询数据。 +例如,查询 `status_code` 为 200 且 `http_method` 为 GET 的日志。 + +```sql +SELECT * FROM custom_pipeline_logs WHERE status_code = 200 AND http_method = 'GET'; +``` + +```sql ++------------+-------------+----------------------+---------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +| ip_address | status_code | request_line | user_agent | response_size | timestamp | http_method | ++------------+-------------+----------------------+---------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +| 127.0.0.1 | 200 | /index.html HTTP/1.1 | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 | 612 | 2024-05-25 20:16:37 | GET | ++------------+-------------+----------------------+---------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +1 row in set (0.02 sec) +``` + +### 全文搜索 + +对于文本字段 `request_line` 和 `user_agent`,你可以使用 `matches_term` 函数来搜索日志。 +还记得我们在[创建 pipeline](#create-a-pipeline) 时为这两列创建了全文索引。 +这带来了高性能的全文搜索。 + +例如,查询 `request_line` 列包含 `/index.html` 或 `/api/login` 的日志。 + +```sql +SELECT * FROM custom_pipeline_logs WHERE matches_term(request_line, '/index.html') OR matches_term(request_line, '/api/login'); +``` + +```sql ++-------------+-------------+----------------------+--------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +| ip_address | status_code | request_line | user_agent | response_size | timestamp | http_method | ++-------------+-------------+----------------------+--------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +| 127.0.0.1 | 200 | /index.html HTTP/1.1 | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 | 612 | 2024-05-25 20:16:37 | GET | +| 192.168.1.1 | 200 | /api/login HTTP/1.1 | Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 | 1784 | 2024-05-25 20:17:37 | POST | ++-------------+-------------+----------------------+--------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +2 rows in set (0.00 sec) +``` + +你可以参考[全文搜索](fulltext-search.md) 文档了解 `matches_term` 函数的详细用法。 + + +## 使用 Pipeline 的好处 + +使用 pipeline 处理日志带来了结构化的数据和自动的字段提取, +这使得查询和分析更加高效。 + +你也可以在没有 pipeline 的情况下直接将日志写入数据库, +但这种方法限制了高性能分析能力。 + +### 直接插入日志(不使用 Pipeline) + +为了比较,你可以创建一个表来存储原始日志消息: + +```sql +CREATE TABLE `origin_logs` ( + `message` STRING FULLTEXT INDEX, + `time` TIMESTAMP TIME INDEX +) WITH ( + append_mode = 'true' +); +``` + +使用 `INSERT` 语句将日志插入表中。 +注意你需要为每个日志手动添加时间戳字段: + +```sql +INSERT INTO origin_logs (message, time) VALUES +('127.0.0.1 - - [25/May/2024:20:16:37 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"', '2024-05-25 20:16:37.217'), +('192.168.1.1 - - [25/May/2024:20:17:37 +0000] "POST /api/login HTTP/1.1" 200 1784 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36"', '2024-05-25 20:17:37.217'), +('10.0.0.1 - - [25/May/2024:20:18:37 +0000] "GET /images/logo.png HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0"', '2024-05-25 20:18:37.217'), +('172.16.0.1 - - [25/May/2024:20:19:37 +0000] "GET /contact HTTP/1.1" 404 162 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1"', '2024-05-25 20:19:37.217'); +``` + +### 表结构比较:Pipeline 转换后 vs 原始日志 + +在上面的示例中,表 `custom_pipeline_logs` 是通过使用 pipeline 写入日志自动创建的, +而表 `origin_logs` 是通过直接写入日志创建的。 +让我们看一看这两个表之间的差异。 + +```sql +DESC custom_pipeline_logs; +``` + +```sql ++---------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++---------------+---------------------+------+------+---------+---------------+ +| ip_address | String | PRI | YES | | TAG | +| status_code | Int32 | PRI | YES | | TAG | +| request_line | String | | YES | | FIELD | +| user_agent | String | | YES | | FIELD | +| response_size | Int32 | | YES | | FIELD | +| timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| http_method | String | | YES | | FIELD | ++---------------+---------------------+------+------+---------+---------------+ +7 rows in set (0.00 sec) +``` + +```sql +DESC origin_logs; +``` + +```sql ++---------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++---------+----------------------+------+------+---------+---------------+ +| message | String | | YES | | FIELD | +| time | TimestampMillisecond | PRI | NO | | TIMESTAMP | ++---------+----------------------+------+------+---------+---------------+ +``` + +以上表结构显示了关键差异: + +`custom_pipeline_logs` 表(使用 pipeline 创建)自动将日志数据结构化为多列: +- `ip_address`、`status_code` 作为索引标签用于快速过滤 +- `request_line`、`user_agent` 具有全文索引用于文本搜索 +- `response_size`、`http_method` 作为常规字段 +- `timestamp` 作为时间索引 + +`origin_logs` 表(直接插入)将所有内容存储在单个 `message` 列中。 + +### 为什么使用 Pipeline? + +建议使用 pipeline 方法将日志消息拆分为多列, +这具有明确查询特定列中特定值的优势。 +有几个关键原因使得基于列的匹配查询比全文搜索更优越: + +- **性能**:基于列的查询通常比全文搜索更快 +- **存储效率**:GreptimeDB 的列式存储能更好地压缩结构化数据;标签的倒排索引比全文索引消耗更少的存储空间 +- **查询简单性**:基于标签的查询更容易编写、理解和调试 + +## 下一步 + +- **全文搜索**:阅读[全文搜索](fulltext-search.md) 指南,了解 GreptimeDB 中的高级文本搜索功能和查询技术 +- **Pipeline 配置**:阅读 [Pipeline 配置](/reference/pipeline/pipeline-config.md) 文档,了解更多关于为各种日志格式和处理需求创建和自定义 pipeline 的信息 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/manage-data/data-index.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/manage-data/data-index.md new file mode 100644 index 0000000000..7c69bd838f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/manage-data/data-index.md @@ -0,0 +1,234 @@ +--- +keywords: [索引, 倒排索引, 跳数索引, 全文索引, 查询性能] +description: 了解 GreptimeDB 支持的各类索引,包括倒排索引、跳数索引和全文索引,以及如何合理使用这些索引来提升查询效率。 +--- + +# 数据索引 + +GreptimeDB 提供了多种索引机制来提升查询性能。作为数据库中的核心组件,索引通过建立高效的数据检索路径,显著优化了数据的查询操作。 + +## 概述 + +在 GreptimeDB 中,索引是在表创建时定义的,其设计目的是针对不同的数据类型和查询模式来优化查询性能。目前支持的索引类型包括: + +- 倒排索引(Inverted Index) +- 跳数索引(Skipping Index) +- 全文索引(Fulltext Index) + +需要说明的是,本章节重点讨论数据值索引。虽然主键(PRIMARY KEY)和 TIME INDEX 也在某种程度上具有索引的特性,但不在本章讨论范围内。 + +## 索引类型 + +### 倒排索引 + +倒排索引主要用于优化 Tag 列的查询效率。它通过在唯一值和对应数据行之间建立映射关系,实现对特定标签值的快速定位。 + +Tag 列不会被自动建立倒排索引, +你需要考虑以下使用场景手动为 Tag 列建立倒排索引: +- 基于标签值的数据查询 +- 字符串列的过滤操作 +- Tag 列的精确查询 + +示例: +```sql +CREATE TABLE monitoring_data ( + host STRING INVERTED INDEX, + region STRING PRIMARY KEY INVERTED INDEX, + cpu_usage DOUBLE, + `timestamp` TIMESTAMP TIME INDEX, +); +``` + +需要注意的是,当标签值的组合数(即倒排索引覆盖的列的笛卡尔积)非常大时,倒排索引可能会带来较高的维护成本,导致内存占用增加和索引体积膨胀。这种情况下,建议考虑使用跳数索引作为替代方案。 + +### 跳数索引 + +跳数索引是专为列式存储系统(如 GreptimeDB)优化设计的索引类型。它通过维护数据块内值域范围的元数据,使查询引擎能够在进行范围查询时快速跳过不相关的数据块。与其他索引相比,跳数索引的存储开销相对较小。 + +**适用场景:** +- 数据分布稀疏的场景,例如日志中的 MAC 地址 +- 在大规模数据集中查询出现频率较低的值 + +示例: +```sql +CREATE TABLE sensor_data ( + domain STRING PRIMARY KEY, + device_id STRING SKIPPING INDEX, + temperature DOUBLE, + `timestamp` TIMESTAMP TIME INDEX, +); +``` + +跳数索引支持 `WITH` 选项: +* `type`: 索引类型,目前仅支持 `BLOOM` 类型。 +* `granularity`: (适用于 `BLOOM` 类型)每个过滤器覆盖的数据块大小。粒度越小,过滤效果越好,但索引大小会增加。默认为 `10240`。 +* `false_positive_rate`: (适用于 `BLOOM` 类型)错误识别块的概率。该值越低,准确性越高(过滤效果越好),但索引大小会增加。该值为介于 `0` 和 `1` 之间的浮点数。默认为 `0.01`。 + +例如: + +```sql +CREATE TABLE sensor_data ( + domain STRING PRIMARY KEY, + device_id STRING SKIPPING INDEX WITH(type='BLOOM', granularity=1024, false_positive_rate=0.01), + temperature DOUBLE, + `timestamp` TIMESTAMP TIME INDEX, +); +``` + +然而,跳数索引无法处理复杂的过滤条件,并且其过滤性能通常不如倒排索引或全文索引。 + +### 全文索引 + +全文索引专门用于优化字符串列的文本搜索操作。它支持基于词的匹配和文本搜索功能,能够实现对文本内容的高效检索。你可以使用灵活的关键词、短语或模式匹配来查询文本数据。 + +**适用场景:** +- 文本内容搜索 +- 模式匹配查询 +- 大规模文本过滤 + +示例: +```sql +CREATE TABLE logs ( + message STRING FULLTEXT INDEX, + `level` STRING PRIMARY KEY, + `timestamp` TIMESTAMP TIME INDEX, +); +``` + +#### 配置选项 + +在创建或修改全文索引时,您可以使用 `FULLTEXT INDEX WITH` 指定以下选项: + +- `analyzer`:设置全文索引的语言分析器 + - 支持的值:`English`、`Chinese` + - 默认值:`English` + - 注意:由于中文文本分词的复杂性,中文分析器构建索引需要的时间显著更长。建议仅在中文文本搜索是主要需求时使用。 + +- `case_sensitive`:决定全文索引是否区分大小写 + - 支持的值:`true`、`false` + - 默认值:`false` + - 注意:设置为 `true` 可能会略微提高区分大小写查询的性能,但会降低不区分大小写查询的性能。此设置不会影响 `matches_term` 查询的结果。 + +- `backend`:设置全文索引的后端实现 + - 支持的值:`bloom`、`tantivy` + - 默认值:`bloom` + +- `granularity`:(适用于 `bloom` 后端)每个过滤器覆盖的数据块大小。粒度越小,过滤效果越好,但索引大小会增加。 + - 支持的值:正整数 + - 默认值:`10240` + +- `false_positive_rate`:(适用于 `bloom` 后端)错误识别块的概率。该值越低,准确性越高(过滤效果越好),但索引大小会增加。该值为介于 `0` 和 `1` 之间的浮点数。 + - 支持的值:介于 `0` 和 `1` 之间的浮点数 + - 默认值:`0.01` + +#### 后端选择 + +GreptimeDB 提供两种全文索引后端用于高效日志搜索: + +1. **Bloom 后端** + - 最适合:通用日志搜索 + - 特点: + - 使用 Bloom 过滤器进行高效过滤 + - 存储开销较低 + - 在不同查询模式下性能稳定 + - 限制: + - 对于高选择性查询稍慢 + - 存储成本示例: + - 原始数据:约 10GB + - Bloom 索引:约 1GB + +2. **Tantivy 后端** + - 最适合:高选择性查询(如 TraceID 等唯一值) + - 特点: + - 使用倒排索引实现快速精确匹配 + - 对高选择性查询性能优异 + - 限制: + - 存储开销较高(接近原始数据大小) + - 对低选择性查询性能较慢 + - 存储成本示例: + - 原始数据:约 10GB + - Tantivy 索引:约 10GB + +#### 性能对比 + +下表显示了不同查询方法之间的性能对比(以 Bloom 为基准): + +| 查询类型 | 高选择性(如 TraceID) | 低选择性(如 "HTTP") | +|------------|----------------------------------|--------------------------------| +| LIKE | 慢 50 倍 | 1 倍 | +| Tantivy | 快 5 倍 | 慢 5 倍 | +| Bloom | 1 倍(基准) | 1 倍(基准) | + +主要观察结果: +- 对于高选择性查询(如唯一值),Tantivy 提供最佳性能 +- 对于低选择性查询,Bloom 提供更稳定的性能 +- Bloom 在存储方面比 Tantivy 有明显优势(测试案例中为 1GB vs 10GB) + +#### 配置示例 + +**创建带全文索引的表** + +```sql +-- 使用 Bloom 后端(大多数情况推荐) +CREATE TABLE logs ( + timestamp TIMESTAMP(9) TIME INDEX, + message STRING FULLTEXT INDEX WITH ( + backend = 'bloom', + analyzer = 'English', + case_sensitive = 'false' + ) +); + +-- 使用 Tantivy 后端(用于高选择性查询) +CREATE TABLE logs ( + timestamp TIMESTAMP(9) TIME INDEX, + message STRING FULLTEXT INDEX WITH ( + backend = 'tantivy', + analyzer = 'English', + case_sensitive = 'false' + ) +); +``` + +**修改现有表** + +```sql +-- 在现有列上启用全文索引 +ALTER TABLE monitor +MODIFY COLUMN load_15 +SET FULLTEXT INDEX WITH ( + analyzer = 'English', + case_sensitive = 'false', + backend = 'bloom' +); + +-- 更改全文索引配置 +ALTER TABLE logs +MODIFY COLUMN message +SET FULLTEXT INDEX WITH ( + analyzer = 'English', + case_sensitive = 'false', + backend = 'tantivy' +); +``` + +## 修改索引 + +你可以随时通过`ALTER TABLE`语句来更改列的索引类型,阅读[文档](/reference/sql/alter#alter-table)以获取更多信息。 + +## 最佳实践 + +1. 根据实际的数据特征和查询模式选择合适的索引类型 +2. 只为频繁出现在 WHERE 子句中的列创建索引 +3. 在查询性能、写入性能和资源消耗之间寻找平衡 +4. 定期监控索引使用情况并持续优化索引策略 + +## 性能考虑 + +索引虽然能够显著提升查询性能,但也会带来一定开销: + +- 需要额外的存储空间维护索引结构 +- 索引维护会影响数据刷新和压缩性能 +- 索引缓存会占用系统内存 + +建议根据具体应用场景和性能需求,合理规划索引策略。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/manage-data/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/manage-data/overview.md new file mode 100644 index 0000000000..3932be9ac8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/manage-data/overview.md @@ -0,0 +1,346 @@ +--- +keywords: [数据管理, 数据更新, 数据删除, TTL 策略, 数据保留] +description: 介绍如何在 GreptimeDB 中更新和删除数据,包括使用相同的 tag 和 time index 更新数据、删除数据、使用 TTL 策略保留数据等。 +--- + +# 管理数据 + +## 更新数据 + +### 使用相同的 tag 和 time index 更新数据 + +更新操作可以通过插入操作来实现。 +如果某行数据具有相同的 tag 和 time index,旧数据将被新数据替换,这意味着你只能更新 field 类型的列。 +想要更新数据,只需使用与现有数据相同的 tag 和 time index 插入新数据即可。 + +有关列类型的更多信息,请参阅[数据模型](/user-guide/concepts/data-model.md)。 + +:::warning 注意 +尽管更新操作的性能与插入数据相同,过多的更新可能会对查询性能产生负面影响。 +::: + +#### 更新表中的所有字段 + +在更新数据时,默认情况下所有字段都将被新值覆盖, +而 [InfluxDB 行协议](/user-guide/protocols/influxdb-line-protocol.md) 除外,它只会[更新表中的部分字段](#更新表中的部分字段)。 +以下示例使用 SQL 演示了更新表中所有字段的行为。 + +假设你有一个名为 `monitor` 的表,具有以下 schema。 +`host` 列表示 tag,`ts` 列表示 time index。 + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64, + memory FLOAT64, + PRIMARY KEY(host) +); +``` + +向 `monitor` 表中插入一行新数据: + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +VALUES ("127.0.0.1", "2024-07-11 20:00:00", 0.8, 0.1); +``` + +检查表中的数据: + +```sql +SELECT * FROM monitor; +``` + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-07-11 20:00:00 | 0.8 | 0.1 | ++-----------+---------------------+------+--------+ +1 row in set (0.00 sec) +``` + +要更新数据,你可以使用与现有数据相同的 `host` 和 `ts` 值,并将新的 `cpu` 值设置为 `0.5`: + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +-- 与现有数据相同的标签 `127.0.0.1` 和相同的时间索引 2024-07-11 20:00:00 +VALUES ("127.0.0.1", "2024-07-11 20:00:00", 0.5, 0.1); +``` + +新数据将为: + +```sql +SELECT * FROM monitor; +``` + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-07-11 20:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +1 row in set (0.01 sec) +``` + +当使用默认的合并策略时, +如果在 `INSERT INTO` 语句中省略了某列, +它们将被默认值覆盖。 + +例如: + +```sql +INSERT INTO monitor (host, ts, cpu) +VALUES ("127.0.0.1", "2024-07-11 20:00:00", 0.5); +``` + +`monitor` 表中 `memory` 列的默认值为 `NULL`。因此,新数据将为: + +```sql +SELECT * FROM monitor; +``` + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-07-11 20:00:00 | 0.5 | NULL | ++-----------+---------------------+------+--------+ +1 row in set (0.01 sec) +``` + +### 更新表中的部分字段 + +默认情况下, [InfluxDB 行协议](/user-guide/protocols/influxdb-line-protocol.md) 支持此种更新策略。 +你还可以使用 SQL 在创建表时通过指定 `merge_mode` 选项为 `last_non_null` 来启用此行为。 +示例如下: + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64, + memory FLOAT64, + PRIMARY KEY(host) +) WITH ('merge_mode'='last_non_null'); +``` + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +VALUES ("127.0.0.1", "2024-07-11 20:00:00", 0.8, 0.1); +``` + +要更新 `monitor` 表中的特定字段, +你可以只插入带有要更新的字段的新数据。 +例如: + +```sql +INSERT INTO monitor (host, ts, cpu) +VALUES ("127.0.0.1", "2024-07-11 20:00:00", 0.5); +``` + +这将更新 `cpu` 字段,同时保持 `memory` 字段不变。 +结果将为: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-07-11 20:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +``` + + +请注意, `last_non_null` 无法将旧值更新为 `NULL`。 +例如: + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +VALUES ("127.0.0.1", "2024-07-11 20:00:01", 0.8, 0.1); +``` + +```sql +INSERT INTO monitor (host, ts, cpu) +VALUES ("127.0.0.1", "2024-07-11 20:00:01", NULL); +``` + +不会更新任何内容: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-07-11 20:00:01 | 0.8 | 0.1 | ++-----------+---------------------+------+--------+ +``` + +有关 `merge_mode` 选项的更多信息,请参阅 [CREATE TABLE](/reference/sql/create.md#创建带有-merge-模式的表) 语句。 + +### 通过创建带有 `append_mode` 选项的表来避免更新数据 + +在创建表时,GreptimeDB 支持 `append_mode` 选项,该选项始终将新数据插入表中。 +当你想要保留所有历史数据(例如日志)时十分有用。 + +你只能使用 SQL 创建带有 `append_mode` 选项的表。 +成功创建表后,所有[写入数据的协议](/user-guide/ingest-data/overview.md)都将在表中始终插入新数据。 + +例如,你可以创建一个带有 `append_mode` 选项的 `app_logs` 表,如下所示。 +`host` 和 `log_level` 列表示 tag,`ts` 列表示 time index。 + +```sql +CREATE TABLE app_logs ( + ts TIMESTAMP TIME INDEX, + host STRING, + api_path STRING FULLTEXT INDEX, + log_level STRING, + log STRING FULLTEXT INDEX, + PRIMARY KEY (host, log_level) +) WITH ('append_mode'='true'); +``` + +向 `app_logs` 表中插入一行新数据: + +```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'); +``` + +检查表中的数据: + +```sql +SELECT * FROM app_logs; +``` + +输出将为: + +```sql ++---------------------+-------+------------------+-----------+--------------------+ +| ts | host | api_path | log_level | log | ++---------------------+-------+------------------+-----------+--------------------+ +| 2024-07-11 20:00:10 | host1 | /api/v1/resource | ERROR | Connection timeout | ++---------------------+-------+------------------+-----------+--------------------+ +1 row in set (0.01 sec) +``` + +你可以插入具有相同 tag 和 time index 的新数据: + +```sql +INSERT INTO app_logs (ts, host, api_path, log_level, log) +-- 与现有数据相同的标签 `host1` 和 `ERROR`,相同的时间索引 2024-07-11 20:00:10 +VALUES ('2024-07-11 20:00:10', 'host1', '/api/v1/resource', 'ERROR', 'Connection reset'); +``` + +然后,你将在表中找到两行数据: + +```sql +SELECT * FROM app_logs; +``` + +```sql ++---------------------+-------+------------------+-----------+--------------------+ +| ts | host | api_path | log_level | log | ++---------------------+-------+------------------+-----------+--------------------+ +| 2024-07-11 20:00:10 | host1 | /api/v1/resource | ERROR | Connection reset | +| 2024-07-11 20:00:10 | host1 | /api/v1/resource | ERROR | Connection timeout | ++---------------------+-------+------------------+-----------+--------------------+ +2 rows in set (0.01 sec) +``` + +## 删除数据 + +你可以通过指定 tag 和 time index 来有效地删除数据。 +未指定 tag 和 time index 进行删除数据不高效,因为它需要两个步骤:查询数据,然后按 tag 和 time index 进行删除。 +有关列类型的更多信息,请参阅[数据模型](/user-guide/concepts/data-model.md)。 + +:::warning 警告 +过多的删除可能会对查询性能产生负面影响。 +::: + +只能使用 SQL 删除数据。 +例如,要从 `monitor` 表中删除具有 tag `host` 和 time index `ts` 的行: + +```sql +DELETE FROM monitor WHERE host='127.0.0.2' AND ts=1667446798450; +``` + +输出将为: + +```sql +Query OK, 1 row affected (0.00 sec) +``` + +有关 `DELETE` 语句的更多信息,请参阅 [SQL DELETE](/reference/sql/delete.md)。 + +## 删除表中的所有数据 + +要删除表中的所有数据,可以使用 SQL 中的 `TRUNCATE TABLE` 语句。 +例如,要清空 `monitor` 表: + +```sql +TRUNCATE TABLE monitor; +``` + +有关 `TRUNCATE TABLE` 语句的更多信息,请参阅 [SQL TRUNCATE TABLE](/reference/sql/truncate.md) 文档。 + +## 使用 TTL 策略保留数据 + +Time to Live (TTL) 允许你设置定期删除表中数据的策略, +你可以使用 TTL 自动删除数据库中的过期数据。 +设置 TTL 策略具有以下好处: + +- 通过清理过期数据来降低存储成本。 +- 减少数据库在某些查询中需要扫描的行数,从而提高查询性能。 + +> 请注意,因 TTL 策略而过期的数据,并不是在 TTL 到期时立刻删除的,而是发生在 compaction 时。compaction 是一个后台任务。 +> 如果你在测试 TTL 策略,查询过期数据之前请确保 flush 和 compaction 都已触发过了。 +> 你可以使用我们的 ”[ADMIN](/reference/sql/admin.md)“ 函数来手动触发。 + +你可以在创建每个表时设置 TTL。 +例如,以下 SQL 语句创建了一个名为 `monitor` 的表,并设置了 7 天的 TTL 策略: + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64, + memory FLOAT64, + PRIMARY KEY(host) +) WITH ('ttl'='7d'); +``` + +你还可以创建数据库级别的 TTL 策略。 +例如,以下 SQL 语句创建了一个名为 `test` 的数据库,并设置了 7 天的 TTL 策略: + +```sql +CREATE DATABASE test WITH ('ttl'='7d'); +``` + +你可以同时为 table 和 database 设置 TTL 策略。 +如果 table 有自己的 TTL 策略,则该策略将优先于 database 的 TTL 策略, +否则 database 的 TTL 策略将被应用于 table。 + +`'ttl'` 参数的值可以是持续时间(例如 `1hour 12min 5s`)、`instant` 或 `forever`。有关详细信息,请参阅 [CREATE](/reference/sql/create.md#创建指定-ttl-的表) 语句的文档。 + +使用 [`ALTER`](/reference/sql/alter.md#修改表的参数) 来修改现有表或数据库的 TTL: + +```sql +-- 针对表 +ALTER TABLE monitor SET 'ttl'='1 month'; +-- 针对数据库 +ALTER DATABASE test SET 'ttl'='1 month'; +``` + +如果你想移除 TTL 策略,可以使用如下 SQL 语句: + +```sql +-- 针对表移除 'ttl' 设置 +ALTER TABLE monitor UNSET 'ttl'; +-- 针对数据库移除 'ttl' 设置 +ALTER DATABASE test UNSET 'ttl'; +``` + +有关 TTL 策略的更多信息,请参阅 [CREATE](/reference/sql/create.md) 语句。 + +## 更多数据管理操作 + +有关更高级的数据管理操作,例如基本表操作、表分片和 Region 迁移,请参阅 Administration 部分的[数据管理](/user-guide/deployments-administration/manage-data/overview.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-clickhouse.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-clickhouse.md new file mode 100644 index 0000000000..c29e7b05af --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-clickhouse.md @@ -0,0 +1,245 @@ +--- +keywords: [从 ClickHouse 迁移, ClickHouse, GreptimeDB, 写入数据, 导出数据, 导入数据, 数据迁移] +description: 分步指南,指导如何从 ClickHouse 迁移到 GreptimeDB,包括数据模型调整、表结构重建、数据导出与导入等操作。 +--- + +# 从 ClickHouse 迁移 + +本指南详细介绍如何将业务平滑迁移自 ClickHouse 到 GreptimeDB,涵盖迁移前的准备、数据模型调整、表结构重构、双写保障以及数据导出与导入的具体方法,帮助实现系统的无缝切换。 + +## 迁移前须知 + +- **兼容性** + 虽然 GreptimeDB 支持 SQL 协议,但与 ClickHouse 在数据建模、索引设计和压缩机制等方面存在根本差异。请查阅 [SQL 兼容性](/reference/sql/compatibility.md) 文档以及官方[建模建议](/user-guide/deployments-administration/performance-tuning/design-table.md),在迁移过程中重构表结构与数据流。 + +- **数据模型差异** + ClickHouse 属于通用大数据分析引擎,GreptimeDB 则重点优化时序、指标及日志可观测场景。两者在数据模型、索引体系与压缩算法等方面均有差别,模型设计时需充分考虑业务场景及兼容性。 + +--- + +## 重新设计数据模型与表结构 + +### 时间索引 +- ClickHouse 的表未必有 time index 字段,迁移时需明确选择业务主要的时间字段作为时间索引,并在 GreptimeDB 建表时指定,如日志记录时间/链路追踪时间等。 +- 时间精度(秒、毫秒、微秒等)应按实际需求选定,且一旦设定不可更改。 + +### 主键与宽表建议 +- 主键:类似 ClickHouse 的 `order by`,去掉时间戳列;但不建议包含 log_id、user_id 或 UUID 等高基数字段,以避免主键膨胀、写放大和低效查询。 +- 宽表 vs 多表:同一个观测点采集多种指标时建议采用宽表,有助于提升批量写入效率和压缩比。 + +### 索引规划 +- 倒排索引:为低基数列建立索引,提高筛选效率。 +- 跳数索引:按需使用,适用于稀疏值或大表中偶尔查询的特定值。 +- 全文索引:按需使用,适用于字符串字段的文本检索,避免在高基数或高变动字段上建立无用索引。 +- 更多信息详见[数据索引](/user-guide/manage-data/data-index.md)。 + +### 表分区 +ClickHouse 通过 `PARTITION BY` 语法支持分区,GreptimeDB 提供类似能力,语法不同,请参阅[表分片](/user-guide/deployments-administration/manage-data/table-sharding.md)文档。 + +### TTL +GreptimeDB 支持通过表选项 `ttl` 设置生命周期,详见[使用 TTL 策略管理数据存储](/user-guide/manage-data/overview.md#使用-ttl-策略保留数据)。 + +### 表结构举例 + +ClickHouse 表: +```sql +CREATE TABLE example ( + timestamp DateTime, + host String, + app String, + metric String, + value Float64 +) ENGINE = MergeTree() +TTL timestamp + INTERVAL 30 DAY +ORDER BY (timestamp, host, app, metric); +```` + +GreptimeDB 推荐表结构: + +```sql +CREATE TABLE example ( + `timestamp` TIMESTAMP NOT NULL, + host STRING, + app STRING INVERTED INDEX, + metric STRING INVERTED INDEX, + `value` DOUBLE, + PRIMARY KEY (host, app, metric), + TIME INDEX (`timestamp`) +) with(ttl='30d'); +``` + +> 主键及时间索引的选型应结合业务数据量及查询场景慎重设计。如果 host 基数很大(如百万级监控主机),可不做主键,改为跳数索引。 + +### 典型日志表迁移 + +> GreptimeDB 已内置 otel 日志建模方案,操作详见[官方文档](/user-guide/ingest-data/for-observability/opentelemetry.md#logs)。 + +ClickHouse 日志表结构: + +```sql +CREATE TABLE logs + ( + timestamp DateTime, + host String, + service String, + log_level String, + log_message String, + trace_id String, + span_id String, + INDEX inv_idx(log_message) TYPE ngrambf_v1(4, 1024, 1, 0) GRANULARITY 1 + ) ENGINE = MergeTree + ORDER BY (timestamp, host, service); +``` + +推荐的 GreptimeDB 表结构: + +- 时间索引:`timestamp`(根据日志频率选定精度) +- 主键:`host`, `service`(常用过滤/聚合字段) +- 字段列:`log_message`, `trace_id`, `span_id`(高基数、唯一标识或原始内容) + +```sql +CREATE TABLE logs ( + `timestamp` TIMESTAMP NOT NULL, + host STRING, + service STRING, + log_level STRING, + log_message STRING FULLTEXT INDEX WITH ( + backend = 'bloom', + analyzer = 'English', + case_sensitive = 'false' + ), + trace_id STRING SKIPPING INDEX, + span_id STRING SKIPPING INDEX, + PRIMARY KEY (host, service), + TIME INDEX (`timestamp`) +); +``` + +**说明:** + +- `host` 和 `service` 作为常用过滤项列入主键,如主机数量非常多,可移出主键,改为跳数索引。 +- `log_message` 作为原始文本内容建立全文索引。**若要全文索引生效,查询时 SQL 语法也需调整,详见[日志检索文档](/user-guide/logs/fulltext-search.md)**。 +- `trace_id` 和 `span_id` 通常为高基数字段,建议仅做跳数索引。 + + +### 典型链路表迁移 + +> GreptimeDB 已内置 otel 链路建模方案,详见[官方文档](/user-guide/ingest-data/for-observability/opentelemetry.md#traces)。 + +ClickHouse 链路表结构设计: + +```sql +CREATE TABLE traces ( + timestamp DateTime, + trace_id String, + span_id String, + parent_span_id String, + service String, + operation String, + duration UInt64, + status String, + tags Map(String, String) +) ENGINE = MergeTree() +ORDER BY (timestamp, trace_id, span_id); +``` + +GreptimeDB 推荐表结构: + +- 时间索引:`timestamp`(采集/起始时间) +- 主键:`service`, `operation`(常用过滤/聚合属性) +- 字段列:`trace_id`, `span_id`, `parent_span_id`, `duration`, `tags`(高基数或 Map 字段) + +```sql +CREATE TABLE traces ( + `timestamp` TIMESTAMP NOT NULL, + service STRING, + operation STRING, + `status` STRING, + trace_id STRING SKIPPING INDEX, + span_id STRING SKIPPING INDEX, + parent_span_id STRING SKIPPING INDEX, + duration DOUBLE, + tags STRING, -- 如为结构化 JSON 可原样存储,必要时用 Pipeline 展开字段 + PRIMARY KEY (service, operation), + TIME INDEX (`timestamp`) +); +``` + +**说明:** + +- `service` 与 `operation` 作为主键,便于链路调度和按服务聚合。 +- `trace_id`、`span_id`、`parent_span_id` 用跳数索引,不作为主键。 +- 高基数字段仅作普通字段,便于写入效率;`tags` 推荐用字符串或 json,复杂属性可结合 [ETL Pipeline](/user-guide/logs/quick-start.md#使用-pipeline-写入日志) 展开。 +- 若业务量极大可考虑多表分区(如多服务场景区分)。 + + +双写保障迁移策略 +-------- + +迁移期间,为避免数据丢失和写入不一致,建议采用双写: + +- 应用需同时写入 ClickHouse 和 GreptimeDB,双系统并行。 +- 通过日志和校验对比数据,可保证一致性,数据无误后再切换全部流量。 + +历史数据导出与导入 +--------- + +1. **迁移前开启双写** 应用同时写入 ClickHouse 和 GreptimeDB,校验数据一致性,减少数据缺失风险。 + +2. **从 ClickHouse 导出数据** 利用 ClickHouse 命令将数据导出为 CSV、TSV、Parquet 等格式样例: + + +```sh +clickhouse client --query="SELECT * FROM example INTO OUTFILE 'example.csv' FORMAT CSVWithNames" +``` + +导出的 CSV 内容类似: + +```csv +"timestamp","host","app","metric","value" +"2024-04-25 10:00:00","host01","nginx","cpu_usage",12.7 +"2024-04-25 10:00:00","host02","redis","cpu_usage",8.4 +... +``` + +3. **导入数据到 GreptimeDB** + +> 需先在 GreptimeDB 创建好目标表。 + +支持 SQL 命令批量导入,或用 [REST API](/reference/http-endpoints.md#协议端点) 分批导入大数据量。 可用 [`COPY FROM` 命令](/reference/sql/copy.md#copy-from): + +```sql + COPY example FROM "/path/to/example.csv" WITH (FORMAT = 'CSV'); +``` + +或转换为标准 INSERT 语句分批导入。 + + +验证与流量切换 +------- + +- 导入完成后,使用 GreptimeDB 查询接口与 ClickHouse 进行数据对比。 +- 校验数据及监控无误后,可正式切换业务写入到 GreptimeDB,并关闭双写。 + + +常见问题与优化建议 +--------- + +### SQL/类型不兼容怎么办? + +迁移前需梳理所有查询 SQL 并按官方文档 ([SQL 查询](/user-guide/query-data/sql.md)、[日志检索](/user-guide/logs/fulltext-search.md)) 重写或翻译不兼容语法和类型。 + +### 如何高效批量导入大规模数据? + +大表或历史全量数据建议分分区/分片导出导入,并密切监控速度和进度。 + +### 高基数字段如何处理? + +避免作为主键,直接存为字段,必要时分表拆分。 + +### 宽表如何规划? + +每个监控对象(采集端)建议聚合到单表,如 `host_metrics` 专表存储服务器所有指标。 + + +如果您需要更详细的迁移方案或示例脚本,请提供具体表结构和数据量信息。[GreptimeDB 官方社区](https://github.com/orgs/GreptimeTeam/discussions)将为您提供进一步支持。欢迎加入 [Greptime Slack](http://greptime.com/slack) 交流。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-influxdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-influxdb.md new file mode 100644 index 0000000000..dcabee1b10 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-influxdb.md @@ -0,0 +1,195 @@ +--- +keywords: [InfluxDB 迁移, 数据迁移, HTTP API, 数据写入, 客户端库] +description: 指导用户从 InfluxDB 迁移到 GreptimeDB,包括使用 HTTP API 和客户端库写入数据的示例。 +--- + +import DocTemplate from '../../db-cloud-shared/migrate/migrate-from-influxdb.md' + +# 从 InfluxDB 迁移 + + + +
+ + + + +```shell +curl -X POST 'http://{{host}}:4000/v1/influxdb/api/v2/write?db={{db-name}}' \ + -H 'authorization: token {{greptime_user:greptimedb_password}}' \ + -d 'census,location=klamath,scientist=anderson bees=23 1566086400000000000' +``` + + + + + +```shell +curl 'http://{{host}}:4000/v1/influxdb/write?db={{db-name}}&u={{greptime_user}}&p={{greptimedb_password}}' \ + -d 'census,location=klamath,scientist=anderson bees=23 1566086400000000000' +``` + + + + + +
+ +
+ +有关详细的配置说明,请参考 [通过 Telegraf 写入数据](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md#telegraf) 文档。 + +
+ +
+ + + + +```js +'use strict' +/** @module write +**/ + +import { InfluxDB, Point } from '@influxdata/influxdb-client' + +/** Environment variables **/ +const url = 'http://:4000/v1/influxdb' +const token = ':' +const org = '' +const bucket = '' + +const influxDB = new InfluxDB({ url, token }) +const writeApi = influxDB.getWriteApi(org, bucket) +writeApi.useDefaultTags({ region: 'west' }) +const point1 = new Point('temperature') + .tag('sensor_id', 'TLM01') + .floatField('value', 24.0) +writeApi.writePoint(point1) + +``` + + + + + + +```python +import influxdb_client +from influxdb_client.client.write_api import SYNCHRONOUS + +bucket = "" +org = "" +token = ":" +url="http://:4000/v1/influxdb" + +client = influxdb_client.InfluxDBClient( + url=url, + token=token, + org=org +) + +# Write script +write_api = client.write_api(write_options=SYNCHRONOUS) + +p = influxdb_client.Point("my_measurement").tag("location", "Prague").field("temperature", 25.3) +write_api.write(bucket=bucket, org=org, record=p) + +``` + + + + + +```go +bucket := "" +org := "" +token := ":" +url := "http://:4000/v1/influxdb" +client := influxdb2.NewClient(url, token) +writeAPI := client.WriteAPIBlocking(org, bucket) + +p := influxdb2.NewPoint("stat", + map[string]string{"unit": "temperature"}, + map[string]interface{}{"avg": 24.5, "max": 45}, + time.Now()) +writeAPI.WritePoint(context.Background(), p) +client.Close() + +``` + + + + + +```java +private static String url = "http://:4000/v1/influxdb"; +private static String org = ""; +private static String bucket = ""; +private static char[] token = ":".toCharArray(); + +public static void main(final String[] args) { + + InfluxDBClient influxDBClient = InfluxDBClientFactory.create(url, token, org, bucket); + WriteApiBlocking writeApi = influxDBClient.getWriteApiBlocking(); + Point point = Point.measurement("temperature") + .addTag("location", "west") + .addField("value", 55D) + .time(Instant.now().toEpochMilli(), WritePrecision.MS); + + writeApi.writePoint(point); + influxDBClient.close(); +} +``` + + + + + +```php +$client = new Client([ + "url" => "http://:4000/v1/influxdb", + "token" => ":", + "bucket" => "", + "org" => "", + "precision" => InfluxDB2\Model\WritePrecision::S +]); + +$writeApi = $client->createWriteApi(); + +$dateTimeNow = new DateTime('NOW'); +$point = Point::measurement("weather") + ->addTag("location", "Denver") + ->addField("temperature", rand(0, 20)) + ->time($dateTimeNow->getTimestamp()); +$writeApi->write($point); +``` + + + + + +
+ +
+ +推荐使用 Grafana 可视化 GreptimeDB 数据, +请参考 [Grafana 文档](/user-guide/integrations/grafana.md) 了解如何配置 GreptimeDB。 + +
+ +
+ + +```shell +for file in data.*; do + curl -i --retry 3 \ + -X POST "http://${GREPTIME_HOST}:4000/v1/influxdb/write?db=${GREPTIME_DB}&u=${GREPTIME_USERNAME}&p=${GREPTIME_PASSWORD}" \ + --data-binary @${file} + sleep 1 +done +``` + +
+ +
diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-mysql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-mysql.md new file mode 100644 index 0000000000..f2824b104c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-mysql.md @@ -0,0 +1,103 @@ +--- +keywords: [MySQL 迁移, 数据迁移, 数据库创建, 数据导出, 数据导入] +description: 指导用户从 MySQL 迁移到 GreptimeDB,包括创建数据库和表、双写策略、数据导出和导入等步骤。 +--- + +# 从 MySQL 迁移 + +本文档将指引您完成从 MySQL 迁移到 GreptimeDB。 + +## 在开始迁移之前 + +请注意,尽管 GreptimeDB 支持 MySQL 的协议,并不意味着 GreptimeDB 实现了 MySQL +的所有功能。你可以参考 +- [ANSI 兼容性](/reference/sql/compatibility.md)查看在 GreptimeDB 中使用 SQL 的约束。 +- [数据建模指南](/user-guide/deployments-administration/performance-tuning/design-table.md)创建合适的表结构。 +- [数据索引指南](/user-guide/manage-data/data-index.md)用于索引规划。 + +## 迁移步骤 + +### 在 GreptimeDB 中创建数据库和表 + +在从 MySQL 迁移数据之前,你首先需要在 GreptimeDB 中创建相应的数据库和表。 +由于 GreptimeDB 有自己的 SQL 语法用于创建表,因此你不能直接重用 MySQL 生成的建表 SQL。 + +当你为 GreptimeDB 编写创建表的 SQL 时,首先请了解其“[数据模型](/user-guide/concepts/data-model.md)”。然后,在创建表的 +SQL 中请考虑以下几点: + +1. 由于 time index 列在表创建后无法更改,所以你需要仔细选择 time index + 列。时间索引最好设置为数据生成时的自然时间戳,因为它提供了查询数据的最直观方式,以及最佳的查询性能。例如,在 IOT + 场景中,你可以使用传感器采集数据时的时间作为 time index;或者在可观测场景中使用事件的发生时间。 +2. 不建议在此迁移过程中另造一个时间戳用作时间索引,例如使用 `DEFAULT current_timestamp()` 创建的新列。也不建议使用具有随机时间戳的列。 +3. 选择合适的 time index 精度也至关重要。和 time index 的选择一样,一旦表创建完毕,time index + 的精度就无法变更了。请根据你的数据集在[这里](/reference/sql/data-types.md#与-mysql-和-postgresql-兼容的数据类型)找到最适合的时间戳类型。 +4. 仅在真正需要时才选择主键。GreptimeDB 中的主键与 MySQL 中的主键不同。仅在以下情况下才应使用主键: + - 大部分查询可以受益于排序。 + - 您需要通过主键和时间索引来删除重复行(包括删除)。 通常会被查询。标签列中的值是附加到收集源的标签,通常用于描述这些源的特定特征。标签列会被索引,从而使对它们的查询具有高性能。 + + 否则,设置主键是可选的,并且可能会损害性能。阅读[主键](/user-guide/deployments-administration/performance-tuning/design-table.md#主键)了解详情。 + + 最后,请参阅“[CREATE](/reference/sql/create.md)” SQL 文档,了解有关选择合适的数据类型和“ttl”或“compaction”选项等的更多详细信息。 + +5. 选择合适的索引以加快查询速度。 + - 倒排索引:非常适合按低基数列进行过滤,并快速查找具有特定值的行。 + - 跳数索引:适用于稀疏数据。 + - 全文索引:可以在大型文本列中实现高效的关键字和模式搜索。 + + 有关详细信息和最佳实践,请参阅[数据索引](/user-guide/manage-data/data-index.md) 文档。 + +### 双写 GreptimeDB 和 MySQL + +双写 GreptimeDB 和 MySQL 是迁移过程中防止数据丢失的有效策略。通过使用 MySQL 的客户端库(JDBC + 某个 MySQL +驱动),你可以建立两个客户端实例 —— 一个用于 GreptimeDB,另一个用于 MySQL。有关如何使用 SQL 将数据写入 +GreptimeDB,请参考[写入数据](/user-guide/ingest-data/for-iot/sql.md)部分。 + +若无需保留所有历史数据,你可以双写一段时间以积累业务所需的最新数据,然后停止向 MySQL 写入数据并仅使用 +GreptimeDB。如果需要完整迁移所有历史数据,请按照接下来的步骤操作。 + +### 从 MySQL 导出数据 + +[mysqldump](https://dev.mysql.com/doc/refman/8.4/en/mysqldump.html) 是一个常用的、从 MySQL 导出数据的工具。使用 +mysqldump,我们可以从 MySQL 中导出后续可直接导入到 GreptimeDB 的数据。例如,如果我们想要从 MySQL 导出两个数据库 `db1` 和 +`db2`,我们可以使用以下命令: + +```bash +mysqldump -h127.0.0.1 -P3306 -umysql_user -p --compact -cnt --skip-extended-insert --databases db1 db2 > /path/to/output.sql +``` + +替换 `-h`、`-P` 和 `-u` 参数为 MySQL 服务的正确值。`--databases` 参数用于指定要导出的数据库。输出将写入 +`/path/to/output.sql` 文件。 + +`/path/to/output.sql` 文件应该具有如下内容: + +```plaintext +~ ❯ cat /path/to/output.sql + +USE `db1`; +INSERT INTO `foo` (`ts`, `a`, `b`) VALUES (1,'hello',1); +INSERT INTO ... + +USE `db2`; +INSERT INTO `foo` (`ts`, `a`, `b`) VALUES (2,'greptime',2); +INSERT INTO ... +``` + +### 将数据导入 GreptimeDB + +[MySQL Command-Line Client](https://dev.mysql.com/doc/refman/8.4/en/mysql.html) 可用于将数据导入 +GreptimeDB。继续上面的示例,假设数据导出到文件 `/path/to/output.sql`,那么我们可以使用以下命令将数据导入 GreptimeDB: + +```bash +mysql -h127.0.0.1 -P4002 -ugreptime_user -p -e "source /path/to/output.sql" +``` + +替换 `-h`、`-P` 和 `-u` 参数为你的 GreptimeDB 服务的值。`source` 命令用于执行 `/path/to/output.sql` 文件中的 SQL +命令。若需要进行 debug,添加 `-vvv` 以查看详细的执行结果。 + +总结一下,数据迁移步骤如下图所示: + +![migrate mysql data steps](/migration-mysql.jpg) + +数据迁移完成后,你可以停止向 MySQL 写入数据,并继续使用 GreptimeDB! + +如果您需要更详细的迁移方案或示例脚本,请提供具体的表结构和数据量信息。[GreptimeDB 官方社区](https://github.com/orgs/GreptimeTeam/discussions)将为您提供进一步的支持。欢迎加入 [Greptime Slack](http://greptime.com/slack) 社区交流。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-postgresql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-postgresql.md new file mode 100644 index 0000000000..84a7309908 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-postgresql.md @@ -0,0 +1,127 @@ +--- +keywords: [PostgreSQL 迁移, 数据迁移, 数据库创建, 数据导出, 数据导入] +description: 指导用户从 PostgreSQL 迁移到 GreptimeDB,包括创建数据库和表、双写策略、数据导出和导入等步骤。 +--- + +# 从 PostgreSQL 迁移 + +本文档将指引您完成从 PostgreSQL 迁移到 GreptimeDB。 + +## 在开始迁移之前 + +请注意,尽管 GreptimeDB 支持 PostgreSQL 的协议,并不意味着 GreptimeDB 实现了 PostgreSQL +的所有功能。你可以参考 +- [ANSI 兼容性](/reference/sql/compatibility.md)查看在 GreptimeDB 中使用 SQL 的约束。 +- [数据建模指南](/user-guide/deployments-administration/performance-tuning/design-table.md)创建合适的表结构。 +- [数据索引指南](/user-guide/manage-data/data-index.md)用于索引规划。 + +## 迁移步骤 + +### 在 GreptimeDB 中创建数据库和表 + +在从 PostgreSQL 迁移数据之前,你首先需要在 GreptimeDB 中创建相应的数据库和表。 +由于 GreptimeDB 有自己的 SQL 语法用于创建表,因此你不能直接重用 PostgreSQL 生成的建表 SQL。 + +当你为 GreptimeDB 编写创建表的 SQL 时,首先请了解其“[数据模型](/user-guide/concepts/data-model.md)”。然后,在创建表的 +SQL 中请考虑以下几点: + +1. 由于 time index 列在表创建后无法更改,所以你需要仔细选择 time index + 列。时间索引最好设置为数据生成时的自然时间戳,因为它提供了查询数据的最直观方式,以及最佳的查询性能。例如,在 IOT + 场景中,你可以使用传感器采集数据时的时间作为 time index;或者在可观测场景中使用事件的发生时间。 +2. 不建议在此迁移过程中另造一个时间戳用作时间索引,例如使用 `DEFAULT current_timestamp()` 创建的新列。也不建议使用具有随机时间戳的列。 +3. 选择合适的 time index 精度也至关重要。和 time index 的选择一样,一旦表创建完毕,time index + 的精度就无法变更了。请根据你的数据集在[这里](/reference/sql/data-types.md#与-mysql-和-postgresql-兼容的数据类型)找到最适合的时间戳类型。 +4. 仅在真正需要时才选择主键。GreptimeDB 中的主键与 PosgreSQL 中的主键不同。仅在以下情况下才应使用主键: + - 大部分查询可以受益于排序。 + - 您需要通过主键和时间索引来删除重复行(包括删除)。 通常会被查询。标签列中的值是附加到收集源的标签,通常用于描述这些源的特定特征。标签列会被索引,从而使对它们的查询具有高性能。 + + 否则,设置主键是可选的,并且可能会损害性能。阅读[主键](/user-guide/deployments-administration/performance-tuning/design-table.md#主键)了解详情。 + + 最后,请参阅“[CREATE](/reference/sql/create.md)” SQL 文档,了解有关选择合适的数据类型和“ttl”或“compaction”选项等的更多详细信息。 + +5. 选择合适的索引以加快查询速度。 + - 倒排索引:非常适合按低基数列进行过滤,并快速查找具有特定值的行。 + - 跳数索引:适用于稀疏数据。 + - 全文索引:可以在大型文本列中实现高效的关键字和模式搜索。 + + 有关详细信息和最佳实践,请参阅[数据索引](/user-guide/manage-data/data-index.md) 文档。 + +### 双写 GreptimeDB 和 PostgreSQL + +双写 GreptimeDB 和 PostgreSQL 是迁移过程中防止数据丢失的有效策略。通过使用 PostgreSQL 的客户端库(JDBC + 某个 PostgreSQL +驱动),你可以建立两个客户端实例 —— 一个用于 GreptimeDB,另一个用于 PostgreSQL。有关如何使用 SQL 将数据写入 +GreptimeDB,请参考[写入数据](/user-guide/ingest-data/for-iot/sql.md)部分。 + +若无需保留所有历史数据,你可以双写一段时间以积累业务所需的最新数据,然后停止向 PostgreSQL 写入数据并仅使用 +GreptimeDB。如果需要完整迁移所有历史数据,请按照接下来的步骤操作。 + +### 从 PostgreSQL 导出数据 + +[pg_dump](https://www.postgresql.org/docs/current/app-pgdump.html) 是一个常用的、从 PostgreSQL 导出数据的工具。使用 +pg_dump,我们可以从 PostgreSQL 中导出后续可直接导入到 GreptimeDB 的数据。例如,如果我们想要从 PostgreSQL 的 database +`postgres` 中导出以 `db` 开头的 schema,我们可以使用以下命令: + +```bash +pg_dump -h127.0.0.1 -p5432 -Upostgres -ax --column-inserts -n 'db*' postgres | grep -v "^SE" > /path/to/output.sql +``` + +替换 `-h`、`-p` 和 `-U` 参数为 PostgreSQL 服务的正确值。`-n` 参数用于指定要导出的 schema。数据库 `postgres` 被放在了 `pg_dump` 命令的最后。注意这里我们将 +pg_dump 的输出经过了一个特殊的 `grep` 命令以过滤掉不需要的 `SET` 和 `SELECT` 行。最终输出将写入 `/path/to/output.sql` +文件。 + +`/path/to/output.sql` 文件应该具有如下内容: + +```plaintext +~ ❯ cat /path/to/output.sql + +-- +-- PostgreSQL database dump +-- + +-- Dumped from database version 16.4 (Debian 16.4-1.pgdg120+1) +-- Dumped by pg_dump version 16.4 + + +-- +-- Data for Name: foo; Type: TABLE DATA; Schema: db1; Owner: postgres +-- + +INSERT INTO db1.foo (ts, a) VALUES ('2024-10-31 00:00:00', 1); +INSERT INTO db1.foo (ts, a) VALUES ('2024-10-31 00:00:01', 2); +INSERT INTO db1.foo (ts, a) VALUES ('2024-10-31 00:00:01', 3); +INSERT INTO ... + + +-- +-- Data for Name: foo; Type: TABLE DATA; Schema: db2; Owner: postgres +-- + +INSERT INTO db2.foo (ts, b) VALUES ('2024-10-31 00:00:00', '1'); +INSERT INTO db2.foo (ts, b) VALUES ('2024-10-31 00:00:01', '2'); +INSERT INTO db2.foo (ts, b) VALUES ('2024-10-31 00:00:01', '3'); +INSERT INTO ... + + +-- +-- PostgreSQL database dump complete +-- +``` + +### 将数据导入 GreptimeDB + +”[psql -- PostgreSQL interactive terminal](https://www.postgresql.org/docs/current/app-psql.html)“可用于将数据导入 +GreptimeDB。继续上面的示例,假设数据导出到文件 `/path/to/output.sql`,那么我们可以使用以下命令将数据导入 GreptimeDB: + +```bash +psql -h127.0.0.1 -p4003 -d public -f /path/to/output.sql +``` + +替换 `-h` 和 `-p` 参数为你的 GreptimeDB 服务的值。psql 命令中的 `-d` 参数用于指定数据库,该参数不能省略,`-d` 的值 `public` 是 GreptimeDB 默认使用的数据库。你还可以添加 `-a` 以查看详细的执行结果,或使用 `-s` 进入单步执行模式。 + +总结一下,数据迁移步骤如下图所示: + +![migrate postgresql data steps](/migration-postgresql.jpg) + +数据迁移完成后,你可以停止向 PostgreSQL 写入数据,并继续使用 GreptimeDB! + +如果您需要更详细的迁移方案或示例脚本,请提供具体的表结构和数据量信息。[GreptimeDB 官方社区](https://github.com/orgs/GreptimeTeam/discussions)将为您提供进一步的支持。欢迎加入 [Greptime Slack](http://greptime.com/slack) 社区交流。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-prometheus.md new file mode 100644 index 0000000000..b00abce999 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-prometheus.md @@ -0,0 +1,30 @@ +--- +keywords: [Prometheus 迁移, 数据迁移, 监控数据, 数据导入, 数据查询] +description: 介绍从 Prometheus 迁移到 GreptimeDB 的步骤和注意事项。 +--- + +import DocTemplate from '../../db-cloud-shared/migrate/_migrate-from-prometheus.md' + +# 从 Prometheus 迁移 + + + +
+ +有关 Prometheus 将数据写入 GreptimeDB 的配置信息,请参阅 [Remote Write](/user-guide/ingest-data/for-observability/prometheus.md#配置-remote-write) 文档。 + +
+ +
+ +有关使用 Prometheus 查询语言在 GreptimeDB 中查询数据的详细信息,请参阅 PromQL 文档中的 [HTTP API](/user-guide/query-data/promql.md#prometheus-的-http-api) 部分。 + +
+ +
+ +要在 Grafana 中将 GreptimeDB 添加为 Prometheus 数据源,请参阅 [Grafana](/user-guide/integrations/grafana#prometheus-数据源) 的集成文档。 + +
+ +
\ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/overview.md new file mode 100644 index 0000000000..a0435ad8c1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/migrate-to-greptimedb/overview.md @@ -0,0 +1,13 @@ +--- +keywords: [从 MySQL 迁移, 从 InfluxDB 迁移, 从 PostgreSQL 迁移, 从 Prometheus 迁移, 从 ClickHouse 迁移] +description: 从各种数据库迁移到 GreptimeDB 的概述,包括 InfluxDB、MySQL、PostgreSQL、Prometheus 等。 +--- + +# 迁移到 GreptimeDB + +import DocCardList from '@theme/DocCardList'; + +你可以从多种数据库迁移到 GreptimeDB,例如 InfluxDB、MySQL、PostgreSQL、Prometheus 等。 + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/overview.md new file mode 100644 index 0000000000..f313831708 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/overview.md @@ -0,0 +1,75 @@ +--- +keywords: [概述, 可观测, 物联网, 日志存储, 边缘计算, SQL 查询, 数据处理, 数据模型, 范围查询] +description: 了解如何根据你的使用场景使用 GreptimeDB,包括数据写入、查询和管理。 +--- + +# 用户指南 + +欢迎使用 GreptimeDB 用户指南。 + +GreptimeDB 是用于指标、事件和日志的统一可观测性数据库, +可提供从边缘到云的任何规模的实时洞察。 + +## 理解 GreptimeDB 的概念 + +在深入了解 GreptimeDB 之前, +建议先熟悉数据模型、关键概念和功能。 +请参阅 [概念文档](./concepts/overview.md)。 + +## 根据你的使用场景写入数据 + +GreptimeDB 支持[多种协议](./protocols/overview.md)和[集成工具](./integrations/overview.md), +以便根据你的需求写入数据。 + +### 可观测性指标场景 + +如果你计划将 GreptimeDB 用于存储可观测性指标、日志和链路追踪, +请参阅[可观测性文档](./ingest-data/for-observability/overview.md)。 +该文档解释了如何使用 Otel-Collector, Vector、Kafka、Prometheus 和 InfluxDB 行协议等工具导入数据。 + +对于日志存储解决方案, +请参考 [日志文档](./logs/overview.md)。 +该文档详细说明了如何使用 Pipeline 写入结构化的文本日志。 + +对于链路追踪(trace)存储解决方案, +请参考 [trace 文档](./traces/overview.md)。 +该文档解释了使用 OpenTelemetry 导入数据以及使用 Jaeger 查询数据的方法。 + +### 物联网和边缘计算场景 + +对于物联网和边缘计算场景, +[物联网文档](./ingest-data/for-iot/overview.md)提供了从多种来源导入数据的全面指导。 + +## 查询数据以获取洞察 + +GreptimeDB 提供了强大的[数据查询](./query-data/overview.md)功能。 + +### SQL 支持 + +你可以使用 SQL 进行范围查询、聚合等操作。 +有关详细说明,请参阅 [SQL 查询文档](./query-data/sql.md)。 + +### Prometheus 查询语言 (PromQL) + +GreptimeDB 支持使用 PromQL 查询数据。 +请参考 [PromQL 文档](./query-data/promql.md) 以获取指导。 + +### 流计算 + +对于实时数据处理和分析,GreptimeDB 提供了[流计算](./flow-computation/overview.md), +支持对数据流进行复杂计算。 + +## 使用索引加速查询 + +倒排索引、跳数索引和全文索引等索引可以显著提升查询性能。 +有关如何有效使用这些索引的更多信息,请参阅[数据索引文档](./manage-data/data-index.md)。 + +## 从其他数据库迁移到 GreptimeDB + +你可以轻松从其他数据库迁移数据到 GreptimeDB, +请按照[迁移文档](./migrate-to-greptimedb/overview.md)中的分步说明进行操作。 + +## 管理和部署 GreptimeDB + +当你准备好部署 GreptimeDB 时, +请查阅[部署及管理文档](/user-guide/deployments-administration/overview.md)获取有关服务端部署和管理的详细指南。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/elasticsearch.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/elasticsearch.md new file mode 100644 index 0000000000..d287d9b52b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/elasticsearch.md @@ -0,0 +1,8 @@ +--- +keywords: [Elasticsearch, log storage, API, configuration, data model] +description: 学习如何使用 Elasticsearch 协议写入数据。 +--- + +# Elasticsearch + +请参考[使用 Elasticsearch 协议写入数据](/user-guide/ingest-data/for-observability/elasticsearch.md)获取详细信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/grpc.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/grpc.md new file mode 100644 index 0000000000..232b3eec6b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/grpc.md @@ -0,0 +1,5 @@ +# gRPC + +GreptimeDB 提供了 [gRPC SDK](/user-guide/ingest-data/for-iot/grpc-sdks/overview.md),用于高效和高性能的数据摄入。 + +如果没有适用于你的编程语言的 SDK,你可以按照贡献者指南[创建自己的 SDK](/contributor-guide/how-to/how-to-write-sdk.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/http.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/http.md new file mode 100644 index 0000000000..58032b24c5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/http.md @@ -0,0 +1,598 @@ +--- +keywords: [HTTP API, 数据库交互, 鉴权, 时区, 请求超时, 管理 Pipeline] +description: 介绍 GreptimeDB 提供的 HTTP API 用于与数据库进行交互。 +--- + +# HTTP API + +GreptimeDB 提供了 HTTP API 用于与数据库进行交互。如需查看完整的 API 端点列表,请查看 [HTTP Endpoints](/reference/http-endpoints.md)。 + +## Base URL + +API Base URL 是 `http(s)://{{host}}:{{port}}/`。 + +- 对于在本地机器上运行的 GreptimeDB 实例,Base URL 是 `http://localhost:4000/`,默认端口配置为 `4000`。你可以在[配置文件](/user-guide/deployments-administration/configuration.md#protocol-options)中更改服务的 host 和 port。 +- 对于 GreptimeCloud,Base URL 是 `https://{{host}}/`。你可以在 GreptimeCloud 控制台的 "Connection Information" 中找到 host。 + +在以下内容中,我们使用 `http://{{API-host}}/` 作为 Base URL 来演示 API。 + +## 通用 Headers + +### 鉴权 + +假设你已经正确设置了数据库[鉴权](/user-guide/deployments-administration/authentication/overview.md), +GreptimeDB 支持 HTTP API 中内置的 `Basic` 鉴权机制。要设置鉴权,请按照以下步骤操作: + +1. 使用 `` 格式和 `Base64` 算法对用户名和密码进行编码。 +2. 将编码后的凭据附加到下列 HTTP 请求头之一中: +- `Authorization : Basic ` +- `x-greptime-auth : Basic ` + +以下是一个示例。如果要使用用户名 `greptime_user` 和密码 `greptime_pwd` 连接到 GreptimeDB,请使用以下命令: + +```shell +curl -X POST \ +-H 'Authorization: Basic Z3JlcHRpbWVfdXNlcjpncmVwdGltZV9wd2Q=' \ +-H 'Content-Type: application/x-www-form-urlencoded' \ +-d 'sql=show tables' \ +http://localhost:4000/v1/sql +``` + +在此示例中,`Z3JlcHRpbWVfdXNlcjpncmVwdGltZV9wd2Q=` 表示 `greptime_user:greptime_pwd` 的 Base64 编码值。请确保用自己配置的用户名和密码替换它,并使用 Base64 进行编码。 + +:::tip 注意 +InfluxDB 使用自己的鉴权格式,请参阅 [InfluxDB](./influxdb-line-protocol.md) 获取详细信息。 +::: + +### 请求超时设置 + +GreptimeDB 支持在 HTTP 请求中使用 `X-Greptime-Timeout` 请求头,用于指定数据库服务器中运行的请求超时时间。 + +例如,以下请求为查询设置了 `120s` 的超时时间: + +```bash +curl -X POST \ +-H 'Authorization: Basic {{authentication}}' \ +-H 'X-Greptime-Timeout: 120s' \ +-H 'Content-Type: application/x-www-form-urlencoded' \ +-d 'sql=show tables' \ +http://localhost:4000/v1/sql +``` + +## Admin APIs + +:::tip 注意 +这些 API 在 GreptimeCloud 中无法使用。 +::: + +请参考 [Admin APIs 接口](/reference/http-endpoints.md#管理-api)文档以获取更多信息。 + +## POST SQL 语句 + +要通过 HTTP API 向 GreptimeDB 服务器提交 SQL 语句,请使用以下格式: + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authentication}}' \ + -H 'X-Greptime-Timeout: {{time precision}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d 'sql={{SQL-statement}}' \ +http://{{API-host}}/v1/sql +``` + +### Headers + +- [`Authorization`](#鉴权) +- [`X-Greptime-Timeout`](#请求超时设置) +- `Content-Type`: `application/x-www-form-urlencoded`. +- `X-Greptime-Timezone`: 当前 SQL 查询的时区。可选。请参阅[时区](#时区)。 + +### Query string parameters + +- `db`: 数据库名称。可选。如果未提供,将使用默认数据库 `public`。 +- `format`: 输出格式。可选。默认为 `greptimedb_v1` 的 JSON 格式。 + 除了默认的 JSON 格式外,HTTP API 还允许你通过提供 `format` 查询参数来自定义输出格式,值如下: + - `influxdb_v1`: [influxdb 查询 + API](https://docs.influxdata.com/influxdb/v1/tools/api/#query-http-endpoint) + 兼容格式。附加参数: + - `epoch`: `[ns,u,µ,ms,s,m,h]`,返回指定精度的时间戳 + - `csv`: 以逗号分隔值格式输出 + - `csvWithNames`: 以逗号分隔值格式输出,包含列名标题 + - `csvWithNamesAndTypes`: 以逗号分隔值格式输出,包含列名和数据类型标题 + - `arrow`: [Arrow IPC + 格式](https://arrow.apache.org/docs/python/feather.html)。附加参数: + - `compression`: `zstd` 或 `lz4`,默认:无压缩 + - `table`: 控制台输出的 ASCII 表格格式 + - `null`: 简洁的纯文本输出,仅显示行数和执行时间,用于评估查询性能。 + +### Body + +- `sql`: SQL 语句。必填。 + +### 响应 + +响应是一个 JSON 对象,包含以下字段: + +- `output`: SQL 执行结果,请参阅下面的示例以了解详细信息。 +- `execution_time_ms`: 语句的执行时间(毫秒)。 + +### 示例 + +#### `INSERT` 语句 + +例如,要向数据库 `public` 的 `monitor` 表中插入数据,请使用以下命令: + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d 'sql=INSERT INTO monitor VALUES ("127.0.0.1", 1667446797450, 0.1, 0.4), ("127.0.0.2", 1667446798450, 0.2, 0.3), ("127.0.0.1", 1667446798450, 0.5, 0.2)' \ + http://localhost:4000/v1/sql?db=public +``` + +Response 包含受影响的行数: + +```shell +{"output":[{"affectedrows":3}],"execution_time_ms":11} +``` + +#### `SELECT` 语句 + +你还可以使用 HTTP API 执行其他 SQL 语句。例如,从 `monitor` 表中查询数据: + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql?db=public +``` + +Response 包含 JSON 格式的查询数据: + +```json +{ + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "host", + "data_type": "String" + }, + { + "name": "ts", + "data_type": "TimestampMillisecond" + }, + { + "name": "cpu", + "data_type": "Float64" + }, + { + "name": "memory", + "data_type": "Float64" + } + ] + }, + "rows": [ + [ + "127.0.0.1", + 1720728000000, + 0.5, + 0.1 + ] + ], + "total_rows": 1 + } + } + ], + "execution_time_ms": 7 +} +``` + +Response 包含以下字段: + +- `output`: 执行结果。 + - `records`: 查询结果。 + - `schema`: 结果的 schema,包括每列的 schema。 + - `rows`: 查询结果的行,每行是一个包含 schema 中对应列值的数组。 +- `execution_time_ms`: 语句的执行时间(毫秒)。 + +#### 时区 + +GreptimeDB 支持 HTTP 请求中的 `X-Greptime-Timezone` header。 +它用于为当前 SQL 查询指定时区。 + +例如,以下请求使用时区 `+1:00` 进行查询: + +```bash +curl -X POST \ +-H 'Authorization: Basic {{authentication}}' \ +-H 'X-Greptime-Timezone: +1:00' \ +-H 'Content-Type: application/x-www-form-urlencoded' \ +-d 'sql=SHOW VARIABLES time_zone;' \ +http://localhost:4000/v1/sql +``` + +查询后的结果为: + +```json +{ + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "TIME_ZONE", + "data_type": "String" + } + ] + }, + "rows": [ + [ + "+01:00" + ] + ] + } + } + ], + "execution_time_ms": 27 +} +``` + +有关时区如何影响数据的写入和查询,请参考[写入数据](/user-guide/ingest-data/for-iot/sql.md#time-zone)和[查询数据](/user-guide/query-data/sql.md#时区)部分中的 SQL 文档。 + +#### 使用 `table` 格式输出查询数据 + +你可以在查询字符串参数中使用 `table` 格式,以 ASCII 表格格式获取输出。 + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql?db=public&format=table +``` + +输出 + +``` +┌─host────────┬─ts────────────┬─cpu─┬─memory─┐ +│ "127.0.0.1" │ 1667446797450 │ 0.1 │ 0.4 │ +│ "127.0.0.1" │ 1667446798450 │ 0.5 │ 0.2 │ +│ "127.0.0.2" │ 1667446798450 │ 0.2 │ 0.3 │ +└─────────────┴───────────────┴─────┴────────┘ +``` + + +#### 使用 `csvWithNames` 格式输出查询数据 + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql?db=public&format=csvWithNames +``` + +输出: +```csv +host,ts,cpu,memory +127.0.0.1,1667446797450,0.1,0.4 +127.0.0.1,1667446798450,0.5,0.2 +127.0.0.2,1667446798450,0.2,0.3 +``` + +将 `format` 改为 `csvWithNamesAndTypes`: +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql?db=public&format=csvWithNamesAndTypes +``` + +输出: +```csv +host,ts,cpu,memory +String,TimestampMillisecond,Float64,Float64 +127.0.0.1,1667446797450,0.1,0.4 +127.0.0.1,1667446798450,0.5,0.2 +127.0.0.2,1667446798450,0.2,0.3 +``` + +#### 使用 `influxdb_v1` 格式输出查询数据 + +你可以在查询字符串参数中使用 `influxdb_v1` 格式,以 InfluxDB 查询 API 兼容格式获取输出。 + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql?db=public&format=influxdb_v1&epoch=ms +``` + +```json +{ + "results": [ + { + "statement_id": 0, + "series": [ + { + "name": "", + "columns": [ + "host", + "cpu", + "memory", + "ts" + ], + "values": [ + [ + ["127.0.0.1", 0.1, 0.4, 1667446797450], + ["127.0.0.1", 0.5, 0.2, 1667446798450], + ["127.0.0.2", 0.2, 0.3, 1667446798450] + ] + ] + } + ] + } + ], + "execution_time_ms": 2 +} +``` + + +### 使用 GreptimeDB 的 SQL 方言解析 SQL + +为了解析和理解使用 GreptimeDB SQL 方言编写的查询(例如在仪表盘等工具里,为了更好的用户体验,提前解析 SQL 获取表名等),您可以使用 `/v1/sql/parse` 接口来获取 SQL 查询的结构化结果: + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql/parse +``` + +```json +[ + { + "Query": { + "inner": { + "with": null, + "body": { + "Select": { + "distinct": null, + "top": null, + "top_before_distinct": false, + "projection": [ + { + "Wildcard": { + "opt_ilike": null, + "opt_exclude": null, + "opt_except": null, + "opt_replace": null, + "opt_rename": null + } + } + ], + "into": null, + "from": [ + { + "relation": { + "Table": { + "name": [ + { + "value": "monitor", + "quote_style": null + } + ], + "alias": null, + "args": null, + "with_hints": [], + "version": null, + "with_ordinality": false, + "partitions": [] + } + }, + "joins": [] + } + ], + "lateral_views": [], + "prewhere": null, + "selection": null, + "group_by": { + "Expressions": [ + [], + [] + ] + }, + "cluster_by": [], + "distribute_by": [], + "sort_by": [], + "having": null, + "named_window": [], + "qualify": null, + "window_before_qualify": false, + "value_table_mode": null, + "connect_by": null + } + }, + "order_by": null, + "limit": null, + "limit_by": [], + "offset": null, + "fetch": null, + "locks": [], + "for_clause": null, + "settings": null, + "format_clause": null + } + } + } +] +``` + +## POST PromQL 查询 + +### API 返回 Prometheus 查询结果格式 + +GreptimeDB 兼容 Prometheus 查询语言 (PromQL),可以用于查询 GreptimeDB 中的数据。 +有关所有兼容的 API,请参阅 [Prometheus 查询语言](/user-guide/query-data/promql#prometheus-http-api) 文档。 + +### API 返回 GreptimeDB JSON 格式 + +GreptimeDB 同样暴露了一个自己的 HTTP API 用于 PromQL 查询,即在当前的 API 路径 `/v1` 的后方拼接 `/promql`。 +该接口的返回值是 GreptimeDB 的 JSON 格式,而不是 Prometheus 的格式。 +如下示例: + +```shell +curl -X GET \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -G \ + --data-urlencode 'query=avg(system_metrics{idc="idc_a"})' \ + --data-urlencode 'start=1667446797' \ + --data-urlencode 'end=1667446799' \ + --data-urlencode 'step=1s' \ + 'http://localhost:4000/v1/promql?db=public' +``` + +接口中的参数和 Prometheus' HTTP API 的 [`range_query`](https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries) 接口相似: + +- `db=`:在使用 GreptimeDB 进行鉴权操作时必填,如果使用的是 `public` 数据库则可以忽略该参数。注意这个参数需要被设置在 query param 中,或者通过 `--header 'x-greptime-db-name: '` 设置在 HTTP 请求头中。 +- `query=`:必填。Prometheus 表达式查询字符串。 +- `start=`:必填。开始时间戳,包含在内。它用于设置 `TIME INDEX` 列中的时间范围。 +- `end=`:必填。结束时间戳,包含在内。它用于设置 `TIME INDEX` 列中的时间范围。 +- `step=`:必填。查询步长,可以使用持续时间格式或秒数的浮点数。 +- `format`: 输出格式。可选。默认为 `greptimedb_v1` 的 JSON 格式。 + 除了默认的 JSON 格式外,HTTP API 还允许你通过提供 `format` 查询参数来自定义输出格式,值如下: + - `influxdb_v1`: [influxdb 查询 + API](https://docs.influxdata.com/influxdb/v1/tools/api/#query-http-endpoint) + 兼容格式。附加参数: + - `epoch`: `[ns,u,µ,ms,s,m,h]`,返回指定精度的时间戳 + - `csv`: 以逗号分隔值格式输出 + - `csvWithNames`: 以逗号分隔值格式输出,包含列名标题 + - `csvWithNamesAndTypes`: 以逗号分隔值格式输出,包含列名和数据类型标题 + - `arrow`: [Arrow IPC + 格式](https://arrow.apache.org/docs/python/feather.html)。附加参数: + - `compression`: `zstd` 或 `lz4`,默认:无压缩 + - `table`: 控制台输出的 ASCII 表格格式 + - `null`: 简洁的纯文本输出,仅显示行数和执行时间,用于评估查询性能。 + + +以下是每种参数的类型的示例: + +- rfc3339 + - `2015-07-01T20:11:00Z` (default to seconds resolution) + - `2015-07-01T20:11:00.781Z` (with milliseconds resolution) + - `2015-07-02T04:11:00+08:00` (with timezone offset) +- unix timestamp + - `1435781460` (default to seconds resolution) + - `1435781460.781` (with milliseconds resolution) +- duration + - `1h` (1 hour) + - `5d1m` (5 days and 1 minute) + - `2` (2 seconds) + - `2s` (also 2 seconds) + +结果格式与 [Post SQL 语句](#post-sql-语句)中描述的 `/sql` 接口相同。 + +```json +{ + "code": 0, + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "ts", + "data_type": "TimestampMillisecond" + }, + { + "name": "AVG(system_metrics.cpu_util)", + "data_type": "Float64" + }, + { + "name": "AVG(system_metrics.memory_util)", + "data_type": "Float64" + }, + { + "name": "AVG(system_metrics.disk_util)", + "data_type": "Float64" + } + ] + }, + "rows": [ + [ + 1667446798000, + 80.1, + 70.3, + 90 + ], + [ + 1667446799000, + 80.1, + 70.3, + 90 + ] + ] + } + } + ], + "execution_time_ms": 5 +} +``` + +## Post Influxdb line protocol 数据 + + + + + +```shell +curl -X POST \ + -H 'Authorization: token {{username:password}}' \ + -d '{{Influxdb-line-protocol-data}}' \ + http://{{API-host}}/v1/influxdb/api/v2/write?precision={{time-precision}} +``` + + + + + +```shell +curl -X POST \ + -d '{{Influxdb-line-protocol-data}}' \ + http://{{API-host}}/v1/influxdb/api/v1/write?u={{username}}&p={{password}}&precision={{time-precision}} +``` + + + + +### Headers + +- `Authorization`: **与其他 API 不同**,InfluxDB 行协议 API 使用 InfluxDB 鉴权格式。对于 V2 协议,Authorization 是 `token {{username:password}}`。 + +### Query string parameters + +- `u`: 用户名。可选。它是 V1 的鉴权用户名。 +- `p`: 密码。可选。它是 V1 的鉴权密码。 +- `db`: 数据库名称。可选。默认值是 `public`。 +- `precision`: 定义请求体中提供的时间戳的精度。请参考用户指南中的 [InfluxDB 行协议](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md)文档。 + +### Body + +InfluxDB 行协议数据点。请参考 [InfluxDB 行协议](https://docs.influxdata.com/influxdb/v1/write_protocols/line_protocol_tutorial/#syntax) 文档。 + +### 示例 + +请参考用户指南中的 [InfluxDB 行协议](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md)。 + +## 管理 Pipeline 的 API + +在将日志写入 GreptimeDB 时,你可以使用 HTTP API 来管理 Pipeline。 +请参考 [管理 Pipeline](/user-guide/logs/manage-pipelines.md) 文档。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/influxdb-line-protocol.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/influxdb-line-protocol.md new file mode 100644 index 0000000000..a82f8b7572 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/influxdb-line-protocol.md @@ -0,0 +1,41 @@ +--- +keywords: [InfluxDB Line Protocol, 写入数据, PING, health API] +description: 介绍如何使用 InfluxDB Line Protocol 向 GreptimeDB 写入数据。 +--- + +# InfluxDB Line Protocol + +## 写入数据 + +请参考[写入数据](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md)文档来了解如何使用 InfluxDB Line Protocol 向 GreptimeDB 写入数据。 + +## HTTP API + +请参考 [HTTP API](http.md#post-influxdb-line-protocol-数据) 文档来了解 Influxdb Line Protocol 的接口详情。 + +## PING + +GreptimeDB 同样支持 InfluxDB 的 `ping` 和 `health` API。 + +使用 `curl` 请求 `ping` API: + +```shell +curl -i "127.0.0.1:4000/v1/influxdb/ping" +``` + +```shell +HTTP/1.1 204 No Content +date: Wed, 22 Feb 2023 02:29:44 GMT +``` + +Use `curl` to request `health` API. + +```shell +curl -i "127.0.0.1:4000/v1/influxdb/health" +``` + +```shell +HTTP/1.1 200 OK +content-length: 0 +date: Wed, 22 Feb 2023 02:30:46 GMT +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/loki.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/loki.md new file mode 100644 index 0000000000..62116f00e9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/loki.md @@ -0,0 +1,8 @@ +--- +keywords: [Loki, log storage, API, configuration, data model] +description: 学习如何使用 Loki 协议写入数据。 +--- + +# Loki + +请参考[使用 Loki 协议写入数据](/user-guide/ingest-data/for-observability/loki.md)获取详细信息。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/mysql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/mysql.md new file mode 100644 index 0000000000..ae6b79701c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/mysql.md @@ -0,0 +1,88 @@ +--- +keywords: [MySQL 协议, 连接数据库, 管理表, 写入数据, 查询数据, 时区] +description: 介绍如何通过 MySQL 协议连接和使用 GreptimeDB。 +--- + +# MySQL + +## 连接数据库 + +你可以通过 MySQL 连接到 GreptimeDB,端口为 `4002`。 + +```shell +mysql -h -P 4002 -u -p +``` + +- 请参考[鉴权认证](/user-guide/deployments-administration/authentication/overview.md) 来设置 GreptimeDB 的用户名和密码。 +- 如果你想使用其他端口连接 MySQL,请参考配置文档中的[协议选项](/user-guide/deployments-administration/configuration.md#协议选项)。 + + +## 管理表 + +请参考[表管理](/user-guide/deployments-administration/manage-data/basic-table-operations.md)。 + +## 写入数据 + +请参考[写入数据](/user-guide/ingest-data/for-iot/sql.md). + +## 查询数据 + +请参考[查询数据](/user-guide/query-data/sql.md). + +## 时区 + +GreptimeDB 的 MySQL 协议接口遵循原始 MySQL 服务器的 [时区处理方式](https://dev.mysql.com/doc/refman/8.0/en/time-zone-support.html)。 + +默认情况下,MySQL 使用服务器的时区来处理时间戳。要覆盖这一行为,可以使用 SQL 语句 `SET time_zone = '';` 来为当前会话设置 `time_zone` 变量。`time_zone` 的值可以是: + +- 服务器的时区:`SYSTEM`。 +- UTC 的偏移量,例如 `+08:00`。 +- 任何时区的命名,例如 `Europe/Berlin`。 + +一些 MySQL 客户端,例如 Grafana 的 MySQL 数据源,允许你为当前会话设置时区。想要知道当前设定的时区,可以通过 SQL 语句 `SELECT @@time_zone;` 来查询。 + +你可以使用 `SELECT` 来查看当前的时区设置。例如: + +```sql +SELECT @@system_time_zone, @@time_zone; +``` + +结果显示系统时区和会话时区都设置为 `UTC`: + +```SQL ++--------------------+-------------+ +| @@system_time_zone | @@time_zone | ++--------------------+-------------+ +| UTC | UTC | ++--------------------+-------------+ +``` + +将会话时区更改为 `+1:00`: + +```SQL +SET time_zone = '+1:00' +``` + +你可以看到系统时区和会话时区之间的差异: + +```SQL +SELECT @@system_time_zone, @@time_zone; + ++--------------------+-------------+ +| @@system_time_zone | @@time_zone | ++--------------------+-------------+ +| UTC | +01:00 | ++--------------------+-------------+ +``` + +有关时区如何影响数据的插入和查询,请参考 [写入数据](/user-guide/ingest-data/for-iot/sql.md#时区) 和 [查询数据](/user-guide/query-data/sql.md#时区) 中的 SQL 文档。 + +## 查询超时 + +可以通过 SQL 语句 `SET max_execution_time = ` 或 `SET MAX_EXECUTION_TIME = ` 为当前会话设置 `max_execution_time` 变量,该变量指定**只读语句**执行的最大时间(以毫秒为单位)。如果查询的执行时间超过指定时间,服务器将终止该查询。 + +例如,将最大执行时间设置为 10 秒: + +```SQL +SET max_execution_time=10000; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/opentelemetry.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/opentelemetry.md new file mode 100644 index 0000000000..5fc8f61aae --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/opentelemetry.md @@ -0,0 +1,9 @@ +--- +keyword: [OpenTelemetry, OTLP] +description: 通过 OTLP/HTTP 协议原生消费 OpenTelemetry 指标 +--- + +# OpenTelemetry (OTLP) + +GreptimeDB 可以通过 [OTLP/HTTP](https://opentelemetry.io/docs/specs/otlp/#otlphttp) 协议写入 OpenTelemetry 指标。 +请参考[使用 OpenTelemetry 写入数据](/user-guide/ingest-data/for-observability/opentelemetry.md)文档获取详细信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/opentsdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/opentsdb.md new file mode 100644 index 0000000000..e9ac221036 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/opentsdb.md @@ -0,0 +1,3 @@ +# OpenTSDB + +请参考[使用 OpenTSDB 写入数据](/user-guide/ingest-data/for-iot/opentsdb.md)获取详细信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/overview.md new file mode 100644 index 0000000000..4676f854b3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/overview.md @@ -0,0 +1,10 @@ +--- +keywords: [InfluxDB Line Protocol, OpenTelemetry, MySQL, PostgreSQL, HTTP API, gRPC, OpenTSDB, Loki] +description: 了解如何使用不同的协议写入数据。 +--- + +import DocCardList from '@theme/DocCardList'; + +# 协议 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/postgresql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/postgresql.md new file mode 100644 index 0000000000..2d8c202d6d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/protocols/postgresql.md @@ -0,0 +1,183 @@ +--- +keywords: [pg, pgsql, PostgreSQL 协议, 连接数据库, 管理表, 写入数据, 读取数据, 时区, 外部数据] +description: 介绍如何通过 PostgreSQL 协议连接和使用 GreptimeDB。 +--- + +# PostgreSQL + +## 连接数据库 + +你可以通过端口 `4003` 使用 PostgreSQL 连接到 GreptimeDB。 +只需在命令中添加 `-U` 参数,后跟你的用户名和密码。以下是一个示例: + +```shell +psql -h -p 4003 -U -d public +``` + +- 请参考[鉴权认证](/user-guide/deployments-administration/authentication/overview.md) 来设置 GreptimeDB 的用户名和密码。 +- 如果你想使用其他端口连接 PostgreSQL,请参考配置文档中的[协议选项](/user-guide/deployments-administration/configuration.md#协议选项)。 + +## 管理表 + +请参考[管理表](/user-guide/deployments-administration/manage-data/basic-table-operations.md)。 + +## 写入数据 + +请参考[写入数据](/user-guide/ingest-data/for-iot/sql.md). + +## 读取数据 + +请参考 [读取数据](../query-data/sql.md). + +## 时区 + +GreptimeDB 的 PostgreSQL 协议遵循原始 PostgreSQL 的 [时区处理方式](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-TIMEZONES)。 + +默认情况下,PostgreSQL 使用服务器的时区来处理时间戳。 +你可以使用 SQL 语句 `SET TIMEZONE TO '';` 为当前会话设置 `time_zone` 变量来覆盖服务器时区。 +`time_zone` 的值可以是: + +- 时区的全称,例如 `America/New_York`。 +- 时区的缩写,例如 `PST`。 +- UTC 的偏移量,例如 `+08:00`。 + +你可以使用 `SHOW` 来查看当前的时区设置。例如: + +```sql +SHOW VARIABLES time_zone; +``` + +```sql + TIME_ZONE +----------- + UTC +``` + +将会话时区更改为 `+1:00`: + +```SQL +SET TIMEZONE TO '+1:00' +``` + +有关时区如何影响数据的插入和查询,请参考[写入数据](/user-guide/ingest-data/for-iot/sql.md#时区)和[查询数据](/user-guide/query-data/sql.md#时区)中的 SQL 文档。 + +## 外部数据 + +利用 Postgres 的 [FDW 扩 +展](https://www.postgresql.org/docs/current/postgres-fdw.html),GreptimeDB 可以 +被配置为 Postgres 的外部数据服务。这使得我们可以用 Postgres 服务器上无缝地查询 +GreptimeDB 里的时序数据,并且可以利用 join 查询同时关联两边的数据。 + +举个例子,类似设备信息类的物联网元数据,通常存储在 Postgres 这样的关系型数据库中。 +现在我们可以利用这个功能,先在 Postgres 利用关系查询过滤出满足条件的设备 ID,然 +后直接关联的 GreptimeDB 承载的外部表上查询设备的时序数据。 + +### 配置 + +首先要确保 GreptimeDB 打开了 Postgres 协议,并且她可以被 Postgres 服务器访问到。 + +在 Postgres 上开启 fdw 扩展。 + +```sql +CREATE EXTENSION postgres_fdw; +``` + +将 GreptimeDB 添加为远程服务器。 + +```sql +CREATE SERVER greptimedb +FOREIGN DATA WRAPPER postgres_fdw +OPTIONS (host 'greptimedb_host', dbname 'public', port '4003'); +``` + +把 Postgres 用户映射到 GreptimeDB 上。这一步是必须步骤。如果你没有在 GreptimeDB +开源版本上启用认证,这里可以填写任意的认证信息。 + +```sql +CREATE USER MAPPING FOR postgres +SERVER greptimedb +OPTIONS (user 'greptime', password '...'); +``` + +在 Postgres 创建与 GreptimeDB 映射的外部表。这一步是为了告知 Postgres 相应表的数 +据结构。注意需要将 GreptimeDB 的数据类型映射到 Postgres 类型上。 + +对于这样的 GreptimeDB 表: + +```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'); + +CREATE TABLE app_logs ( + ts TIMESTAMP TIME INDEX, + host STRING, + api_path STRING FULLTEXT INDEX, + log_level STRING, + log STRING FULLTEXT INDEX, + PRIMARY KEY (host, log_level) +) with('append_mode'='true'); +``` + +其 Postgres 外部表定义如下: + +```sql +CREATE FOREIGN TABLE ft_grpc_latencies ( + ts TIMESTAMP, + host VARCHAR, + method_name VARCHAR, + latency DOUBLE precision +) +SERVER greptimedb +OPTIONS (table_name 'grpc_latencies'); + +CREATE FOREIGN TABLE ft_app_logs ( + ts TIMESTAMP, + host VARCHAR, + api_path VARCHAR, + log_level VARCHAR, + log VARCHAR +) +SERVER greptimedb +OPTIONS (table_name 'app_logs'); +``` + +为了帮助用户生成这些语句,我们在 GreptimeDB 里增强了 `SHOW CREATE TABLE` 来直接 +输出可执行的语句。 + +```sql +SHOW CREATE TABLE grpc_latencies FOR postgres_foreign_table; +``` + +注意在输出的语句中你需要把服务器名 `greptimedb` 替换为之前在 `CREATE SERVER` 语句 +里使用的名字。 + +### 执行查询 + +至此你可以通过 Postgres 发起查询。并且可以使用一些同时存在在 GreptimeDB 和 +Postgres 上的函数,如 `date_trunc` 等。 + +```sql +SELECT * FROM ft_app_logs ORDER BY ts DESC LIMIT 100; + +SELECT + date_trunc('MINUTE', ts) as t, + host, + avg(latency), + count(latency) +FROM ft_grpc_latencies GROUP BY host, t; +``` + +## 语句执行超时 + +你可以通过 SQL 语句 `SET statement_timeout = ` 或 `SET STATEMENT_TIMEOUT = ` 为当前会话设置 `statement_timeout` 变量,该变量指定语句执行的最大时间(以毫秒为单位)。如果语句的执行时间超过指定时间,服务器将终止该语句。 + +例如,将最大执行时间设置为 10 秒: + +```SQL +SET statement_timeout=10000; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/api.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/api.md new file mode 100644 index 0000000000..8a606ae6c7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/api.md @@ -0,0 +1,93 @@ +# API + +## 内置模块和功能 + +我们提供了大量的内置函数供用户使用。下面是一个内置函数的列表。只要在脚本开头写上 `import greptime` 或 `from greptime import *` 就可以调用它们。 + +## 向量函数 + +| Function | Description | +| :--- | :--- | +| `pow(v0, v1)` | Raise a number `v0` to a power of `v1`. | +| `clip(v0, v1, v2)` | Clip all elements in a vector `v0` to a range between vectors `v1` and `v2`. | +| `diff(v0)` | Calculate the difference between adjacent elements in a vector `v0`. | +| `mean(v0)` | Calculate the mean of a vector `v0`. | +| `polyval(v0, v1)` | Evaluate a polynomial `v0` at points `v1`. similar to `numpy.polyval`. | +| `argmax(v0)` | Return the index of the maximum value in a vector `v0`. similar to `numpy.argmax`. | +| `argmin(v0)` | Return the index of the minimum value in a vector `v0`. similar to `numpy.argmin`. | +| `percentile` | Calculate the `q`-th percentile of a vector `v0`. similar to `numpy.percentile`. | +| `scipy_stats_norm_cdf` | Calculate the cumulative distribution function for the normal distribution. similar to `scipy.stats.norm.cdf`. | +| `scipy_stats_norm_pdf` | Calculate the probability density function for the normal distribution. similar to `scipy.stats.norm.pdf`. | + +## 数学函数 + +| Function | Description | +| :--- | :--- | +| `sqrt(v)` | Calculate the square root of a number `v`. | +| `sin(v)` | Calculate the sine of a number `v`. | +| `cos(v)` | Calculate the cosine of a number `v`. | +| `tan(v)` | Calculate the tangent of a number `v`. | +| `asin(v)` | Calculate the arcsine of a number `v`. | +| `acos(v)` | Calculate the arccosine of a number `v`. | +| `atan(v)` | Calculate the arctangent of a number `v`. | +| `floor(v)` | Calculate the floor of a number `v`. | +| `ceil(v)` | Calculate the ceiling of a number `v`. | +| `round(v)` | Calculate the nearest integer of a number `v`. | +| `trunc(v)` | Calculate the truncated integer of a number `v`. | +| `abs(v)` | Calculate the absolute value of a number `v`. | +| `signum(v)` | Calculate the sign(gives 1.0/-1.0) of a number `v`. | +| `exp(v)` | Calculate the exponential of a number `v`. | +| `ln(v)` | Calculate the natural logarithm of a number `v`. | +| `log2(v)` | Calculate the base-2 logarithm of a number `v`. | +| `log10(v)` | Calculate the base-10 logarithm of a number `v`. | + +## 效用函数和聚合函数 + +这些函数是由 `DataFusion` 绑定的。 +| Function | Description | +| :--- | :--- | +| `random(len)` | Generate a random vector with length `len`. | +| `approx_distinct(v0)` | Calculate the approximate number of distinct values in a vector `v0`. | +| `median(v0)` | Calculate the median of a vector `v0`. | +| `approx_percentile_cont(values, percent)` | Calculate the approximate percentile of a vector `values` at a given percentage `percent`. | +| `array_agg(v0)` | Aggregate values into an array. | +| `avg(v0)` | Calculate the average of a vector `v0`. | +| `correlation(v0, v1)` | Calculate the Pearson correlation coefficient of a vector `v0` and a vector `v1`. | +| `count(v0)` | Calculate the count of a vector `v0`. | +| `covariance(v0, v1)` | Calculate the covariance of a vector `v0` and a vector `v1`. | +| `covariance_pop(v0, v1)` | Calculate the population covariance of a vector `v0` and a vector `v1`. | +| `max(v0)` | Calculate the maximum of a vector `v0`. | +| `min(v0)` | Calculate the minimum of a vector `v0`. | +| `stddev(v0)` | Calculate the sample standard deviation of a vector `v0`. | +| `stddev_pop(v0)` | Calculate the population standard deviation of a vector `v0`. | +| `sum(v0)` | Calculate the sum of a vector `v0`. | +| `variance(v0)` | Calculate the sample variance of a vector `v0`. | +| `variance_pop(v0)` | Calculate the population variance of a vector `v0`. | + +## 数据框架的 methods + +| Method | Description | +| --- | --- | +| `select_columns(columns: List[str])` | select columns from DataFrame | +| `select(columns: List[Expr]])` | select columns from DataFrame using `PyExpr` | +| `filter(condition: Expr)` | filter DataFrame using `PyExpr` | +| `aggregate(group_expr: List[Expr], aggr_expr: List[Expr])` | Perform an aggregate query with optional grouping expressions. | +| `limit(skip: int, fetch: Optional[int])` |Limit the number of rows returned from this DataFrame. `skip` - Number of rows to skip before fetch any row; `fetch` - Maximum number of rows to fetch, after skipping skip rows. +| `union(other: DataFrame)` | Union two DataFrame | +| `union_distinct(other: DataFrame)` | Union two DataFrame, but remove duplicate rows | +| `distinct()` | Remove duplicate rows | +| `sort(expr: List[Expr])` | Sort DataFrame by `PyExpr`, Sort the DataFrame by the specified sorting expressions. Any expression can be turned into a sort expression by calling its sort method. | +| `join(right: DataFrame, left_cols: List[str], right_cols: List[str], filter: Optional[Expr])` | Join two DataFrame using the specified columns as join keys. Eight Join Types are supported: `inner`, `left`, `right`, `full`, `leftSemi`, `leftAnti`, `rightSemi`, `rightAnti`. | +| `intersect(other: DataFrame)` | Intersect two DataFrame | +| `except(other: DataFrame)` | Except two DataFrame | +| `collect()` | Collect DataFrame to a list of `PyVector` | + +## Expr 的 methods + +| Method | Description | +| --- | --- | +| `col(name: str)` | Create a `PyExpr` that represents a column | +| `lit(value: Any)` | Create a `PyExpr` that represents a literal value | +| `sort(ascending: bool, null_first: bool)` | Create a `PyExpr` that represents a sort expression | +| comparison operators: `==`, `!=`, `>`, `>=`, `<`, `<=` | Create `PyExpr` from compare two `PyExpr` | +| logical operators: `&`, `\|`, `~` | Create `PyExpr` from logical operation between two `PyExpr` | diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/data-types.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/data-types.md new file mode 100644 index 0000000000..825a60b839 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/data-types.md @@ -0,0 +1,185 @@ +# 数据类型 + +## DataFrame + +DataFrame 表示具有相同命名列的逻辑行集,类似于 [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) 或 [Spark DataFrame](https://spark.apache.org/docs/latest/sql-programming-guide.html)。 + +可以从 `sql` 创建一个 DataFrame: + +```python +from greptime import PyDataFrame, col +@copr(returns = ["value"]) +def query_numbers() -> vector[f64]: + df = PyDataFrame.from_sql("select number from numbers") + return df.filter(col('number') <= 5).collect()[0] +``` + +这与 `select number from numbers where number <=5` 相同,但使用了 DataFrame API。 + +事实上,协处理器的 DataFrame API 是 Apache Datafusion [DataFrame API](https://arrow.apache.org/datafusion/user-guide/dataframe.html) 的一个封装器。请参考 [API](api.md) 文档以获得完整的 DataFrame API。 + +## 向量 + +向量是协处理器中的主要数据类型,它是同类值的向量。通常,它是查询结果中提取的一列,但也可以在 Python 脚本中构建它。 + +向量就像编程语言中的数组类型,Apache [Arrow](https://arrow.apache.org/) 中的 `Array` 或 [NumPy](https://numpy.org/doc/stable/reference/arrays.html) 中的 `NDArray`。 + +### 向量类型 + +协处理器引擎支持以下类型的向量: + +| Type | Description | +| -------------- | -------------------------------- | +| `vector[str]` | The string type | +| `vector[bool]` | The boolean type | +| `vector[u8]` | The 8-bit unsigned integer type | +| `vector[u16]` | The 16-bit unsigned integer type | +| `vector[u32]` | The 32-bit unsigned integer type | +| `vector[u64]` | The 64-bit unsigned integer type | +| `vector[i8]` | The 8-bit signed integer type | +| `vector[i16]` | The 16-bit signed integer type | +| `vector[i32]` | The 32-bit signed integer type | +| `vector[i64]` | The 64-bit signed integer type | +| `vector[f32]` | The 32-bit floating point type | +| `vector[f64]` | The 64-bit floating point type | +| `vector[none]` | The any type | + +正如我们在 [Hello, world](./getting-started.md#hello-world-example) 的例子中看到的那样,如果我们想把它作为 SQL UDF 使用,我们可以为协处理器定义返回向量类型。否则,我们可以忽略返回向量类型的声明: + +```python +@coprocessor(returns=['msg']) +def hello() -> vector[str]: + return "hello, GreptimeDB" +``` + +协处理器引擎会根据结果推断出返回向量的类型。但是如果没有声明,除非通过 HTTP API,不然就不能在 SQL 中调用它。 + +### 构建一个向量 + +之前已经展示了在[查询数据](./query-data.md)中通过执行 `@coprocessor` 中的 `sql` 属性从查询结果中提取向量的例子。 + +我们可以从字面意义上创建一个向量: + +```python +@copr(returns=["value"]) +def answer() -> vector[i64]: + return 42 +``` + +结果 `42` 将被包装成 `vector[i64]` 的一个元素的向量。 + +```sql +mysql> select answer(); ++----------+ +| answer() | ++----------+ +| 42 | ++----------+ +1 row in set (0.01 sec) +``` + +我们可以从一个 Python 列表中创建一个向量: + +```python +from greptime import vector + +@copr(returns=["value"]) +def answer() -> vector[i64]: + return vector([42, 43, 44]) +``` + +`greptime` 是一个内置模块,请参考 [API](./api.md) 文档。 + +```sql +mysql> select answer(); ++----------+ +| answer() | ++----------+ +| 42 | +| 43 | +| 44 | ++----------+ +3 rows in set (0.02 sec) +``` + +事实上,`vector` 函数可以从 Python 的任何可迭代对象中创建一个向量。但是它要求所有的元素类型必须相同,而且它选择第一个元素的类型作为它的向量类型。 + +### 向量操作 + +向量支持很多操作: + +1. 支持基本的算术运算,包括 `+`、`-`、`*`、`/`。 +2. 支持基本的逻辑运算,包括 `&`, `|`, `~`。 +3. 也支持基本的比较操作,包括 `>`, `<`, `>=`, `<=`, `==`, `!=`。 + +> 注意:这里我们覆盖了 bitwise 和 `&`,bitwise 或 `|`,bitwise 不是 `~` 的逻辑运算符,因为 Python 不支持逻辑运算符的覆盖 (不能覆盖 `and` `or` `not`)。 +> [PEP335](https://peps.python.org/pep-0335/) 提出了一个建议,最终被拒绝。但是位操作符的优先级比比较操作符高,所以记得使用一对小括号来确保结果是想要的。 +> 即如果想过滤一个在 0 和 100 之间的向量,应该使用 `(vector[i32] >= 0) & (vector[i32] <= 100)` 而不是 `vector[i32] >= 0 & vector[i32] <= 100`。后者将被评估为 `vector[i32] >= (0 & vector[i32]) <= 100`。 + +例如,可以将两个向量相加: + +```python +@copr(args=["n1", "n2"], + returns=["value"], + sql="select number as n1,number as n2 from numbers limit 5") +def add_vectors(n1, n2) -> vector[i32]: + return n1 + n2 +``` + +或者用 Numpy 的方式对一个 bool 数组做比较: + +```python +from greptime import vector + +@copr(returns=["value"]) +def compare() -> vector[bool]: + # This returns a vector([False, False, True]) + return vector([1.0, 2.0, 3.0]) > 2.0 +``` + +并使用 bool 数组的索引: + +```python +from greptime import vector + +@copr(returns=["value"]) +def boolean_array() -> vector[f64]: + v = vector([1.0, 2.0, 3.0]) + # This returns a vector([2.0]) + return v[(v > 1) & (v< 3)] +``` + +也支持两个向量之间的比较: + +```python +from greptime import vector + +@copr(returns=["value"]) +def compare_vectors() -> vector[bool]: + # This returns a vector([False, False, True]) + return vector([1.0, 2.0, 3.0]) > vector([1.0, 2.0, 2.0]) +``` + +使用一个有索引的 bool 数组从一个向量中选择元素: + +```python +from greptime import vector + +@copr(returns=["value"]) +def select_elements() -> (vector[f64]): + a = vector([1.0, 2.0, 3.0]) + # This returns a vector([2.0, 3.0]) + return a[a>=2.0] +``` + +当然,我们可以使用列表理解法来构造一个新的向量: + +```python +from greptime import vector + +@copr(returns=["value"]) +def list_comprehension() -> (vector[f64]): + a = vector([1.0, 2.0, 3.0]) + # This returns a vector([3.0, 4.0]) + return [x+1 for x in a if a >= 2.0] +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/define-function.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/define-function.md new file mode 100644 index 0000000000..9096d42a05 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/define-function.md @@ -0,0 +1,270 @@ +# 定义函数 + +## 协处理器注释 + +`@coprocessor` 注释指定一个 python 函数作为 GreptimeDB 的协处理器,并为其设置一些属性。 + +该引擎允许一个且仅有一个用 `@coprocessor` 注释的函数,不能在一个脚本中拥有一个以上的协处理器。 + +| Parameter | Description | Example | +| --- | --- | --- | +| `sql` | Optional. The SQL statement that the coprocessor function will query data from the database and assign them to input `args`. | `@copr(sql="select * from cpu", ..)` | +| `args` | Optional. The argument names that the coprocessor function will be taken as input, which are the columns in query results by `sql`. | `@copr(args=["cpu", "mem"], ..)` | +| `returns` | The column names that the coprocessor function will return. The Coprocessor Engine uses it to generate the output schema. | `@copr(returns=["add", "sub", "mul", "div"], ..)` | +| `backend` | Optional. The coprocessor function will run on available engines like `rspy` and `pyo3`, which are associated with `RustPython` Backend and `CPython` Backend respectively. The default engine is set to `rspy`. | `@copr(backend="rspy", ..)` | + +`sql` 和 `args` 都是可选的;它们必须都可用,或都不可用,并通常在后查询处理中被使用,详情请阅读下文。 + +`returns` 是每个 coprocessor 都需要的,因为输出模式必然存在。 + + 因为 `RustPython` 不能支持 C 语言 API,当尝试使用 `pyo3` 后端来使用只支持 C 语言 API 的第三方 python 库时,例如 `numpy`,`pandas` 等,`backend` 则是必要的。 + +## 协处理器函数的输入 + +该协处理器也接受之前已经看到的参数: + +```python +@coprocessor(args=["number"], sql="select number from numbers limit 20", returns=["value"]) +def normalize(v) -> vector[i64]: + return [normalize0(x) for x in v] +``` + +参数 `v` 是执行 `sql` 返回的查询结果中的 `number` 列(由 `args` 属性指定)。 + +当然,也可以有多个参数: + +```python +@coprocessor(args=["number", "number", "number"], + sql="select number from numbers limit 5", + returns=["value"]) +def normalize(n1, n2, n3) -> vector[i64]: + # returns [0,1,8,27,64] + return n1 * n2 * n3 +``` + +除了 `args`,还可以向协处理器传递用户定义的参数: + +```python +@coprocessor(returns=['value']) +def add(**params) -> vector[i64]: + a = params['a'] + b = params['b'] + return int(a) + int(b) +``` + +然后从 HTTP API 传递 `a` 和 `b`: + +```sh +curl -XPOST \ + "http://localhost:4000/v1/run-script?name=add&db=public&a=42&b=99" +``` + +```json +{ + "code": 0, + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "value", + "data_type": "Int64" + } + ] + }, + "rows": [ + [ + 141 + ] + ] + } + } + ], + "execution_time_ms": 0 +} +``` + +将 `a=42&b=99` 作为查询参数传入 HTTP API,返回结果 `141`。 + +用户定义的参数必须由协处理器中的 `**kwargs` 来完成,其类型都是字符串。可以传递任何想要的东西,如在协处理器中运行的 SQL。 + +## 协处理器函数的输出 + +正如前面的例子所展示的那样,协处理器函数的输出必须是向量。 + +We can return multi vectors: + +```python +from greptime import vector + +@coprocessor(returns=["a", "b", "c"]) +def return_vectors() -> (vector[i64], vector[str], vector[f64]): + a = vector([1, 2, 3]) + b = vector(["a", "b", "c"]) + c = vector([42.0, 43.0, 44.0]) + return a, b, c +``` + +函数 `return_vectors` 的返回类型是 `(vector[i64], vector[str], vector[f64])`。 + +但必须确保所有这些由函数返回的向量具有相同的长度,因为当它们被转换为行时,每一行必须呈现所有的列值。 + +当然,可以返回字面值,它们也会被转化为向量: + +```python +from greptime import vector + +@coprocessor(returns=["a", "b", "c"]) +def return_vectors() -> (vector[i64], vector[str], vector[i64]): + a = 1 + b = "Hello, GreptimeDB!" + c = 42 + return a, b, c +``` + +## HTTP API + +`/scripts` 提交一个 Python 脚本到 GreptimeDB。 + +保存一个 Python 脚本,如 `test.py`: + +```python +@coprocessor(args = ["number"], + returns = [ "number" ], + sql = "select number from numbers limit 5") +def square(number) -> vector[i64]: + return number * 2 +``` + +将其提交到数据库: + +```shell +curl --data-binary @test.py -XPOST \ + "http://localhost:4000/v1/scripts?db=default&name=square" +``` + +```json +{"code":0} +``` + +Python 脚本被插入到 `scripts` 表中并被自动编译: + +```shell +curl -G http://localhost:4000/v1/sql --data-urlencode "sql=select * from scripts" +``` + +```json +{ + "code": 0, + "output": [{ + "records": { + "schema": { + "column_schemas": [ + { + "name": "schema", + "data_type": "String" + }, + { + "name": "name", + "data_type": "String" + }, + { + "name": "script", + "data_type": "String" + }, + { + "name": "engine", + "data_type": "String" + }, + { + "name": "timestamp", + "data_type": "TimestampMillisecond" + }, + { + "name": "gmt_created", + "data_type": "TimestampMillisecond" + }, + { + "name": "gmt_modified", + "data_type": "TimestampMillisecond" + } + ] + }, + "rows": [ + [ + "default", + "square", + "@coprocessor(args = [\"number\"],\n returns = [ \"number\" ],\n sql = \"select number from numbers\")\ndef square(number):\n return number * 2\n", + "python", + 0, + 1676032587204, + 1676032587204 + ] + ] + } + }], + "execution_time_ms": 4 +} +``` + +也可以通过 `/run-script` 执行脚本: + +```shell +curl -XPOST -G "http://localhost:4000/v1/run-script?db=default&name=square" +``` + +```json +{ + "code": 0, + "output": [{ + "records": { + "schema": { + "column_schemas": [ + { + "name": "number", + "data_type": "Float64" + } + ] + }, + "rows": [ + [ + 0 + ], + [ + 2 + ], + [ + 4 + ], + [ + 6 + ], + [ + 8 + ] + ] + } + }], + "execution_time_ms": 8 +} +``` + +### Python 脚本的参数和结果 + +`/scripts` 接受指定数据库的查询参数 `db`,以及命名脚本的 `name`。`/scripts` 处理 POST 方法主体来作为脚本文件内容。 + +`/run-script` 通过 `db` 和 `name` 运行编译好的脚本,然后返回输出,这与 `/sql` API 中的查询结果相同。 + +`/run-script` 也接收其他查询参数,作为传递到协处理器的用户参数,参考[输入和输出](#协处理器函数的输入)。 + + +## 在 GreptimeDB 控制台中编辑脚本 + +[GreptimeDB 控制台](/getting-started/installation/greptimedb-dashboard.md) 提供了编辑器供用户方便地编辑脚本。 + +在启动 GreptimeDB 后,你可以通过 URL `http://localhost:4000/dashboard` 访问控制台。 +点击左侧边栏的 `Scripts` 进入脚本列表页。 +你可以创建一个新的脚本,编辑一个已有的脚本,或者从控制台运行一个脚本。 + +![dashboard-scripts](/db-dashboard-scripts.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/getting-started.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/getting-started.md new file mode 100644 index 0000000000..d6993002da --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/getting-started.md @@ -0,0 +1,193 @@ +# 入门指南 + +## 安装 + +### 创建 Python 环境 + +如果您正在使用 Greptime 的 Docker 镜像,那么它已经设置好了脚本功能,您可以跳过这一步。 + +如果您希望使用带有 pyo3 功能的 Greptime 二进制文件,首先需要知道您的 Greptime 二进制文件所需的 Python 版本。您可以通过运行 `ldd greptime | grep 'libpython'`(或在 Mac 上运行 `otool -L greptime|grep Python.framework`)来检查。然后安装相应的 Python 版本(例如,`libpython3.10.so` 需要 Python 3.10)。 + +使用 Conda 创建一个 Python3 环境。Conda 是管理 Python 环境的强大工具,请参阅[官方文档](https://docs.conda.io/en/latest/miniconda.html)以获取更多信息。 + +```shell +conda create --name Greptime python=<上一步中特定的Python版本,例如3.10> +conda activate Greptime +``` + +您可能需要为您的 Python 共享库设置正确的 `LD_LIBRARY_PATH`,例如,对于 Conda 环境,您需要将 `LD_LIBRARY_PATH`(或`DYLD_LIBRARY_PATH`)设置为 `$CONDA_PREFIX/lib`。您可以通过运行`ls $CONDA_PREFIX/lib | grep 'libpython'` 来检查该路径是否包含正确的 Python 共享库,并确认版本是否正确。 + +### 安装 GreptimeDB + +请参考 [安装 GreptimeDB](/getting-started/installation/overview.md)。 + +## Hello world 实例 + +让我们从 hello world 实例开始入手: + +```python +@coprocessor(returns=['msg']) +def hello() -> vector[str]: + return "Hello, GreptimeDB" +``` + +将其保存为 `hello.py`,然后通过 [HTTP API](./define-function.md#http-api) 发布: + +### 提交 Python 脚本到 GreptimeDB + +```sh +curl --data-binary "@hello.py" -XPOST "http://localhost:4000/v1/scripts?name=hello&db=public" +``` + +然后在 SQL 中调用: + +```sql +select hello(); +``` + +```sql ++-------------------+ +| hello() | ++-------------------+ +| Hello, GreptimeDB | ++-------------------+ +1 row in set (1.77 sec) +``` + +或者通过 [HTTP API](./define-function.md#http-api) 进行调用: + +```sh +curl -XPOST "http://localhost:4000/v1/run-script?name=hello&db=public" +``` + +```json +{ + "code": 0, + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "msg", + "data_type": "String" + } + ] + }, + "rows": [["Hello, GreptimeDB"]] + } + } + ], + "execution_time_ms": 1917 +} +``` + +函数 `hello` 带有 `@coprocessor` 注解。 + +`@coprocessor` 中的 `returns` 指定了返回的列名,以及整体的返回格式: + +```json + "schema": { + "column_schemas": [ + { + "name": "msg", + "data_type": "String" + } + ] + } +``` + +参数列表后面的 `-> vector[str]` 指定了函数的返回类型,都是具有具体类型的 vector。返回类型是生成 coprocessor 函数的输出所必需的。 + +`hello` 的函数主体返回一个字面字符串 `"Hello, GreptimeDB"`。Coprocessor 引擎将把它转换成一个常量字符串的 vector 并返回它。 + +总的来说一个协处理器包含三个主要部分: + +- `@coprocessor` 注解 +- 函数的输入和输出 +- 函数主体 + +我们可以像 SQL UDF(User Defined Function) 一样在 SQL 中调用协处理器,或者通过 HTTP API 调用。 + +## SQL 实例 + +将复杂的分析用的 Python 代码(比如下面这个通过 cpu/mem/disk 使用率来确定负载状态的代码)保存到一个文件中(这里命名为 `system_status.py`): + +```python +@coprocessor(args=["host", "idc", "cpu_util", "memory_util", "disk_util"], + returns = ["host", "idc", "status"], + sql = "SELECT * FROM system_metrics") +def system_status(hosts, idcs, cpus, memories, disks)\ + -> (vector[str], vector[str], vector[str]): + statuses = [] + for host, cpu, memory, disk in zip(hosts, cpus, memories, disks): + if cpu > 80 or memory > 80 or disk > 80: + statuses.append("red") + continue + + status = cpu * 0.4 + memory * 0.4 + disk * 0.2 + + if status > 80: + statuses.append("red") + elif status > 50: + statuses.append("yello") + else: + statuses.append("green") + + + return hosts, idcs, statuses + +``` + +上述代码根据 cpu/memory/disk 的使用情况来评估主机状态。参数来自于查询 `system_metrics` 的数据,由 `@coprocessor` 注释中的参数 `sql` 指定(这里是=`"SELECT * FROM system_metrics"`)。查询结果被分配给 `args=[...]` 中的每个位置参数,然后函数返回三个变量,这些变量被转换为三个列 `returns = ["host", "idc", "status"]`。 + +### 提交 Python 脚本到 GreptimeDB + +可以用 `system_status` 将文件提交给 GreptimeDB,这样以后就可以用这个名称来引用并执行它: + +```shell +curl --data-binary "@system_status.py" \ + -XPOST "http://localhost:4000/v1/scripts?name=system_status&db=public" +``` + +运行该脚本: + +```shell +curl -XPOST \ + "http://localhost:4000/v1/run-script?name=system_status&db=public" +``` + +以 `json` 格式获取结果: + +```json +{ + "code": 0, + "output": { + "records": { + "schema": { + "column_schemas": [ + { + "name": "host", + "data_type": "String" + }, + { + "name": "idc", + "data_type": "String" + }, + { + "name": "status", + "data_type": "String" + } + ] + }, + "rows": [ + ["host1", "idc_a", "green"], + ["host1", "idc_b", "yello"], + ["host2", "idc_a", "red"] + ] + } + } +} +``` + +更多有关 Python 协处理器的信息,请参考[定义函数](./define-function.md)文档。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/overview.md new file mode 100644 index 0000000000..6fffbc0128 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/overview.md @@ -0,0 +1,31 @@ +# 概述 + +GreptimeDB 支持在数据库内运行 Python 脚本,如果业务逻辑太复杂,无法通过 SQL 表达,则可以使用 Python。Python 目前在数据科学和人工智能领域被广泛使用,为了避免花费大量的时间和精力来传输和转换数据,我们提供了在数据库中执行 Python 脚本的能力。 + +我们认为 GreptimeDB 中的 Python 脚本是传统 RDMS 中存储过程的完美替代品,同时用户也可以创建 SQL UDFs(用户定义的函数)。 + +- [入门指南](./getting-started.md) +- [定义函数](./define-function.md) +- [查询数据](./query-data.md) +- [写入数据](./write-data.md) +- [数据类型](./data-types.md) +- [API](./api.md) + +所有的例子都可以在 [python-coprocessor-examples](https://github.com/GreptimeTeam/python-coprocessor-examples) 中找到。 + +# 注意事项 + +Python 脚本目前正处于实验阶段,API 可能会发生一些变化。 + +用户可以下载支持 PyO3 的 [pre-built binaries](https://greptime.cn/download),其文件名后缀为 `pyo3`。也可以通过下载没有 `pyo3` 后缀的 binary 文件直接使用 RustPython,它不需要额外的设置。 + +如果有库的链接问题,那么需要检查是否设置了正确的 Python 共享库,这可能会有点难度。一般来说,只需要安装 `python-dev` 包(在大多数基于 Debian 的系统上)。然而,如果用户使用 Homebrew 在 macOS 上安装 Python,则必须创建一个适当的链接到 `Library/Frameworks/Python.framework`。 + +推荐利用 `Conda` 来管理 Python 环境。首先,用下载的 binary 文件所要求的相同版本的 Python 创建一个 Python 环境。或者,可以使用一个 docker 容器,在其中执行 `greptime` binary。 + +另一个可行方案,但并非推荐方案:手动安装所需的 Python 版本,并将 `LD_LIBRARY_PATH`环境变量设置为包含 `libpython.so` 文件的目录。`` 的版本号根据所使用的 Python 的版本而不同。 + +两个 Python 脚本的后端: + +1. RustPython 解释器:无需安装任何 Python 库就可以支持,但它没有 CPython 后端那么快。名称中没有 `pyo3` 的 Release Binary 使用 RustPython Interpreter。虽然仍然可以在 RustPython 解释器中使用 Python 语法,但不能使用任何第三方的库。 +2. CPython 解释器:这是最常用的 Python 版本。它允许使用各种第三方库,但需要安装正确的 Python 共享库。任何名称中带有 `pyo3` 的 Release Binary 都使用 CPython Interpreter。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/query-data.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/query-data.md new file mode 100644 index 0000000000..f645c3ba75 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/query-data.md @@ -0,0 +1,117 @@ +# 查询数据 + +我们在 Python Corpcessor 中提供了两种方法来轻松查询 GreptimeDB 的数据: + +* SQL:运行一个 SQL 字符串并返回查询结果。 +* DataFrame API:描述和执行查询的内置模块,类似于 [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) 或 [Spark DataFrame](https://spark.apache.org/docs/latest/sql-programming-guide.html)。 + +## SQL + +使用 `greptime` 模块的 `query` 方法来检索一个查询引擎,然后调用 `sql` 函数来执行一个 SQL 字符串,比如: + +```python +@copr(returns=["value"]) +def query_numbers()->vector[f64]: + from greptime import query + return query().sql("select number from numbers limit 10")[0] +``` + +通过 SQL 客户端调用它: + +```sql +SQL > select query_numbers(); ++-----------------+ +| query_numbers() | ++-----------------+ +| 0 | +| 1 | +| 2 | +| 3 | +| 4 | +| 5 | +| 6 | +| 7 | +| 8 | +| 9 | ++-----------------+ +10 rows in set (1.78 sec) +``` + + `sql` 函数返回一个列的列表,每个列是一个值的向量。 + +在上面的例子中,`sql("select number from numbers limit 10")` 返回一个向量的列表。并使用 `[0]` 检索第一列向量,这就是 `select` SQL 中的 `number` 列。 + +## 查询后处理 + +在查询结果返回给用户之前进行处理时,协处理器就能派上用场。 + +例如,我们想对数值进行标准化处理: + +* 如果错过了,返回 0,而不是 null 或 `NaN`, +* 如果它大于 5,返回 5, +* 如果它小于 0,则返回 0。 + +然后我们可以创建 `normalize.py`: + +```python +import math + +def normalize0(x): + if x is None or math.isnan(x): + return 0 + elif x > 5: + return 5 + elif x < 0: + return 0 + else: + return x + +@coprocessor(args=["number"], sql="select number from numbers limit 10", returns=["value"]) +def normalize(v) -> vector[i64]: + return [normalize0(x) for x in v] +``` + +`normalize0` 函数的行为如上所述。而 `normalize` 函数是协处理器的入口点: + +* 执行 SQL 的 `select value from demo`, +* 提取查询结果中的列 `value` 并将其作为 `normalize` 函数的参数,然后调用该函数。 +* 在函数中,使用列表理解来处理 `value` 向量,通过 `normalize0` 函数处理每个元素, +* 返回以 `value` 列命名的结果。 + +`->vector[i64]` 部分指定了用于生成输出模式的返回列类型。 + +这个例子还展示了如何导入 stdlib 和定义其他函数(`normalize0`)进行调用。 +`normalize` 协处理器将在流中被调用,查询结果可能包含多个批次,引擎将对每个批次调用协处理器。而且应该记住,从查询结果中提取的列都是向量,我们将在下一章中介绍向量。 + +提交并运行这个脚本将产生输出: + +```json +{ + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "value", + "data_type": "Int64" + } + ] + }, + "rows": [ + [0], + [1], + [2], + [3], + [4], + [5], + [5], + [5], + [5], + [5] + ] + } + } + ] +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/write-data.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/write-data.md new file mode 100644 index 0000000000..cf9b2e2d4c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/python-scripts/write-data.md @@ -0,0 +1,38 @@ +# 写入数据 + +## 插入新数据 + +用户也可以通过 `sql` API 插入数据 + +```python +from greptime import query +@copr(returns=["affected_rows"]) +def insert() -> vector[i32]: + return query().sql("insert into monitor(host, ts, cpu, memory) values('localhost',1667446807000, 15.3, 66.6)") +``` + +```json +{ + "code": 0, + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "rows", + "data_type": "Int32" + } + ] + }, + "rows": [ + [ + 1 + ] + ] + } + } + ], + "execution_time_ms": 4 +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/cte.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/cte.md new file mode 100644 index 0000000000..dfd084ea7e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/cte.md @@ -0,0 +1,242 @@ +--- +keywords: [公共表表达式, CTE, SQL 查询, 临时结果集, 简化查询, 可读性, 可重用性] +description: 介绍公共表表达式(CTE)的基本概念和使用方法。 +--- + +# 公共表表达式(CTE) + +CTE 与 [视图](./view.md) 类似,它们帮助您简化查询的复杂性,将长而复杂的 SQL 语句分解,并提高可读性和可重用性。 + +您已经在 [快速开始](/getting-started/quick-start.md#指标和日志的关联查询) 文档中阅读了一个 CTE 的例子。 + +## 什么是公共表表达式(CTE)? + +公共表表达式 (CTE) 是可以在 `SELECT`、`INSERT`、`UPDATE` 或 `DELETE` 语句中引用的临时结果集。CTE 有助于将复杂的查询分解成更可读的部分,并且可以在同一个查询中多次引用。 + +## CTE 的基本语法 + +CTE 通常使用 `WITH` 关键字定义。基本语法如下: + +```sql +WITH cte_name [(column1, column2, ...)] AS ( + QUERY +) +SELECT ... +FROM cte_name; +``` + +## 示例解释 + +接下来,我们将通过一个完整的示例来演示如何使用 CTE,包括数据准备、CTE 创建和使用。 + +### 步骤 1:创建示例数据 + +假设我们有以下两个表: + +- `grpc_latencies`:包含 gRPC 请求延迟数据。 +- `app_logs`:包含应用程序日志信息。 + +```sql +CREATE TABLE grpc_latencies ( + ts TIMESTAMP TIME INDEX, + host VARCHAR(255), + latency FLOAT, + PRIMARY KEY(host), +); + +INSERT INTO grpc_latencies VALUES +('2023-10-01 10:00:00', 'host1', 120), +('2023-10-01 10:00:00', 'host2', 150), +('2023-10-01 10:00:05', 'host1', 130); + +CREATE TABLE app_logs ( + ts TIMESTAMP TIME INDEX, + host VARCHAR(255), + `log` TEXT, + log_level VARCHAR(50), + PRIMARY KEY(host, log_level), +); + +INSERT INTO app_logs VALUES +('2023-10-01 10:00:00', 'host1', 'Error on service', 'ERROR'), +('2023-10-01 10:00:00', 'host2', 'All services OK', 'INFO'), +('2023-10-01 10:00:05', 'host1', 'Error connecting to DB', 'ERROR'); +``` + +### 步骤 2:定义和使用 CTE + +我们将创建两个 CTE 来分别计算第 95 百分位延迟和错误日志的数量。 + +```sql +WITH +metrics AS ( + SELECT + ts, + host, + approx_percentile_cont(0.95) WITHIN GROUP (ORDER BY latency) RANGE '5s' AS p95_latency + FROM + grpc_latencies + ALIGN '5s' FILL PREV +), +logs AS ( + SELECT + ts, + host, + COUNT(*) RANGE '5s' AS num_errors + FROM + app_logs + WHERE + log_level = 'ERROR' + ALIGN '5s' BY (host) +) +SELECT + metrics.ts, + metrics.host, + metrics.p95_latency, + COALESCE(logs.num_errors, 0) AS num_errors +FROM + metrics +LEFT JOIN logs ON metrics.host = logs.host AND metrics.ts = logs.ts +ORDER BY + metrics.ts; +``` + +输出: + +```sql ++---------------------+-------+-------------+------------+ +| ts | host | p95_latency | num_errors | ++---------------------+-------+-------------+------------+ +| 2023-10-01 10:00:00 | host2 | 150 | 0 | +| 2023-10-01 10:00:00 | host1 | 120 | 1 | +| 2023-10-01 10:00:05 | host1 | 130 | 1 | ++---------------------+-------+-------------+------------+ +``` + +### 详细说明 + +1. **定义 CTEs**: + - `metrics`: + ```sql + metrics AS ( + SELECT + ts, + host, + approx_percentile_cont(0.95) WITHIN GROUP (ORDER BY latency) RANGE '5s' AS p95_latency + FROM + grpc_latencies + ALIGN '5s' FILL PREV + ), + ``` + 这里我们使用[范围查询](/user-guide/query-data/sql.md#按时间窗口聚合数据)计算每个 `host` 在每个 5 秒时间窗口内的第 95 百分位延迟。 + + - `logs`: + ```sql + logs AS ( + SELECT + ts, + host, + COUNT(*) RANGE '5s' AS num_errors + FROM + app_logs + WHERE + log_level = 'ERROR' + ALIGN '5s' BY (host) + ) + ``` + 同样地,我们计算每个 `host` 在每个 5 秒时间窗口内的错误日志数量。 + +2. **使用 CTEs**: + 在最终的查询部分: + ```sql + SELECT + metrics.ts, + metrics.host, + metrics.p95_latency, + COALESCE(logs.num_errors, 0) AS num_errors + FROM + metrics + LEFT JOIN logs ON metrics.host = logs.host AND metrics.ts = logs.ts + ORDER BY + metrics.ts; + ``` + 我们对两个 CTE 结果集进行左连接,以获得最终的综合分析结果。 + +## 在 CTE 中使用 TQL + +GreptimeDB 支持在 CTE 中使用 [TQL](/reference/sql/tql.md)(Telemetry 查询语言),让你可以在 SQL 工作流中使用 PromQL 风格的查询。 + +### 基本语法 + +```sql +WITH cte_name AS ( + TQL EVAL (start, end, step) promql_expression +) +SELECT * FROM cte_name; +``` + +### 关键点 + +1. **列名**: + - 时间索引列名取决于表结构(例如,自定义表使用 `ts`,Prometheus 远程写入的默认使用 `greptime_timestamp`) + - 值的列名取决于 PromQL 表达式,可能无法预测,因此更推荐使用 TQL 中的 `AS` 进行值别名以确保可预测的值列名:`TQL EVAL (...) expression AS my_value` + - **重要**:避免在 CTE 定义中使用列别名(如 `WITH cte_name (ts, val) AS (...)`),因为 TQL EVAL 结果的列数量和顺序可能变化,特别是在 Prometheus 场景中标签可能动态添加或删除 + +2. **支持的命令**:CTE 中仅支持 `TQL EVAL`。不能在 CTE 中使用 `TQL ANALYZE` 和 `TQL EXPLAIN`。 + +3. **回溯参数**:可选的第四个参数控制回溯持续时间(默认:5 分钟)。 + +### 示例 + +#### 使用值别名的基本 TQL CTE + +```sql +-- 使用 TQL 中的 AS 子句为值列命名 +WITH metrics_data AS ( + TQL EVAL (0, 40, '10s') metric AS value +) +SELECT * FROM metrics_data WHERE value > 5; +``` + +#### 带 PromQL 函数的 TQL + +```sql +WITH request_rate AS ( + TQL EVAL (0, 40, '10s') rate(metric[20s]) AS rate_per_sec +) +SELECT * FROM request_rate; +``` + +#### 组合多个 TQL CTE + +```sql +WITH + current AS ( + TQL EVAL (0, 40, '10s') metric AS current_value + ), + rate AS ( + TQL EVAL (0, 40, '10s') rate(metric[20s]) AS rate_value + ) +SELECT + c.*, + r.rate_value +FROM current c +JOIN rate r ON c.ts = r.ts; -- 注意:时间列名取决于您的表 +``` + +#### 混合 CTE(TQL + SQL) + +```sql +WITH + tql_data AS ( + TQL EVAL (0, 40, '10s') metric AS val + ), + filtered AS ( + SELECT * FROM tql_data WHERE val > 5 + ) +SELECT count(*) FROM filtered; +``` + +## 总结 + +通过 CTE,您可以将复杂的 SQL 查询分解为更易于管理和理解的部分。在本示例中,我们分别创建了两个 CTE 来计算第 95 百分位延迟和错误日志的数量,然后将它们合并到最终查询中进行分析。CTE 中的 TQL 支持通过将 PromQL 风格的查询与 SQL 处理无缝集成来扩展这种能力。阅读更多关于 [WITH](/reference/sql/with.md) 和 [TQL](/reference/sql/tql.md) 的内容。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/jaeger.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/jaeger.md new file mode 100644 index 0000000000..e587816482 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/jaeger.md @@ -0,0 +1,57 @@ +--- +keywords: [Jaeger, traces, query, experimental, HTTP endpoint] +description: 介绍如何使用 Jaeger 查询 GreptimeDB 中的 traces 数据。 +--- + +# Jaeger 查询(实验功能) + +:::warning + +Jaeger 查询接口目前仍处于实验阶段,在未来的版本中可能会有所调整。 + +::: + +GreptimeDB 目前支持以下 [Jaeger](https://www.jaegertracing.io/) 查询接口: + +- `/api/services`: 获取所有 Service。 +- `/api/operations?service={service}`: 获取指定 Service 的所有 Operations。 +- `/api/services/{service}/operations`: 获取指定 Service 的所有 Operations。 +- `/api/traces`: 根据查询参数获取 traces 数据。 + +你可以使用 Grafana 的 [Jaeger 插件](https://grafana.com/docs/grafana/latest/datasources/jaeger/)(推荐) 或者 [Jaeger UI](https://github.com/jaegertracing/jaeger-ui) 来查询 GreptimeDB 中的 traces 数据。当你在使用 Jaeger UI 的时候,可将 `packages/jaeger-ui/vite.config.mts` 的 `proxyConfig` 配置为 GreptimeDB 的地址,比如: + +```ts +const proxyConfig = { + target: 'http://localhost:4000/v1/jaeger', + secure: false, + changeOrigin: true, + ws: true, + xfwd: true, +}; +``` + +目前 GreptimeDB 对 Jaeger 协议接口在 `/v1/jaeger` 路径下。 + +## 快速开始 + +我们将以 Grafana 中使用 Jaeger 插件为例,介绍如何查询 GreptimeDB 中的 traces 数据。在开始之前,请确保你已经正常启动了 GreptimeDB。 + +### 启动应用生成 traces 数据并写入 GreptimeDB + +你可以参考 [OpenTelemetry 官方文档](https://opentelemetry.io/docs/languages/) 来选择任意你熟悉的编程语言来生成 traces 并将其写入到 GreptimeDB 中。你也可以参考[配置 OpenTelemetry Collector](/user-guide/traces/read-write.md#opentelemetry-collector) 文档。 + +### 配置 Jaeger 插件 + +1. 打开 Grafana,添加 Jaeger 数据源: + + ![添加 Jaeger 数据源](/add-jaeger-data-source.jpg) + +2. 根据实际情况,填写 Jaeger 地址,然后 **Save and Test** 即可。比如: + + ``` + http://localhost:4000/v1/jaeger + ``` + +3. 使用 Jaeger Explore 来查看数据: + + ![Jaeger Explore](/jaeger-explore.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/log-query.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/log-query.md new file mode 100644 index 0000000000..0303362040 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/log-query.md @@ -0,0 +1,105 @@ +--- +keywords: [日志查询, 日志, 搜索, 实验功能, HTTP 接口] +description: GreptimeDB 实验性日志查询接口的说明文档,该接口提供了专门用于搜索和处理日志数据的 HTTP 服务。 +--- + +# 日志查询(实验功能) + +:::warning +日志查询接口目前仍处于实验阶段,在未来的版本中可能会有所调整。 +::: + +GreptimeDB 提供了一个专门用于查询日志数据的 HTTP 接口。通过这个功能,你可以使用简单的查询界面来搜索和处理日志记录。这是对 GreptimeDB 现有功能(如 SQL 查询和 Flow 计算)的补充。你仍然可以像之前一样使用已有的工具和工作流程来查询日志数据。 + +## 接口地址 + +```http +POST /v1/logs +``` + +## 请求头 +- [认证](/user-guide/protocols/http.md#authentication) +- `Content-Type`: `application/json` + +## 请求格式 + +请求体应为 JSON 格式(在实验阶段可能会随补丁版本有所变化)。关于最新的请求格式,请参考[源代码实现](https://github.com/GreptimeTeam/greptimedb/blob/main/src/log-query/src/log_query.rs): + +## 响应格式 + +此接口的响应格式与 SQL 查询接口相同。详情请参阅 [SQL 查询响应格式](/user-guide/protocols/http/#response)。 + +## 使用限制 + +- 最大结果数量:1000 条记录 +- 仅支持包含时间戳和字符串列的表格 + +## 使用示例 + +以下示例展示了如何使用日志查询接口来查询日志数据(请注意,在实验性阶段这个例子可能会失效): + +```shell +curl -X "POST" "http://localhost:4000/v1/logs" \ + -H "Authorization: Basic {{authentication}}" \ + -H "Content-Type: application/json" \ + -d $' + { + "table": { + "catalog_name": "greptime", + "schema_name": "public", + "table_name": "my_logs" + }, + "time_filter": { + "start": "2025-01-23" + }, + "limit": { + "fetch": 1 + }, + "columns": [ + "message" + ], + "filters": [ + { + "column_name": "message", + "filters": [ + { + "Contains": "production" + } + ] + } + ], + "context": "None", + "exprs": [] + } +' +``` + +在这个查询中,我们在 `greptime.public.my_logs` 表中搜索 `message` 字段包含 `production` 的日志记录。我们还设定了时间过滤条件,只获取 `2025-01-23` 当天的日志,并将结果限制为仅返回 1 条记录。 + +响应结果类似于以下内容: + +```json +{ + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "message", + "data_type": "String" + } + ] + }, + "rows": [ + [ + "Everything is in production" + ] + ], + "total_rows": 1 + } + } + ], + "execution_time_ms": 30 +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/overview.md new file mode 100644 index 0000000000..c9d1fed939 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/overview.md @@ -0,0 +1,28 @@ +--- +keywords: [查询语言, SQL, PromQL, 查询库, 外部数据查询, 公共表表达式, 视图] +description: 介绍 GreptimeDB 支持的查询语言和推荐的查询库。 +--- + +# 查询数据 + +## 查询语言 + +- [SQL](./sql.md) +- [PromQL](promql.md) +- [Log Query](./log-query.md) (实验性功能) + +从 v0.9 开始,GreptimeDB 开始支持查询视图和公共表表达式(CTE),用于简化查询语句: + +* [View](./view.md) +* [公共表表达式(CTE)](./cte.md) + +## 推荐的查询库 + +由于 GreptimeDB 使用 SQL 作为主要查询语言,并支持 [MySQL](/user-guide/protocols/mysql.md) 和 [PostgreSQL](/user-guide/protocols/postgresql.md) 协议, +你可以使用支持 MySQL 或 PostgreSQL 的成熟 SQL Driver 来查询数据。 + +有关更多信息,请参考[SQL 工具](/reference/sql-tools.md)文档。 + +## 查询外部数据 + +GreptimeDB 具有查询外部数据文件的能力,更多信息请参考[查询外部数据](./query-external-data.md)文档。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/promql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/promql.md new file mode 100644 index 0000000000..aa4ae287fa --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/promql.md @@ -0,0 +1,289 @@ +--- +keywords: [PromQL, Prometheus 查询语言, HTTP API, SQL 扩展, Grafana, Prometheus 替代品] +description: 介绍 GreptimeDB 对 Prometheus 查询语言(PromQL)的支持,包括 HTTP API 和 SQL 扩展。 +--- + +# Prometheus Query Language + +GreptimeDB 可以作为 Grafana 中 Prometheus 的替代品,因为 GreptimeDB 支持 PromQL(Prometheus Query Language)。GreptimeDB 在 Rust 中重新实现了 PromQL,并通过接口将能力开放,包括 Prometheus 的 HTTP API、GreptimeDB 的 HTTP API 和 SQL 接口。 + +## Prometheus 的 HTTP API + + + + +GreptimeDB 实现了兼容 Prometheus 的一系列 API,通过 `/v1/prometheus` 路径对外提 +供服务: + +- Instant queries `/api/v1/query` +- Range queries `/api/v1/query_range` +- Series `/api/v1/series` +- Label names `/api/v1/labels` +- Label values `/api/v1/label//values` + +这些接口的输入和输出与原生的 Prometheus HTTP API 相同,用户可以把 GreptimeDB 当 +作 Prometheus 的直接替换。例如,在 Grafana 中我们可以设置 +`http://localhost:4000/v1/prometheus/` 作为其 Prometheus 数据源的地址。 + +访问 [Prometheus 文档](https://prometheus.io/docs/prometheus/latest/querying/api) +获得更详细的说明。 + +你可以通过设置 HTTP 请求的 `db` 参数来指定 GreptimeDB 中的数据库名。 + +例如,以下查询将返回 `public` 数据库中 `process_cpu_seconds_total` 指标的 CPU 使用率: + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + --data-urlencode 'query=irate(process_cpu_seconds_total[1h])' \ + --data-urlencode 'start=2024-11-24T00:00:00Z' \ + --data-urlencode 'end=2024-11-25T00:00:00Z' \ + --data-urlencode 'step=1h' \ + 'http://localhost:4000/v1/prometheus/api/v1/query_range?db=public' +``` + +如果你使用启用了身份验证的 GreptimeDB,则需要 Authorization header,请参阅[鉴权](/user-guide/protocols/http.md#鉴权)。 +该 API 的查询字符串参数与原始 [Prometheus API](https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries) 的查询字符串参数相同。 +你需要在 HTTP 的 query param 设置 `db` 参数,或者通过 `--header 'x-greptime-db-name: '` 设置在 HTTP 请求头中。 + +输出格式与 Prometheus API 完全兼容: + +```json +{ + "status": "success", + "data": { + "resultType": "matrix", + "result": [ + { + "metric": { + "job": "node", + "instance": "node_exporter:9100", + "__name__": "process_cpu_seconds_total" + }, + "values": [ + [ + 1732618800, + "0.0022222222222222734" + ], + [ + 1732622400, + "0.0009999999999999788" + ], + [ + 1732626000, + "0.0029999999999997585" + ], + [ + 1732629600, + "0.002222222222222175" + ] + ] + } + ] + } +} +``` + +## SQL + +GreptimeDB 还扩展了 SQL 语法以支持 PromQL。可以用 `TQL`(Time-series Query Language)为关键字开始写入参数和进行查询。该语法如下: + +```sql +TQL [EVAL|EVALUATE] (, , ) +``` + +`` 指定查询开始时间范围,`` 指定查询结束时间。 `` 识别查询步幅。它们均可为无引号数字(表示``和``的 UNIX 时间戳,以及``的秒数持续时间),或带引号的字符串(表示``和``的 RFC3339 时间戳,以及``的字符串格式的持续时间)。 + +例如: + +```sql +TQL EVAL (1676738180, 1676738780, '10s') sum(some_metric) +``` + +你可以在所有支持 SQL 的地方编写上述命令,包括 GreptimeDB HTTP API、SDK、PostgreSQL 和 MySQL 客户端等。 + +## GreptimeDB 的扩展 + +### 指定数值列 + +基于表模型,GreptimeDB 支持在单个表(或在 Prometheus 中称为指标)中查询多个字段。默认情况下,查询将应用于每个值字段 (field)。或者也可以使用特殊的过滤器 `__field__` 来查询特定的字段: + +```promql +metric{__field__="field1"} +``` + +反选或正则表达式也都支持 + +```promql +metric{__field__!="field1"} + +metric{__field__=~"field_1|field_2"} + +metric{__field__!~"field_1|field_2"} +``` + +### 指定数据库 + +不同于 Prometheus,GreptimeDB 包含数据库概念。如果要进行跨数据库的 PromQL 查询, +可以使用 `__database__` 来指定数据库名称。 + +```promql +metric{__database__="mydatabase"} +``` + +注意 `__database__` 仅支持 `=` 匹配。 + +## 局限 + +尽管 GreptimeDB 支持丰富的数据类型,但 PromQL 的实现仍然局限于以下类型: + +- timestamp: `Timestamp` +- tag: `String` +- value: `Double` + +GreptimeDB 目前已实现了大部分(超过 90%)的 PromQL 功能。您可以在下方查看详细的兼容性列表,或者通过此 [issue](https://github.com/GreptimeTeam/greptimedb/issues/1042) 了解我们最新的功能支持情况。 + +选择器引用不存在的列时,其行为与 Prometheus 一致:不报错且选择器会被静默忽略。但若 `__name__` 选择器引用了不存在的指标(或等效形式),GreptimeDB 则会报告错误。 + +支持字符串和浮点数,与 PromQL 的[规则](https://prometheus.io/docs/prometheus/latest/querying/basics/#literals)相同。 + +### 选择器 + +Instant 选择器和 Range 选择器均已支持。需要注意的是,在 Prometheus 和 GreptimeDB 中,指标名称的标签匹配有一个特殊限制:不支持反向匹配(例如 `{__name__!="request_count"}`)。但其他匹配方式,如等值匹配和正则匹配都是完全支持的。 + +时间区间和时间偏移修饰符均已支持,但目前尚未支持 `@` 修饰符。 + +当选择不存在的列时,它们将被视为一个所有值都为 `""` 的列。该行为与 Prometheus 和 VictoriaMetrics 一致。 + +### 时间精度 + +PromQL 的时间戳精度受制于查询语法的限制,最高只支持毫秒级精度的计算。然而,GreptimeDB 支持存储微秒和纳秒等高精度时间。在使用 PromQL 进行计算时,这些高精度时间将被隐式转换为毫秒精度进行计算。 + +### Binary + +- 支持: + | Operator | + | :------- | + | add | + | sub | + | mul | + | div | + | mod | + | eqlc | + | neq | + | gtr | + | lss | + | gte | + | lte | + | power | + | atan2 | + | and | + | or | + | unless | + +- 不支持: + +无 + +### Aggregators + +- 支持: + | Aggregator | Example | + | :----------- | :------------------------------------------- | + | sum | `sum by (foo)(metric)` | + | avg | `avg by (foo)(metric)` | + | min | `min by (foo)(metric)` | + | max | `max by (foo)(metric)` | + | stddev | `stddev by (foo)(metric)` | + | stdvar | `stdvar by (foo)(metric)` | + | topk | `topk(3, rate(instance_cpu_time_ns[5m]))` | + | bottomk | `bottomk(3, rate(instance_cpu_time_ns[5m]))` | + | count_values | `count_values("version", build_version)` | + | count | `count (metric)` | + | quantile | `quantile(0.9, cpu_usage)` | + +- 不支持: + | Aggregator | Progress | + | :--------- | :------- | + | count | TBD | + | grouping | TBD | + +### Instant Functions + +- 支持: + | Function | Example | + | :----------------- | :-------------------------------- | + | abs | `abs(metric)` | + | ceil | `ceil(metric)` | + | exp | `exp(metric)` | + | ln | `ln(metric)` | + | log2 | `log2(metric)` | + | log10 | `log10(metric)` | + | sqrt | `sqrt(metric)` | + | acos | `acos(metric)` | + | asin | `asin(metric)` | + | atan | `atan(metric)` | + | sin | `sin(metric)` | + | cos | `cos(metric)` | + | tan | `tan(metric)` | + | acosh | `acosh(metric)` | + | asinh | `asinh(metric)` | + | atanh | `atanh(metric)` | + | sinh | `sinh(metric)` | + | cosh | `cosh(metric)` | + | scalar | `scalar(metric)` | + | tanh | `tanh(metric)` | + | timestamp | `timestamp()` | + | sort | `sort(http_requests_total)` | + | sort_desc | `sort_desc(http_requests_total)` | + | histogram_quantile | `histogram_quantile(phi, metric)` | + | predicate_linear | `predict_linear(metric, 120)` | + | absent | `absent(nonexistent{job="myjob"})`| + | sgn | `sgn(metric)` | + | pi | `pi()` | + | deg | `deg(metric)` | + | rad | `rad(metric)` | + | floor | `floor(metric)` | + | clamp | `clamp(metric, 0, 12)` | + | clamp_max | `clamp_max(metric, 12)` | + | clamp_min | `clamp_min(metric, 0)` | + +- 不支持: + | Function | Progress | + | :------------------------- | :------- | + | *other multiple input fns* | TBD | + +### Range Functions + +- 支持: + | Function | Example | + | :----------------- | :----------------------------- | + | idelta | `idelta(metric[5m])` | + | \_over_time | `count_over_time(metric[5m])` | + | stddev_over_time | `stddev_over_time(metric[5m])` | + | stdvar_over_time | `stdvar_over_time(metric[5m])` | + | changes | `changes(metric[5m])` | + | delta | `delta(metric[5m])` | + | rate | `rate(metric[5m])` | + | deriv | `deriv(metric[5m])` | + | increase | `increase(metric[5m])` | + | irate | `irate(metric[5m])` | + | reset | `reset(metric[5m])` | + +- 不支持: + +无 + +### Label 及其他函数 + +- 支持: + | Function | Example | + | :------------ | :------------------------------------------------------------------------------------------------ | + | label_join | `label_join(up{job="api-server",src1="a",src2="b",src3="c"}, "foo", ",", "src1", "src2", "src3")` | + | label_replace | `label_replace(up{job="api-server",service="a:c"}, "foo", "$1", "service", "(.*):.*")` | + | sort_by_label | `sort_by_label(metric, "foo", "bar")` | + | sort_by_label_desc | `sort_by_label_desc(metric, "foo", "bar")` | + +- 不支持: + +无 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/query-external-data.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/query-external-data.md new file mode 100644 index 0000000000..f341aa59cd --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/query-external-data.md @@ -0,0 +1,124 @@ +--- +keywords: [外部数据查询, 创建外部表, 查询目录数据, Parquet 文件, CSV 文件, ORC 文件, NDJson 文件] +description: 介绍如何查询外部数据文件,包括创建外部表和查询目录中的数据。 +--- + +# 查询外部数据 + +## 对文件进行查询 + +目前,我们支持 `Parquet`、`CSV`、`ORC` 和 `NDJson` 格式文件的查询。 + +以 [Taxi Zone Lookup Table](https://d37ci6vzurychx.cloudfront.net/misc/taxi+_zone_lookup.csv) 数据为例。 + +```bash +curl "https://d37ci6vzurychx.cloudfront.net/misc/taxi+_zone_lookup.csv" -o /tmp/taxi+_zone_lookup.csv +``` + +创建一个外部表: + +```sql +CREATE EXTERNAL TABLE taxi_zone_lookup with (location='/tmp/taxi+_zone_lookup.csv',format='csv'); +``` + +检查外部表的组织和结构: + +```sql +DESC TABLE taxi_zone_lookup; +``` + +```sql ++--------------------+----------------------+------+------+--------------------------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+----------------------+------+------+--------------------------+---------------+ +| LocationID | Int64 | | YES | | FIELD | +| Borough | String | | YES | | FIELD | +| Zone | String | | YES | | FIELD | +| service_zone | String | | YES | | FIELD | +| greptime_timestamp | TimestampMillisecond | PRI | NO | 1970-01-01 00:00:00+0000 | TIMESTAMP | ++--------------------+----------------------+------+------+--------------------------+---------------+ +4 rows in set (0.00 sec) +``` + +:::tip 注意 +在这里,你可能会注意到出现了一个 `greptime_timestamp` 列,这个列作为表的时间索引列,在文件中并不存在。这是因为在创建外部表时,我们没有指定时间索引列,`greptime_timestamp` 列被自动添加作为时间索引列,并且默认值为 `1970-01-01 00:00:00+0000`。你可以在 [create](/reference/sql/create.md#create-external-table) 文档中查找更多详情。 +::: + +现在就可以查询外部表了: + +```sql +SELECT `Zone`, `Borough` FROM taxi_zone_lookup LIMIT 5; +``` + +```sql ++-------------------------+---------------+ +| Zone | Borough | ++-------------------------+---------------+ +| Newark Airport | EWR | +| Jamaica Bay | Queens | +| Allerton/Pelham Gardens | Bronx | +| Alphabet City | Manhattan | +| Arden Heights | Staten Island | ++-------------------------+---------------+ +``` + +## 对目录进行查询 + +首先下载一些数据: + +```bash +mkdir /tmp/external +curl "https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2022-01.parquet" -o /tmp/external/yellow_tripdata_2022-01.parquet +curl "https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2022-02.parquet" -o /tmp/external/yellow_tripdata_2022-02.parquet +``` + +验证下载情况: + +```bash +ls -l /tmp/external +total 165368 +-rw-r--r-- 1 wenyxu wheel 38139949 Apr 28 14:35 yellow_tripdata_2022-01.parquet +-rw-r--r-- 1 wenyxu wheel 45616512 Apr 28 14:36 yellow_tripdata_2022-02.parquet +``` + +创建外部表 + +```sql +CREATE EXTERNAL TABLE yellow_tripdata with(location='/tmp/external/',format='parquet'); +``` + +执行查询: + +```sql +SELECT count(*) FROM yellow_tripdata; +``` + +```sql ++-----------------+ +| COUNT(UInt8(1)) | ++-----------------+ +| 5443362 | ++-----------------+ +1 row in set (0.48 sec) +``` + +```sql +SELECT * FROM yellow_tripdata LIMIT 5; +``` + +```sql ++----------+----------------------+-----------------------+-----------------+---------------+------------+--------------------+--------------+--------------+--------------+-------------+-------+---------+------------+--------------+-----------------------+--------------+----------------------+-------------+---------------------+ +| VendorID | tpep_pickup_datetime | tpep_dropoff_datetime | passenger_count | trip_distance | RatecodeID | store_and_fwd_flag | PULocationID | DOLocationID | payment_type | fare_amount | extra | mta_tax | tip_amount | tolls_amount | improvement_surcharge | total_amount | congestion_surcharge | airport_fee | greptime_timestamp | ++----------+----------------------+-----------------------+-----------------+---------------+------------+--------------------+--------------+--------------+--------------+-------------+-------+---------+------------+--------------+-----------------------+--------------+----------------------+-------------+---------------------+ +| 1 | 2022-02-01 00:06:58 | 2022-02-01 00:19:24 | 1 | 5.4 | 1 | N | 138 | 252 | 1 | 17 | 1.75 | 0.5 | 3.9 | 0 | 0.3 | 23.45 | 0 | 1.25 | 1970-01-01 00:00:00 | +| 1 | 2022-02-01 00:38:22 | 2022-02-01 00:55:55 | 1 | 6.4 | 1 | N | 138 | 41 | 2 | 21 | 1.75 | 0.5 | 0 | 6.55 | 0.3 | 30.1 | 0 | 1.25 | 1970-01-01 00:00:00 | +| 1 | 2022-02-01 00:03:20 | 2022-02-01 00:26:59 | 1 | 12.5 | 1 | N | 138 | 200 | 2 | 35.5 | 1.75 | 0.5 | 0 | 6.55 | 0.3 | 44.6 | 0 | 1.25 | 1970-01-01 00:00:00 | +| 2 | 2022-02-01 00:08:00 | 2022-02-01 00:28:05 | 1 | 9.88 | 1 | N | 239 | 200 | 2 | 28 | 0.5 | 0.5 | 0 | 3 | 0.3 | 34.8 | 2.5 | 0 | 1970-01-01 00:00:00 | +| 2 | 2022-02-01 00:06:48 | 2022-02-01 00:33:07 | 1 | 12.16 | 1 | N | 138 | 125 | 1 | 35.5 | 0.5 | 0.5 | 8.11 | 0 | 0.3 | 48.66 | 2.5 | 1.25 | 1970-01-01 00:00:00 | ++----------+----------------------+-----------------------+-----------------+---------------+------------+--------------------+--------------+--------------+--------------+-------------+-------+---------+------------+--------------+-----------------------+--------------+----------------------+-------------+---------------------+ +5 rows in set (0.11 sec) +``` + +:::tip 注意 +查询结果中包含 `greptime_timestamp` 列的值,尽管它在原始文件中并不存在。这个列的所有值均为 `1970-01-01 00:00:00+0000`,这是因为我们在创建外部表时,自动添加列 `greptime_timestamp`,并且默认值为 `1970-01-01 00:00:00+0000`。你可以在 [create](/reference/sql/create.md#create-external-table) 文档中查找更多详情。 +::: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/sql.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/sql.md new file mode 100644 index 0000000000..927a5837dd --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/sql.md @@ -0,0 +1,466 @@ +--- +keywords: [pg, pgsql, SQL 查询, 基础查询, 数据过滤, 数据排序, 数据聚合, 时间索引, 时间函数, 时间序列数据] +description: 介绍 GreptimeDB 支持的 SQL 查询功能,包括基础查询、函数使用、数据过滤、排序、聚合等内容。 +--- + +# SQL + +GreptimeDB 在查询数据时支持完整的 `SQL` 语法。 + +在这篇文档中,我们将使用 `monitor` 表中的数据作为示例来演示如何查询数据。关于如何创建 `monitor` 表格并向其中插入数据,请参考[表管理](/user-guide/deployments-administration/manage-data/basic-table-operations.md#创建表)和[写入数据](/user-guide/ingest-data/for-iot/sql.md)。 + +## 基础查询 + +通过 `SELECT` 语句来查询数据。例如,下面的查询返回 `monitor` 表中的所有数据: + +```sql +SELECT * FROM monitor; +``` + +查询结果如下: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2022-11-03 03:39:57 | 0.1 | 0.4 | +| 127.0.0.1 | 2022-11-03 03:39:58 | 0.5 | 0.2 | +| 127.0.0.2 | 2022-11-03 03:39:58 | 0.2 | 0.3 | ++-----------+---------------------+------+--------+ +3 rows in set (0.00 sec) +``` + +`SELECT` 字段列表中也支持使用函数。 +例如,你可以使用 `count()` 函数来获取表中的总行数: + +```sql +SELECT count(*) FROM monitor; +``` + +```sql ++-----------------+ +| COUNT(UInt8(1)) | ++-----------------+ +| 3 | ++-----------------+ +``` + +使用函数 `avg()` 返回某个字段的平均值: + +```sql +SELECT avg(cpu) FROM monitor; +``` + +```sql ++---------------------+ +| AVG(monitor.cpu) | ++---------------------+ +| 0.26666666666666666 | ++---------------------+ +1 row in set (0.00 sec) +``` + +你还可以只返回函数的结果,例如从时间戳中提取一年中的第几天。 +SQL 语句中的 `DOY` 是 `day of the year` 的缩写: + +```sql +SELECT date_part('DOY', '2021-07-01 00:00:00'); +``` + +结果: + +```sql ++----------------------------------------------------+ +| date_part(Utf8("DOY"),Utf8("2021-07-01 00:00:00")) | ++----------------------------------------------------+ +| 182 | ++----------------------------------------------------+ +1 row in set (0.003 sec) +``` + +时间函数的参数和结果与 SQL 客户端的时区保持一致。 +例如,当客户端的时区设置为 `+08:00` 时,下面两个查询的结果是相同的: + +```sql +select to_unixtime('2024-01-02 00:00:00'); +select to_unixtime('2024-01-02 00:00:00+08:00'); +``` + +请参考 [SELECT](/reference/sql/select.md) 和 [Functions](/reference/sql/functions/overview.md) 获取更多信息。 + +## 限制返回的行数 + +时间序列数据通常是海量的。 +为了节省带宽和提高查询性能,你可以使用 `LIMIT` 语句来限制 `SELECT` 语句返回的行数。 + +例如,下面的查询限制返回的行数为 10: + +```sql +SELECT * FROM monitor LIMIT 10; +``` + +## 过滤数据 + +你可以使用 `WHERE` 子句来过滤 `SELECT` 语句返回的行。 +时序数据库中常见的场景是按照标签或时间索引来过滤数据。 +例如,按照标签 `host` 来过滤数据: + +```sql +SELECT * FROM monitor WHERE host='127.0.0.1'; +``` + +按照时间索引 `ts` 来过滤数据,返回 `2022-11-03 03:39:57` 之后的数据: + +```sql +SELECT * FROM monitor WHERE ts > '2022-11-03 03:39:57'; +``` + +你可以使用 `AND` 关键字来组合多个约束条件: + +```sql +SELECT * FROM monitor WHERE host='127.0.0.1' AND ts > '2022-11-03 03:39:57'; +``` + +### 使用时间索引过滤数据 + +按照时间索引来过滤数据是时序数据库的一个关键特性。 + +当处理 Unix 时间值时,数据库会默认将其类型认定为相关列的值类型。 +例如,当 `monitor` 表中的 `ts` 列的值类型为 `TimestampMillisecond` 时, +你可以使用下面的查询来过滤数据: + +Unix 时间值 `1667446797000` 表示一个以毫秒为单位的时间戳。 + +```sql +SELECT * FROM monitor WHERE ts > 1667446797000; +``` + +当处理时间精度为非默认类型的 Unix 时间值时,你需要使用 `::` 语法来指定时间的类型。 +这样可以确保数据库正确地识别时间的类型。 + +例如 `1667446797` 表示一个以秒为单位的时间戳,不是 `ts` 列默认的毫秒时间戳。 +你需要使用 `::TimestampSecond` 语法来指定它的类型为 `TimestampSecond` 来告知数据库 `1667446797` 应该被视为以秒为单位的时间戳。 + +```sql +SELECT * FROM monitor WHERE ts > 1667446797::TimestampSecond; +``` + +请参考[数据类型](/reference/sql/data-types.md#日期和时间类型) 获取更多时间类型。 + +对于标准的 `RFC3339` 或 `ISO8601` 字符串,由于其具备明确的精度,你可以直接在过滤条件中使用它们: + +```sql +SELECT * FROM monitor WHERE ts > '2022-07-25 10:32:16.408'; +``` + +你还可以使用时间函数来过滤数据。 +例如,使用 `now()` 函数和 `INTERVAL` 关键字来获取最近 5 分钟的数据: + +```sql +SELECT * FROM monitor WHERE ts >= now() - '5 minutes'::INTERVAL; +``` + +请参考 [Functions](/reference/sql/functions/overview.md) 获取更多时间函数信息。 + +### 时区 + +GreptimeDB 的 SQL 客户端会根据本地时区解释不带时区信息的字符串时间戳。 +例如,当客户端时区为 `+08:00` 时,下面的两个查询是相同的: + +```sql +SELECT * FROM monitor WHERE ts > '2022-07-25 10:32:16.408'; +SELECT * FROM monitor WHERE ts > '2022-07-25 10:32:16.408+08:00'; +``` + +查询结果中的时间戳列值会根据客户端时区格式化。 +例如,下面的代码展示了相同的 `ts` 值在客户端时区 `UTC` 和 `+08:00` 下的结果: + + + + + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2023-12-31 16:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +``` + + + + + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-01-01 00:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +``` + + + + +### 函数 + +GreptimeDB 提供了丰富的内置函数和聚合函数,为数据分析应用开发。其特点包括: + ++ Apache Datafusion 查询引擎中继承的函数,包括一组符合 Postgres 命名方式和行为的日期/时间函数。 ++ JSON、位置信息等特殊数据类型的操作函数。 ++ 高级全文匹配能力。 + +查看 [函数列表](/reference/sql/functions/overview.md)。 + + +## 排序 + +GreptimeDB 不保证返回数据的顺序。你需要使用 `ORDER BY` 子句来对返回的数据进行排序。 +例如,在时间序列场景中通常使用时间索引列作为排序键: + +```sql +-- ascending order by ts +SELECT * FROM monitor ORDER BY ts ASC; +``` + +```sql +-- descending order by ts +SELECT * FROM monitor ORDER BY ts DESC; +``` + +## `CASE` 表达式 + +你可以使用 `CASE` 表达式在查询中执行条件逻辑。 +例如,下面的查询根据 `cpu` 字段的值返回 CPU 的状态: + +```sql +SELECT + host, + ts, + CASE + WHEN cpu > 0.5 THEN 'high' + WHEN cpu > 0.3 THEN 'medium' + ELSE 'low' + END AS cpu_status +FROM monitor; +``` + +结果如下: + +```sql ++-----------+---------------------+------------+ +| host | ts | cpu_status | ++-----------+---------------------+------------+ +| 127.0.0.1 | 2022-11-03 03:39:57 | low | +| 127.0.0.1 | 2022-11-03 03:39:58 | medium | +| 127.0.0.2 | 2022-11-03 03:39:58 | low | ++-----------+---------------------+------------+ +3 rows in set (0.01 sec) +``` + +更多信息请参考 [CASE](/reference/sql/case.md)。 + +## 按标签聚合数据 + +你可以使用 `GROUP BY` 语句将具有相同值的行进行分组汇总,例如查询 `idc` 列中的所有不同值的内存均值: + +```sql +SELECT host, avg(cpu) FROM monitor GROUP BY host; +``` + +```sql ++-----------+------------------+ +| host | AVG(monitor.cpu) | ++-----------+------------------+ +| 127.0.0.2 | 0.2 | +| 127.0.0.1 | 0.3 | ++-----------+------------------+ +2 rows in set (0.00 sec) +``` + +请参考 [GROUP BY](/reference/sql/group_by.md) 获取更多相关信息。 + +### 查询时间线中的最新数据 + +你可以通过组合使用 `DISTINCT ON` 和 `ORDER BY` 来查询每条时间线的最新数据点,例如: + +```sql +SELECT DISTINCT ON (host) * FROM monitor ORDER BY host, ts DESC; +``` + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2022-11-03 03:39:58 | 0.5 | 0.2 | +| 127.0.0.2 | 2022-11-03 03:39:58 | 0.2 | 0.3 | ++-----------+---------------------+------+--------+ +2 rows in set (0.00 sec) +``` +## 按时间窗口聚合数据 + +GreptimeDB 支持 [Range Query](/reference/sql/range.md) 来按时间窗口聚合数据。 + +假设我们有以下数据在 [`monitor` 表](/user-guide/deployments-administration/manage-data/basic-table-operations.md#创建表) 中: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2023-12-13 02:05:41 | 0.5 | 0.2 | +| 127.0.0.1 | 2023-12-13 02:05:46 | NULL | NULL | +| 127.0.0.1 | 2023-12-13 02:05:51 | 0.4 | 0.3 | +| 127.0.0.2 | 2023-12-13 02:05:41 | 0.3 | 0.1 | +| 127.0.0.2 | 2023-12-13 02:05:46 | NULL | NULL | +| 127.0.0.2 | 2023-12-13 02:05:51 | 0.2 | 0.4 | ++-----------+---------------------+------+--------+ +``` + +下面的查询返回 10 秒内的平均 CPU 使用率,并且每 5 秒计算一次: + +```sql +SELECT + ts, + host, + avg(cpu) RANGE '10s' FILL LINEAR +FROM monitor +ALIGN '5s' TO '2023-12-01T00:00:00' BY (host) ORDER BY ts ASC; +``` + +1. `avg(cpu) RANGE '10s' FILL LINEAR` 是一个 Range 表达式。`RANGE '10s'` 指定了聚合的时间范围为 10s,`FILL LINEAR` 指定了如果某个点没有数据,使用 `LINEAR` 方法来填充。 +2. `ALIGN '5s'` 指定了查询的步频为 5s。 +3. `TO '2023-12-01T00:00:00` 指定了原始对齐时间。默认值为 Unix 时间 0。 +4. `BY (host)` 指定了聚合的键。如果省略 `BY` 关键字,那么默认使用数据表的主键作为聚合键。 +5. `ORDER BY ts ASC` 指定了结果集的排序方法。如果不指定排序方法,结果集的顺序是不确定的。 + +查询结果如下: + +```sql ++---------------------+-----------+----------------------------------------+ +| ts | host | AVG(monitor.cpu) RANGE 10s FILL LINEAR | ++---------------------+-----------+----------------------------------------+ +| 2023-12-13 02:05:35 | 127.0.0.1 | 0.5 | +| 2023-12-13 02:05:40 | 127.0.0.1 | 0.5 | +| 2023-12-13 02:05:45 | 127.0.0.1 | 0.4 | +| 2023-12-13 02:05:50 | 127.0.0.1 | 0.4 | +| 2023-12-13 02:05:35 | 127.0.0.2 | 0.3 | +| 2023-12-13 02:05:40 | 127.0.0.2 | 0.3 | +| 2023-12-13 02:05:45 | 127.0.0.2 | 0.2 | +| 2023-12-13 02:05:50 | 127.0.0.2 | 0.2 | ++---------------------+-----------+----------------------------------------+ +``` + +### 时间范围窗口 + +将初始时间范围窗口在时间序列中向前和向后移动,就生成了所有时间范围窗口。 +在上面的例子中,初始对齐时间被设置为 `2023-12-01T00:00:00`,这也是初始时间窗口的结束时间。 + +`RANGE` 选项和初始对齐时间定义了初始时间范围窗口,它从 `初始对齐时间` 开始,到 `初始对齐时间 + RANGE` 结束。 +`ALIGN` 选项定义了查询的步频,决定了从初始时间窗口到其他时间窗口的计算步频。 +例如,使用初始对齐时间 `2023-12-01T00:00:00` 和 `ALIGN '5s'`,时间窗口的对齐时间为 `2023-11-30T23:59:55`、`2023-12-01T00:00:00`、`2023-12-01T00:00:05`、`2023-12-01T00:00:10` 等。 + +这些时间窗口是左闭右开区间,满足条件 `[对齐时间, 对齐时间 + 范围)`。 + +下方的图片可以帮助你更直观的理解时间范围窗口: + +当查询的步频大于时间范围窗口时,数据将只会被计算在一个时间范围窗口中。 + +![align > range](/align_greater_than_range.png) + +当查询的步频小于时间范围窗口时,数据将会被计算在多个时间范围窗口中。 + +![align < range](/align_less_than_range.png) + +### 对齐到特定时间戳 + +对齐时间默认基于当前 SQL 客户端会话的时区。 +你可以将初始对齐时间设置为任何你想要的时间戳。例如,使用 `NOW` 将对齐到当前时间: + +```sql +SELECT + ts, + host, + avg(cpu) RANGE '1w' +FROM monitor +ALIGN '1d' TO NOW BY (host); +``` + +或者使用 `ISO 8601` 时间戳将对齐到指定时间: + +```sql +SELECT + ts, + host, + avg(cpu) RANGE '1w' +FROM monitor +ALIGN '1d' TO '2023-12-01T00:00:00+08:00' BY (host); +``` + +### 填充空值 + +`FILL` 选项可以用来填充数据中的空值。 +例如上面的例子使用了 `LINEAR` 方法来填充空值。 +该选项也支持其他填充空值的方法,例如 `PREV` 和常量值 `X`,更多信息请参考 [FILL OPTION](/reference/sql/range.md#fill-option)。 + +### 语法 + +请参考 [Range Query](/reference/sql/range.md) 获取更多信息。 + +## 表名约束 + +如果你的表名包含特殊字符或大写字母,需要将表名用反引号括起来。 +有关示例,请参阅表创建表文档中的[表名约束](/user-guide/deployments-administration/manage-data/basic-table-operations.md#表名约束)部分。 + +## HTTP API + +在 HTTP 请求中使用 `POST` 方法来查询数据: + +```shell +curl -X POST \ + -H 'authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d 'sql=select * from monitor' \ +http://localhost:4000/v1/sql?db=public +``` + +结果如下: + +```json +{ + "code": 0, + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "host", + "data_type": "String" + }, + { + "name": "ts", + "data_type": "TimestampMillisecond" + }, + { + "name": "cpu", + "data_type": "Float64" + }, + { + "name": "memory", + "data_type": "Float64" + } + ] + }, + "rows": [ + ["127.0.0.1", 1667446797450, 0.1, 0.4], + ["127.0.0.1", 1667446798450, 0.5, 0.2], + ["127.0.0.2", 1667446798450, 0.2, 0.3] + ] + } + } + ], + "execution_time_ms": 0 +} +``` + +请参考 [API 文档](/user-guide/protocols/http.md#post-sql-语句)获取更详细的 HTTP 请求的内容。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/view.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/view.md new file mode 100644 index 0000000000..5b8825ade4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/query-data/view.md @@ -0,0 +1,149 @@ +--- +keywords: [视图, SQL 视图, 创建视图, 更新视图, 删除视图, 显示视图定义, 列出视图] +description: 介绍了视图的定义、使用示例、更新、显示定义、列出视图和删除视图的方法。 +--- + +# 视图 + +在 SQL 中,视图(View)是基于 SQL 语句的结果集的虚拟表。 +它包含与真实的表一样的行和列。 +每次查询视图时,都会运行该视图的查询。 + +在以下情况下,我们可以使用视图: +* 简化复杂查询,避免每次查询都重复编写和发送复杂语句。 +* 对特定用户开放读取权限,限制一些列和行的读取,保证数据安全和隔离。 + +可以使用 `CREATE VIEW` 语句创建视图。 + +## 视图示例 + +```sql +CREATE VIEW cpu_monitor AS + SELECT cpu, host, ts FROM monitor; +``` + +这个视图的名称是 `cpu_monitor`,在 `AS` 之后的查询语句是用于呈现数据的 SQL 语句。查询视图: + +```sql +SELECT * FROM cpu_monitor; +``` + +结果示例: + +```sql ++------+-----------+---------------------+ +| cpu | host | ts | ++------+-----------+---------------------+ +| 0.5 | 127.0.0.1 | 2023-12-13 02:05:41 | +| 0.3 | 127.0.0.1 | 2023-12-13 02:05:46 | +| 0.4 | 127.0.0.1 | 2023-12-13 02:05:51 | +| 0.3 | 127.0.0.2 | 2023-12-13 02:05:41 | +| 0.2 | 127.0.0.2 | 2023-12-13 02:05:46 | +| 0.2 | 127.0.0.2 | 2023-12-13 02:05:51 | ++------+-----------+---------------------+ +``` + +通过 `WHERE` 查询视图: + +```sql +SELECT * FROM cpu_monitor WHERE host = '127.0.0.2'; +``` + +结果示例: + +```sql ++------+-----------+---------------------+ +| cpu | host | ts | ++------+-----------+---------------------+ +| 0.3 | 127.0.0.2 | 2023-12-13 02:05:41 | +| 0.2 | 127.0.0.2 | 2023-12-13 02:05:46 | +| 0.2 | 127.0.0.2 | 2023-12-13 02:05:51 | ++------+-----------+---------------------+ +``` + +创建一个从两个表联合查询数据的视图: + +```sql +CREATE VIEW app_cpu_monitor AS + SELECT cpu, latency, host, ts FROM monitor LEFT JOIN app_monitor + ON monitor.host = app_monitor.host AND monitor.ts = app_monitor.ts +``` + +然后可以像查询一个单表数据一样查询这个视图: + +```sql +SELECT * FROM app_cpu_monitor WHERE host = 'host1' +``` + +## 更新视图 + +使用 `CREATE OR REPLACE VIEW` 来更新视图,如果视图不存在,则会创建: + +```sql +CREATE OR REPLACE VIEW memory_monitor AS + SELECT memory, host, ts FROM monitor; +``` + +## 显示视图定义 + +通过 `SHOW CREATE VIEW view_name` 语句来显示创建视图的 `CREATE VIEW` 语句: + +```sql +SHOW CREATE VIEW cpu_monitor; +``` + +```sql ++-------------+--------------------------------------------------------------+ +| View | Create View | ++-------------+--------------------------------------------------------------+ +| cpu_monitor | CREATE VIEW cpu_monitor AS SELECT cpu, host, ts FROM monitor | ++-------------+--------------------------------------------------------------+ +``` + +## 列出视图 + +使用 `SHOW VIEWS` 语句查找所有视图: + +```sql +> SHOW VIEWS; + ++----------------+ +| Views | ++----------------+ +| cpu_monitor | +| memory_monitor | ++----------------+ +``` + +当然,像 `SHOW TABLES` 一样,它也支持 `LIKE` 和 `WHERE`: + +```sql +> SHOW VIEWS like 'cpu%'; ++-------------+ +| Views | ++-------------+ +| cpu_monitor | ++-------------+ +1 row in set (0.02 sec) + +> SHOW VIEWS WHERE Views = 'memory_monitor'; ++----------------+ +| Views | ++----------------+ +| memory_monitor | ++----------------+ +``` + +## 删除视图 + +使用 `DROP VIEW` 语句删除视图: + +```sql +DROP VIEW cpu_monitor; +``` + +如果希望在视图不存在时不报错,可以使用: + +```sql +DROP VIEW IF EXISTS test; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/timezone.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/timezone.md new file mode 100644 index 0000000000..76692a9dce --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/timezone.md @@ -0,0 +1,53 @@ +--- +keywords: [时区, 客户端会话, 数据写入, 数据查询, 时间管理, GreptimeDB, 时区设置] +description: 介绍了如何在客户端会话中指定时区,并解释了时区设置对数据写入和查询的影响。 +--- + +# 时区 + +你可以在客户端会话中指定时区以方便地管理时间数据。 +客户端会话中指定的时区仅应用在客户端向服务器发送请求时, +不影响存储在 GreptimeDB 服务器中的时间数据。 +GreptimeDB 在数据写入或查询时,会根据指定的时区将时间值从字符串表示转换为日期时间,或转换回来。 + +## 在客户端中指定时区 + +默认情况下,所有客户端使用[默认时区配置](/user-guide/deployments-administration/configuration.md#默认时区配置),即 UTC。 +你也可以在每个客户端会话中指定时区, +这将覆盖默认的时区配置。 + +### MySQL 客户端 + +- **命令行**:有关通过 MySQL 命令行客户端配置时区的内容,请参阅 MySQL 协议文档中的[时区部分](/user-guide/protocols/mysql.md#时区)。 +- **MySQL driver**:如果你使用的是 Java 或 Go 中的 MySQL driver,请查看 SQL 工具文档的[时区部分](/reference/sql-tools.md#时区)。 + +### PostgreSQL 客户端 + +要配置 PostgreSQL 客户端的时区,请参阅 PostgreSQL 协议文档中的[时区部分](/user-guide/protocols/postgresql.md#时区)。 + +### HTTP API + +使用 HTTP API 时,你可以通过 header 参数指定时区。有关更多信息,请参阅 [HTTP API 文档](/user-guide/protocols/http.md#时区)。 + +### Dashboard + +Dashboard 将使用本地时区作为默认时区值。您可以在 settings 菜单中更改它。 + +### 其他客户端 + +对于其他客户端,你可以更改 GreptimeDB 的[默认时区配置](/user-guide/deployments-administration/configuration.md#默认时区配置)。 + +## 时区对 SQL 语句的影响 + +客户端中的时区设置会影响数据的写入和查询。 + +### 写入数据 + +客户端中设置的时区会影响数据的写入。有关更多信息,请参阅[写入数据](/user-guide/ingest-data/for-iot/sql.md#时区)。 +此外,表 schema 中的默认写入的时间戳值也会受到客户端时区的影响,影响方式与数据写入相同。 + +### 查询数据 + +时区设置也会影响数据的查询。 +有关详细信息,请参阅[查询数据](/user-guide/query-data/sql.md#时区)。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/data-model.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/data-model.md new file mode 100644 index 0000000000..bff6267d19 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/data-model.md @@ -0,0 +1,185 @@ +--- +keywords: [Trace, OpenTelemetry, Jaeger] +description: 介绍 Trace 数据如何存入 GreptimeDB. +--- + +# Trace 数据模型 + +:::warning + +本章内容目前仍处于实验阶段,在未来的版本中可能会有所调整。 + +::: + +在本节,我们主要描述 Trace 数据如何转换成 GreptimeDB 的表结构。 + +我们复用了 Pipeline 的概念来标记数据模型的版本,因此注意在 Trace 数据中暂时只能 +使用内置的 Pipeline。 + +## 数据模型版本机制 + +GreptimeDB 本身的数据类型和相关功能在持续演化。为了实现向后兼容,我们使用 +Pipeline 的名称来作为数据模型的版本。目前可用的 Pipeline 包括: + +- `greptime_trace_v1` + +在使用 OTLP/HTTP 协议写入数据时,HTTP 头是必须设置的 `x-greptime-pipeline-name: +greptime_trace_v1`. + +在未来我们可能引入新的 Pipeline 名称,即数据模型版本。但已有的版本会持续保持维护。 +新的 Pipeline 可能与老版本不兼容,倒是需要创建新的数据表来使用。 + +## 数据模型 + +`greptime_trace_v1` 数据模型是非常直观的: + +- 所有常见的 [OpenTelemetry + Trace](https://opentelemetry.io/docs/concepts/signals/traces/) 数据字段都被映 + 射为 GreptimeDB 的列。 +- `duration_nano` 列由 `end_time - start_time` 生成。 +- 所有的属性字段被打平为列,按照 `[span|resource|scope]_attributes.[attribute_key]` + 的命名方式生成名称。如果属性的值是复合类型,如 `Array` 或 `Kvlist`,它将被存储 + 为 GreptimeDB 的 JSON 类型。 +- 其他复合类型字段 `span_links` 和 `span_events` 将被存储为 JSON 类型。 + +在插入第一条数据时,表将被创建。并且当数据中涉及新的字段时,表的结构会自动变更增 +加列。 + +以下是一个使用 OpenTelemetry Django 埋点生成的表结构: + +``` +timestamp | 2025-05-07 10:03:29.657544 +timestamp_end | 2025-05-07 10:03:29.661714 +duration_nano | 4169970 +trace_id | fb60d19aa36fdcb7d14a71ca0b9b42ae +span_id | 49806a2671f2ddcb +span_kind | SPAN_KIND_SERVER +span_name | POST todos/ +span_status_code | STATUS_CODE_UNSET +span_status_message | +trace_state | +scope_name | opentelemetry.instrumentation.django +scope_version | 0.51b0 +service_name | myproject +span_attributes.http.request.method | POST +span_attributes.url.full | +span_attributes.server.address | django:8000 +span_attributes.network.peer.address | +span_attributes.server.port | 8000 +span_attributes.network.peer.port | +span_attributes.http.response.status_code | 201 +span_attributes.network.protocol.version | 1.1 +resource_attributes.telemetry.sdk.language | python +resource_attributes.telemetry.sdk.name | opentelemetry +resource_attributes.telemetry.sdk.version | 1.30.0 +span_events | [] +span_links | [] +parent_span_id | eccc18b6fc210f31 +span_attributes.db.system | +span_attributes.db.name | +span_attributes.db.statement | +span_attributes.url.scheme | http +span_attributes.url.path | /todos/ +span_attributes.client.address | 10.89.0.5 +span_attributes.client.port | 44302 +span_attributes.user_agent.original | python-requests/2.32.3 +span_attributes.http.route | todos/ +``` + +可以通过执行 `show create table
` 来查看表建表语句: + +``` +Table | web_trace_demo +Create Table | CREATE TABLE IF NOT EXISTS "web_trace_demo" ( + + | "timestamp" TIMESTAMP(9) NOT NULL, + + | "timestamp_end" TIMESTAMP(9) NULL, + + | "duration_nano" BIGINT UNSIGNED NULL, + + | "trace_id" STRING NULL SKIPPING INDEX WITH(granularity = '10240', type = 'BLOOM'), + + | "span_id" STRING NULL, + + | "span_kind" STRING NULL, + + | "span_name" STRING NULL, + + | "span_status_code" STRING NULL, + + | "span_status_message" STRING NULL, + + | "trace_state" STRING NULL, + + | "scope_name" STRING NULL, + + | "scope_version" STRING NULL, + + | "service_name" STRING NULL SKIPPING INDEX WITH(granularity = '10240', type = 'BLOOM'),+ + | "span_attributes.http.request.method" STRING NULL, + + | "span_attributes.url.full" STRING NULL, + + | "span_attributes.server.address" STRING NULL, + + | "span_attributes.network.peer.address" STRING NULL, + + | "span_attributes.server.port" BIGINT NULL, + + | "span_attributes.network.peer.port" BIGINT NULL, + + | "span_attributes.http.response.status_code" BIGINT NULL, + + | "span_attributes.network.protocol.version" STRING NULL, + + | "resource_attributes.telemetry.sdk.language" STRING NULL, + + | "resource_attributes.telemetry.sdk.name" STRING NULL, + + | "resource_attributes.telemetry.sdk.version" STRING NULL, + + | "span_events" JSON NULL, + + | "span_links" JSON NULL, + + | "parent_span_id" STRING NULL, + + | "span_attributes.db.system" STRING NULL, + + | "span_attributes.db.name" STRING NULL, + + | "span_attributes.db.statement" STRING NULL, + + | "span_attributes.url.scheme" STRING NULL, + + | "span_attributes.url.path" STRING NULL, + + | "span_attributes.client.address" STRING NULL, + + | "span_attributes.client.port" BIGINT NULL, + + | "span_attributes.user_agent.original" STRING NULL, + + | "span_attributes.http.route" STRING NULL, + + | TIME INDEX ("timestamp"), + + | PRIMARY KEY ("service_name") + + | ) + + | PARTITION ON COLUMNS ("trace_id") ( + + | trace_id < '1', + + | trace_id >= 'f', + + | trace_id >= '1' AND trace_id < '2', + + | trace_id >= '2' AND trace_id < '3', + + | trace_id >= '3' AND trace_id < '4', + + | trace_id >= '4' AND trace_id < '5', + + | trace_id >= '5' AND trace_id < '6', + + | trace_id >= '6' AND trace_id < '7', + + | trace_id >= '7' AND trace_id < '8', + + | trace_id >= '8' AND trace_id < '9', + + | trace_id >= '9' AND trace_id < 'a', + + | trace_id >= 'a' AND trace_id < 'b', + + | trace_id >= 'b' AND trace_id < 'c', + + | trace_id >= 'c' AND trace_id < 'd', + + | trace_id >= 'd' AND trace_id < 'e', + + | trace_id >= 'e' AND trace_id < 'f' + + | ) + + | ENGINE=mito + + | WITH( + + | append_mode = 'true', + + | table_data_model = 'greptime_trace_v1' + + | ) +``` + +### 分区规则 + +Trace 表包含了默认的 [分区规 +则](/user-guide/deployments-administration/manage-data/table-sharding.md#partition),在 +`trace_id` 列上根据首个字符的取值划分区间。 + +这个规则默认将引入 16 个分区,适合在 3-5 个 datanode 的部署规模下使用。 + +如果数据量和部署规模更大,需要自定义分区规则,可以拷贝这个建表语句,并更新 +`PARTITION ON` 这部分来设置更细致的分区规则,并在写入数据之前创建这个表。 + +### 索引 + +我们默认使用对 `service_name` 和 `trace_id` 两个常用字段使用[跳数索 +引](/user-guide/manage-data/data-index.md#skipping-index),满足常见的查询场景。 + +实际使用中,用户可能希望对一些特定的属性列增加索引,这可以通过[alter +table](/reference/sql/alter.md#create-an-index-for-a-column)语句来实现。不同于分 +区规则,索引可以增量添加而不用重新建表。 + +### Append 模式 + +通过此接口创建的表,默认为[Append 模 +式](/user-guide/deployments-administration/performance-tuning/design-table.md#何时使用-append-only-表)。 + +### TTL + +可以对 Trace 表应用 [过期时间规则](/reference/sql/alter.md#alter-table-options)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/extend-trace.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/extend-trace.md new file mode 100644 index 0000000000..b0d1195c07 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/extend-trace.md @@ -0,0 +1,110 @@ +--- +keywords: [Trace, OpenTelemetry, Jaeger, Grafana] +description: 介绍从 Trace 数据中衍生其他数据的机制 +--- + +# 扩展 Trace 数据 + +:::warning + +本章内容目前仍处于实验阶段,在未来的版本中可能会有所调整。 + +::: + +本章主要介绍如何从 Trace 数据中生成衍生数据。 + +## 从 Trace 生成聚合指标数据 + +每个 Span 中都包含 `duration_nano` 字段代表其处理时间,在这个例子里,我们将创建 +[Flow](/user-guide/flow-computation/overview.md) 任务来生成延迟的指标数据。 + +这里我们使用 OpenTelemetry Django 埋点数据作为源数据,不过因为使用的都是通用字段, +所以并不影响例子的解读。 + +### 创建 Sink 表 + +首先,我们创建一个 Flow 中的物化视图,Sink 表。对于延迟数据,我们使用 +[uddsketch](https://arxiv.org/abs/2004.08604) 结构来快速生成特定百分为的延迟数据。 + +```sql +CREATE TABLE "django_http_request_latency" ( + "span_name" STRING NULL, + "latency_sketch" BINARY, + "time_window" TIMESTAMP time index, + PRIMARY KEY ("span_name") +); +``` + +表中包含三个关键列: + +- `span_name`: Span 的名称或类型 +- `latency_sketch`: uddsketch 数据 +- `time_window`: 时间窗口 + +### 创建 Flow + +下一步我们创建用于计算 uddsketch 数据的 Flow 任务。该任务以 30s 为时间窗口。这里 +例子里我们过滤了 `scope_name` 字段,在实际的场景里这是可选的。 + +```sql +CREATE FLOW django_http_request_latency_flow +SINK TO django_http_request_latency +EXPIRE AFTER '30m' +COMMENT 'Aggregate latency using uddsketch' +AS +SELECT + span_name, + uddsketch_state(128, 0.01, "duration_nano") AS "latency_sketch", + date_bin('30 seconds'::INTERVAL, "timestamp") as "time_window", +FROM web_trace_demo +WHERE + scope_name = 'opentelemetry.instrumentation.django' +GROUP BY + span_name, + time_window; +``` + +### 查询指标 + +当 Trace 数据写入进来时,sink 表中将有数据生成。我们可以用 SQL 语句来查询 p90 分 +为的延迟: + +```sql +SELECT + span_name, + time_window, + uddsketch_calc(0.90, "latency_sketch") AS p90 +FROM + django_http_request_latency +ORDER BY + time_window DESC +LIMIT 20; +``` + +我们将获得类似的结果: + +``` + span_name | time_window | p90 +---------------------+----------------------------+-------------------- + GET todos/ | 2025-05-09 02:38:00.000000 | 4034758.586053441 + POST todos/ | 2025-05-09 02:38:00.000000 | 22988738.680499777 + PUT todos// | 2025-05-09 02:38:00.000000 | 5338559.200101535 + GET todos/ | 2025-05-09 02:37:30.000000 | 4199425.807196321 + POST todos/ | 2025-05-09 02:37:30.000000 | 15104466.164886404 + PUT todos// | 2025-05-09 02:37:30.000000 | 16693072.385310777 + GET todos/ | 2025-05-09 02:37:00.000000 | 4370813.453648573 + POST todos/ | 2025-05-09 02:37:00.000000 | 30417369.407361753 + PUT todos// | 2025-05-09 02:37:00.000000 | 14512192.224492861 + GET todos/ | 2025-05-09 02:36:30.000000 | 3578495.53232116 + POST todos/ | 2025-05-09 02:36:30.000000 | 15409606.895490168 + PUT todos// | 2025-05-09 02:36:30.000000 | 15409606.895490168 + GET todos/ | 2025-05-09 02:36:00.000000 | 3507634.2346514342 + POST todos/ | 2025-05-09 02:36:00.000000 | 45377987.991290994 + PUT todos// | 2025-05-09 02:36:00.000000 | 14512192.224492861 + GET todos/ | 2025-05-09 02:35:30.000000 | 3237945.86410019 + POST todos/ | 2025-05-09 02:35:30.000000 | 15409606.895490168 + PUT todos// | 2025-05-09 02:35:30.000000 | 13131130.769316385 + GET todos/ | 2025-05-09 02:35:00.000000 | 3173828.124217018 + POST todos/ | 2025-05-09 02:35:00.000000 | 14512192.224492861 +(20 rows) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/overview.md new file mode 100644 index 0000000000..11eb9d777d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/overview.md @@ -0,0 +1,19 @@ +--- +keywords: [trace, distributed tracing, opentelemetry, jaeger, wide events, observability] +description: 介绍 GreptimeDB 中的 Trace 数据支持 +--- + +# Trace + +:::warning + +本章内容目前仍处于实验阶段,在未来的版本中可能会有所调整。 + +::: + +GreptimeDB 0.14 中加入了 Trace 数据的原生支持。本节内容我们将介绍 Trace 数据读写, +和数据建模等高级主题。 + +- [如何读写 Trace 数据](./read-write.md) +- [GreptimeDB 中的 Trace 数据建模](./data-model.md) +- [扩展 Trace 数据](./extend-trace.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/read-write.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/read-write.md new file mode 100644 index 0000000000..e2c49b4dee --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/traces/read-write.md @@ -0,0 +1,171 @@ +--- +keywords: [Trace, OpenTelemetry, Jaeger, Grafana] +description: 介绍 GreptimeDB 中的 Trace 的数据写入和查询。 +--- + +# 写入与查询 + +:::warning + +本章内容目前仍处于实验阶段,在未来的版本中可能会有所调整。 + +::: + +本节我们将从 Trace 数据的写入和查询开始使用 GreptimeDB. + +GreptimeDB 并未为 Trace 数据引入新的协议,而是尽可能使用以后的广泛接受的协议。 + +## 写入 + +GreptimeDB 使用 OpenTelemetry 的 OTLP/HTTP 协议作为主要的 Trace 数据写入协议。 +Trace 也是 OpenTelemetry 中最广为接受的子协议,包含了良好的生态。 + +### OpenTelemetry SDK + +如果你在应用中使用了 OpenTelemetry 的 SDK/API 库,你可以直接配置一个 OTLP/HTTP +的导出模块来将 trace 数据写入 GreptimeDB。 + +在我们的 [OpenTelemetry 协议文档 +里](/user-guide/ingest-data/for-observability/opentelemetry.md) 介绍了关于这部分 +接口的使用,包含相应的写入路径和配置项。 + +### OpenTelemetry Collector + +[OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) 是一个厂商中 +立的用于收集和处理 OpenTelemetry 数据的服务。本文我们将介绍如何使用 +OpenTelemetry Collector 将 traces 数据写入到 GreptimeDB。 + +#### 启动 OpenTelemetry Collector + +你可以使用如下命令来快速启动一个 OpenTelemetry Collector 实例,此时 collector 会监听 `4317`(gRPC) 和 `4318`(HTTP) 端口: + +```shell +docker run --rm \ + --network host \ + -p 4317:4317 \ + -p 4318:4318 \ + -v $(pwd)/config.yaml:/etc/otelcol-contrib/config.yaml \ + otel/opentelemetry-collector-contrib:0.123.0 +``` + +其中 `config.yaml` 文件内容如下: + +```yaml +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +exporters: + otlphttp: + endpoint: "http://greptimedb:4000/v1/otlp" # GreptimeDB 的 OTLP 路径 + headers: + x-greptime-pipeline-name: "greptime_trace_v1" + #authorization: "Basic " + tls: + insecure: true + +service: + pipelines: + traces: + receivers: [otlp] + exporters: [otlphttp] +``` + +#### 将 traces 数据写入到 OpenTelemetry Collector + +你可以给应用配置相应的 exporter 来将 traces 数据写入到 OpenTelemetry Collector。 +比如你可以使用环境变量 `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` 来配置 exporter 的 +endpoint: + +```shell +export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="http://localhost:4318/v1/otlp/v1/traces" +``` + +此处为了方便,我们可使用工具 +[`telemetrygen`](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/cmd/telemetrygen) +来快速生成 traces 数据并写入到 OpenTelemetry Collector 中,更多细节可参考 +[OpenTelemetry Collector 官方文 +档](https://opentelemetry.io/docs/collector/quick-start/)。 + +我们可以用如下命令安装 `telemetrygen`(请确保你已经安装了 Go): + +```shell +go install github.com/open-telemetry/opentelemetry-collector-contrib/cmd/telemetrygen@latest +``` + +然后我们就可以使用如下命令来生成 traces 数据并写入到 OpenTelemetry Collector 中: + +```shell +telemetrygen traces --otlp-insecure --traces 3 +``` + +上面这条命令将生成 3 条 traces 数据,并通过 gRPC 协议写入到 OpenTelemetry Collector 中。 + + +### 认证 + +GreptimeDB 的 OTEL 端点支持 Basic 认证。详情请参考 [鉴权](/user-guide/protocols/http.md#鉴权) 文档。 + +### GreptimeDB Pipeline + +在 OTLP 接口中,我们要求 HTTP 头 `x-greptime-pipeline-name` 作为必选参数。在这里 +我们复用了日志接口中 Pipeline 的概念作为数据转化的机制。但是注意在 Trace 接口中 +我们目前仅支持内置的 `greptime_trace_v1`,自定义的 Pipeline 暂不支持。 + +### Append 模式 + +通过此接口创建的表,默认为[Append 模 +式](/user-guide/deployments-administration/performance-tuning/design-table.md#何时使用-append-only-表). + +## 查询 + +GreptimeDB 提供了两种 Trace 数据的查询接口,分别是 Jarger API 兼容接口和 +GreptimeDB 原生的 SQL 查询接口,后者可以运行在 HTTP, MySQL 或者 Postgres 等协议 +上。 + +### Jaeger + +GreptimeDB 内置的 Jaeger 兼容层使得用户可以直接复用市面上的 Jaeger 生态工具,例 +如 Grafana 的 Jaeger 数据源。 + +我们在 [Jaeger 协议文档](/user-guide/query-data/jaeger.md)里对此做了具体描述。 + +### SQL + +Trace 数据也可以通过 SQL 查询。默认 Trace 数据会写入 `opentelemetry_traces` 表中, +这个表名也可以在写入时通过 `x-greptime-trace-table-name` 来指定。通过 SQL 查询: + +```sql +SELECT * FROM public.opentelemetry_traces \G +``` + +输出的例子如下: + +``` +*************************** 1. row *************************** + timestamp: 2025-04-02 09:58:43.822229 + timestamp_end: 2025-04-02 09:58:43.822352 + duration_nano: 123000 + parent_span_id: NULL + trace_id: 1948380e459f4ca69bb4f4274b5db7ba + span_id: f179c8dc2171a0a0 + span_kind: SPAN_KIND_CLIENT + span_name: lets-go + span_status_code: STATUS_CODE_UNSET + span_status_message: + trace_state: + scope_name: telemetrygen + scope_version: + service_name: telemetrygen +span_attributes.net.sock.peer.addr: 1.2.3.4 + span_attributes.peer.service: telemetrygen-server + span_events: [] + span_links: [] +... +``` + +在下一节[数据模型](./data-model.md) 中我们会对这个表结构做详细介绍。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/vectors/vector-type.md b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/vectors/vector-type.md new file mode 100644 index 0000000000..eb31a287fe --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-1.0/user-guide/vectors/vector-type.md @@ -0,0 +1,99 @@ +--- +keywords: [向量, 数据类型, AI 应用, 特征表示, 相似度计算, GreptimeDB, 向量存储, 向量计算] +description: 介绍了向量数据类型在 GreptimeDB 中的定义、写入和计算方法,适用于 AI 应用中的特征表示和相似度计算。 +--- + +# 向量数据类型 + +## 概述 + +在人工智能领域,向量是一种重要的数据类型,用于表示数据集中的特征或者样本。向量可以用于许多机器学习和深度学习算法中,如推荐系统、自然语言处理和图像识别。引入向量类型后,GreptimeDB 可以更有效地支持这些 AI 应用,提供强大的向量存储和计算能力。 + +## 基本介绍 + +在 GreptimeDB 中,向量表示为固定维度的 Float32(32 位浮点数)数组。创建向量类型列时,必须指定向量的维度,并且维度在定义后不能更改。 + +## 定义向量类型列 + +在 SQL 中,可以通过以下语法来定义包含向量类型的表。需要注意的是,维度 `` 必须是一个正整数,用于定义向量的长度。 + +```sql +CREATE TABLE ( + ... + VECTOR() +); +``` + +例如,定义一个具有维度 3 的向量类型列的表: + +```sql +CREATE TABLE vecs ( + ts TIMESTAMP TIME INDEX, + vec_col VECTOR(3) +); +``` + +## 向量写入 + +在 GreptimeDB 中,你可以通过多种方式将向量数据写入数据库。最简单的方法是使用字符串形式,并通过隐式转换将其存储为向量。字符串需要用方括号 `[]` 包围。以下是使用隐式转换的 SQL 示例: + +```sql +INSERT INTO
() VALUES +('[, , ...]'), +('[, , ...]'), +... +('[, , ...]'); +``` + +例如,插入 3 个三维向量: + +```sql +INSERT INTO vecs (ts, vec_col) VALUES +('2024-11-18 00:00:01', '[1.0, 2.0, 3.0]'), +('2024-11-18 00:00:02', '[4.0, 5.0, 6.0]'), +('2024-11-18 00:00:03', '[7.0, 8.0, 9.0]'); +``` + +如果你希望更明确地控制数据转换,可以使用 `parse_vec` 函数来显式地解析字符串为向量: + +```sql +INSERT INTO vecs (ts, vec_col) VALUES +('2024-11-18 00:00:01', parse_vec('[1.0, 2.0, 3.0]')), +('2024-11-18 00:00:02', parse_vec('[4.0, 5.0, 6.0]')), +('2024-11-18 00:00:03', parse_vec('[7.0, 8.0, 9.0]')); +``` + +## 向量计算 + +GreptimeDB 支持多种向量函数,用于计算向量之间的相似度,包括 `vec_l2sq_distance`、`vec_cos_distance` 和 `vec_dot_product`。这些函数在 AI 应用中用于搜索最接近的内容。 + +可以使用以下 SQL 格式执行向量计算: + +```sql +SELECT (, ) FROM
; +``` + +例如,若要查找与给定向量 `[5.0, 5.0, 5.0]` 具有最小平方欧几里得距离的向量,并显示它们之间的距离,可以使用如下查询: + +```sql +SELECT vec_to_string(vec_col), vec_l2sq_distance(vec_col, '[5.0, 5.0, 5.0]') AS distance +FROM vecs +ORDER BY distance; +``` + +执行此查询后,您将得到类似以下的结果: + +``` ++-----------------------------+----------+ +| vec_to_string(vecs.vec_col) | distance | ++-----------------------------+----------+ +| [4,5,6] | 2 | +| [1,2,3] | 29 | +| [7,8,9] | 29 | ++-----------------------------+----------+ +3 rows in set (0.01 sec) +``` + +通过这种方式,GreptimeDB 可以帮助你快速识别和查找相似的数据向量,为 AI 应用提供强大的支持。 + +更多关于向量计算函数的信息,请参阅[向量函数参考文档](/reference/sql/functions/vector.md)。 diff --git a/variables/variables-1.0.ts b/variables/variables-1.0.ts new file mode 100644 index 0000000000..b2a1dc71a9 --- /dev/null +++ b/variables/variables-1.0.ts @@ -0,0 +1,10 @@ +export const variables = { + greptimedbVersion: 'v1.0.0', + prometheusVersion: 'v2.52.0', + nodeExporterVersion: 'v1.8.0', + goSdkVersion: 'v0.6.2', + javaSdkVersion: '0.15.0', + debugPodVersion: '20250421-94c4b8d', + etcdChartVersion: "12.0.8", + etcdImageVersion: "3.6.1-debian-12-r3" +}; diff --git a/versioned_docs/version-0.17/index.md b/versioned_docs/version-0.17/index.md index f907ebb3e3..36b5ac1553 100644 --- a/versioned_docs/version-0.17/index.md +++ b/versioned_docs/version-0.17/index.md @@ -27,7 +27,6 @@ Before getting started, please read the following documents that include instruc - [Getting Started][1]: Provides an introduction to GreptimeDB for those who are new to it, including installation and database operations. - [User Guide][2]: For application developers to use GreptimeDB or build custom integration. -- [GreptimeCloud][6]: For users of GreptimeCloud to get started. - [Contributor Guide][3]: For contributors interested in learning more about the technical details and enhancing GreptimeDB. - [Roadmap][7]: The latest GreptimeDB roadmap. - [Release Notes][4]: Presents all historical version release notes. diff --git a/versioned_docs/version-1.0/contributor-guide/datanode/data-persistence-indexing.md b/versioned_docs/version-1.0/contributor-guide/datanode/data-persistence-indexing.md new file mode 100644 index 0000000000..3d28c553b5 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/datanode/data-persistence-indexing.md @@ -0,0 +1,84 @@ +--- +keywords: [data persistence, indexing, SST file format, Apache Parquet, inverted index, OpenDAL] +description: Explanation of data persistence and indexing in GreptimeDB, including SST file format, indexing methods, and the use of OpenDAL. +--- + +# Data Persistence and Indexing + +Similar to all LSMT-like storage engines, data in MemTables is persisted to durable storage, for example, the local disk file system or object storage service. GreptimeDB adopts [Apache Parquet][1] as its persistent file format. + +## SST File Format + +Parquet is an open source columnar format that provides fast data querying and has already been adopted by many projects, such as Delta Lake. + +Parquet has a hierarchical structure like "row groups-columns-data pages". Data in a Parquet file is horizontally partitioned into row groups, in which all values of the same column are stored together to form a data page. Data page is the minimal storage unit. This structure greatly improves performance. + +First, clustering data by column makes file scanning more efficient, especially when only a few columns are queried, which is very common in analytical systems. + +Second, data of the same column tends to be homogeneous which helps with compression when apply techniques like dictionary and Run-Length Encoding (RLE). + +Parquet file format + +## Data Persistence + +GreptimeDB provides a configuration item `storage.flush.global_write_buffer_size`, which is flush threshold of the total memory usage for all MemTables. + +When the size of data buffered in MemTables reaches that threshold, GreptimeDB will pick MemTables and flush them to SST files. + +## Indexing Data in SST Files + +Apache Parquet file format provides inherent statistics in headers of column chunks and data pages, which are used for pruning and skipping. + +Column chunk header + +For example, in the above Parquet file, if you want to filter rows where `name` = `Emily`, you can easily skip row group 0 because the max value for `name` field is `Charlie`. This statistical information reduces IO operations. + +## Index Files + +For each SST file, GreptimeDB not only maintains an internal index but also generates a separate file to store the index structures specific to that SST file. + +The index files utilize the [Puffin][3] format, which offers significant flexibility, allowing for the storage of additional metadata and supporting a broader range of index structures. + +![Puffin](/puffin.png) + +Currently, the inverted index is the first supported index structure, and it is stored within the index file as a Blob. + +## Inverted Index + +In version 0.7, GreptimeDB introduced the inverted index to accelerate queries. + +The inverted index is a common index structure used for full-text searches, mapping each word in the document to a list of documents containing that word. Greptime has adopted this technology, which originates from search engines, for use in the time series databases. + +Search engines and time series databases operate in separate domains, yet the principle behind the applied inverted index technology is similar. This similarity requires some conceptual adjustments: +1. Term: In GreptimeDB, it refers to the column value of the time series. +2. Document: In GreptimeDB, it refers to the data segment containing multiple time series. + +The inverted index enables GreptimeDB to skip data segments that do not meet query conditions, thus improving scanning efficiency. + +![Inverted index searching](/inverted-index-searching.png) + +For instance, the query above uses the inverted index to identify data segments where `job` equals `apiserver`, `handler` matches the regex `.*users`, and `status` matches the regex `4...`. It then scans these data segments to produce the final results that meet all conditions, significantly reducing the number of IO operations. + +### Inverted Index Format + +![Inverted index format](/inverted-index-format.png) + +GreptimeDB builds inverted indexes by column, with each inverted index consisting of an FST and multiple Bitmaps. + +The FST (Finite State Transducer) enables GreptimeDB to store mappings from column values to Bitmap positions in a compact format and provides excellent search performance and supports complex search capabilities (such as regular expression matching). The Bitmaps maintain a list of data segment IDs, with each bit representing a data segment. + +### Index Data Segments + +GreptimeDB divides an SST file into multiple indexed data segments, with each segment housing an equal number of rows. This segmentation is designed to optimize query performance by scanning only the data segments that match the query conditions. + +For example, if a data segment contains 1024 rows and the list of data segments identified through the inverted index for the query conditions is `[0, 2]`, then only the 0th and 2nd data segments in the SST file—from rows 0 to 1023 and 2048 to 3071, respectively—need to be scanned. + +The number of rows in a data segment is controlled by the engine option `index.inverted_index.segment_row_count`, which defaults to `1024`. A smaller value means more precise indexing and often results in better query performance but increases the cost of index storage. By adjusting this option, a balance can be struck between storage costs and query performance. + +## Unified Data Access Layer: OpenDAL + +GreptimeDB uses [OpenDAL][2] to provide a unified data access layer, thus, the storage engine does not need to interact with different storage APIs, and data can be migrated to cloud-based storage like AWS S3 seamlessly. + +[1]: https://parquet.apache.org +[2]: https://github.com/datafuselabs/opendal +[3]: https://iceberg.apache.org/puffin-spec diff --git a/versioned_docs/version-1.0/contributor-guide/datanode/metric-engine.md b/versioned_docs/version-1.0/contributor-guide/datanode/metric-engine.md new file mode 100644 index 0000000000..cb4eb619c6 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/datanode/metric-engine.md @@ -0,0 +1,44 @@ +--- +keywords: [Metric engine, small tables, logical table, physical table, storage optimization] +description: Overview of the Metric engine in GreptimeDB, its concepts, architecture, and design for handling small tables. +--- + +# Metric Engine + +## Overview + +The `Metric` engine is a component of GreptimeDB, and it's an implementation of the storage engine. It mainly targets scenarios with a large number of small tables for observable metrics. + +Its main feature is to use synthetic physical wide tables to store a large amount of small table data, achieving effects such as reuse of the same column and metadata. This reduces storage overhead for small tables and improves columnar compression efficiency. The concept of a table becomes even more lightweight under the `Metric` engine. + +## Concepts + +The `Metric` engine introduces two new concepts: "logical table" and "physical table". From the user's perspective, logical tables are exactly like ordinary ones. From a storage point-of-view, physical Regions are just regular Regions. + +### Logical Table + +A logical table refers to user-defined tables. Just like any other ordinary table, its definition includes the name of the table, column definitions, index definitions etc. All operations such as queries or write-ins by users are based on these logical tables. Users don't need to worry about differences between logical and ordinary tables during usage. + +From an implementation standpoint, a logical table is virtual; it doesn't directly read or write physical data but maps read/write requests into corresponding requests for physical tables in order to implement data storage and querying. + +### Physical Table + +A physical table is a table that actually stores data, possessing several physical Regions defined by partition rules. + +## Architecture and Design + +The main design architecture of the `Metric` engine is as follows: + +![Arch](/metric-engine-arch.png) + +In the current version implementation, the `Metric` engine reuses the `Mito` engine to achieve storage and query capabilities for physical data. It also provides access to both physical tables and logical tables simultaneously. + +Regarding partitioning, logical tables have identical partition rules and Region distribution as physical tables. This makes sense because the data of logical tables are directly stored in physical tables, so their partition rules are consistent. + +Concerning routing metadata, the routing address of a logical table is a logical address - what its corresponding physical table is - then through this physical table for secondary routing to obtain the real physical address. This indirect routing method can significantly reduce the number of metadata modifications required when Region migration scheduling occurs in Metric engines. + +Operationally speaking, The `Metric` engine only supports limited operations on physical tables to prevent misoperations such as prohibiting writing into or deleting from a physical table which could affect user's logic-table data. Generally speaking, users can consider that they have read-only access to these physical tables. + +To improve performance during simultaneous DDL (Data Definition Language) operations on many tables, the 'Metric' engine has introduced some batch DDL operations. These batch DDL operations can merge lots of DDL actions into one request thereby reducing queries and modifications times for metadata thus enhancing performance. This feature is particularly beneficial in scenarios such as the automatic creation requests brought about by large amounts of metrics during Prometheus Remote Write cold start-up, as well as the modification requests for numerous route-tables mentioned earlier during migration of many physical regions. + +Apart from physical data regions belonging to physical tables, the 'Metric' engine creates an additional metadata region physically for each individual physical data region used in storing some metadata needed by itself while maintaining mapping and other states. This metadata includes the mapping relationship between logical tables and physical tables, the mapping relationship between logical columns and physical columns etc. diff --git a/versioned_docs/version-1.0/contributor-guide/datanode/overview.md b/versioned_docs/version-1.0/contributor-guide/datanode/overview.md new file mode 100644 index 0000000000..449b7ba8f2 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/datanode/overview.md @@ -0,0 +1,34 @@ +--- +keywords: [Datanode, region server, data storage, gRPC service, heartbeat task, region manager] +description: Overview of Datanode in GreptimeDB, its responsibilities, components, and interaction with other parts of the system. +--- + +# Datanode + +## Introduction + +`Datanode` is mainly responsible for storing the actual data for GreptimeDB. As we know, in GreptimeDB, +a `table` can have one or more `Region`s, and `Datanode` is responsible for managing the reading and writing +of these `Region`s. `Datanode` is not aware of `table` and can be considered as a `region server`. Therefore, +`Frontend` and `Metasrv` operate `Datanode` at the granularity of `Region`. + +![Datanode](/datanode.png) + +## Components + +A `Datanode` contains all the components needed for a `region server`. Here we list some of the vital parts: + +- A gRPC service is provided for reading and writing region data, and `Frontend` uses this service + to read and write data from `Datanode`s. +- An HTTP service, through which you can obtain metrics, configuration information, etc., of the current node. +- `Heartbeat Task` is used to send heartbeat to the `Metasrv`. The heartbeat plays a crucial role in the + distributed architecture of GreptimeDB and serves as a basic communication channel for distributed coordination. + The upstream heartbeat messages contain important information such as the workload of a `Region`. If the + `Metasrv `has made scheduling(such as `Region` migration) decisions, it will send instructions to the + `Datanode` via downstream heartbeat messages. +- The `Datanode` does not include components like the `Physical Planner`, `Optimizer`, etc. (these are placed in + the `Frontend`). The user's query requests for one or more `Table`s will be transformed into `Region` query + requests in the `Frontend`. The `Datanode` is responsible for handling these `Region` query requests. +- A `Region Manager` is used to manage all `Region`s on a `Datanode`. +- GreptimeDB supports a pluggable multi-engine architecture, with existing engines including `File Engine` and + `Mito Engine`. diff --git a/versioned_docs/version-1.0/contributor-guide/datanode/python-scripts.md b/versioned_docs/version-1.0/contributor-guide/datanode/python-scripts.md new file mode 100644 index 0000000000..98909142a6 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/datanode/python-scripts.md @@ -0,0 +1,35 @@ +--- +keywords: [Python scripts, data analysis, CPython backend, RustPython interpreter, RecordBatch] +description: Guide on using Python scripts for data analysis in GreptimeDB, including backend options and setup instructions. +--- + +# Python Scripts + +## Introduction + +Python scripts are methods for analyzing data in GreptimeDB, +by running it in the database directly instead of fetching all the data from the database and running it locally. +This approach saves a lot of data transfer costs. +The image below depicts how the script works. +The `RecordBatch` (which is basically a column in a table with type and nullability metadata) +can come from anywhere in the database, +and the returned `RecordBatch` can be annotated in Python grammar to indicate its metadata, +such as type or nullability. +The script will do its best to convert the returned object to a `RecordBatch`, +whether it is a Python list, a `RecordBatch` computed from parameters, +or a constant (which is extended to the same length as the input arguments). + +![Python Coprocessor](/python-coprocessor.png) + +## Two optional backends + +### CPython Backend powered by PyO3 + +This backend is powered by [PyO3](https://pyo3.rs/v0.18.1/), enabling the use of your favourite Python libraries (such as NumPy, Pandas, etc.) and allowing Conda to manage your Python environment. + +But using it also involves some complications. You must set up the correct Python shared library, which can be a bit challenging. In general, you just need to install the `python-dev` package. However, if you are using Homebrew to install Python on macOS, you must create a proper soft link to `Library/Frameworks/Python.framework`. Detailed instructions on using PyO3 crate with different Python Version can be found [here](https://pyo3.rs/v0.18.1/building_and_distribution#configuring-the-python-version) + +### Embedded RustPython Interpreter + +An experiment [python interpreter](https://github.com/RustPython/RustPython) to run +the coprocessor script, it supports Python 3.10 grammar. You can use all the very Python syntax, see [User Guide/Python Coprocessor](/user-guide/python-scripts/overview.md) for more! diff --git a/versioned_docs/version-1.0/contributor-guide/datanode/query-engine.md b/versioned_docs/version-1.0/contributor-guide/datanode/query-engine.md new file mode 100644 index 0000000000..2d1ad8a882 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/datanode/query-engine.md @@ -0,0 +1,66 @@ +--- +keywords: [query engine, Apache DataFusion, logical plan, physical plan, data representation, indexing] +description: Overview of GreptimeDB's query engine, its architecture, data representation, indexing, and extensibility. +--- + +# Query Engine + +## Introduction + +GreptimeDB's query engine is built on [Apache DataFusion][1] (subproject under [Apache +Arrow][2]), a brilliant query engine written in Rust. It provides a set of well functional components from +logical plan, physical plan and the execution runtime. Below explains how each component is orchestrated and their positions during execution. + +![Execution Procedure](/execution-procedure.png) + +The entry point is the logical plan, which is used as the general intermediate representation of a +query or execution logic etc. Two noticeable sources of logical plan are from: 1. the user query, like +SQL through SQL parser and planner; 2. the Frontend's distributed query, which is explained in details in the following section. + +Next is the physical plan, or the execution plan. Unlike the logical plan which is a big +enumeration containing all the logical plan variants (except the special extension plan node), the +physical plan is in fact a trait that defines a group of methods invoked during +execution. All data processing logics are packed in corresponding structures that +implement the trait. They are the actual operations performed on the data, like +aggregator `MIN` or `AVG`, and table scan `SELECT ... FROM`. + +The optimization phase which improves execution performance by transforming both logical and physical plans, is now all based on rules. It is also called, "Rule Based Optimization". Some of the rules are DataFusion native and others are customized in Greptime DB. In the future, we plan to add more +rules and leverage the data statistics for Cost Based Optimization/CBO. + +The last phase "execute" is a verb, stands for the procedure that reads data from storage, performs +calculations and generates the expected results. Although it's more abstract than previously mentioned concepts, you can just +simply imagine it as executing a Rust async function. And it's indeed a future (stream). + +`EXPLAIN [VERBOSE] ` is very useful if you want to see how your SQL is represented in the logical or physical plan. + +## Data Representation + +GreptimeDB uses [Apache Arrow][2] as the in-memory data representation. It's column-oriented, in +cross-platform format, and also contains many high-performance data operators. These features +make it easy to share data in many different environments and implement calculation logic. + +## Indexing + +In time series data, there are two important dimensions: timestamp and tag columns (or like +primary key in a general relational database). GreptimeDB groups data in time buckets, so it's efficient +to locate and extract data within the expected time range at a very low cost. The mainly used persistent file format [Apache Parquet][3] in GreptimeDB helps a lot -- it +provides multi-level indices and filters that make it easy to prune data during querying. In the future, we +will make more use of this feature, and develop our separated index to handle more complex use cases. + +## Extensibility + + + +Extending operations in GreptimeDB is extremely simple. You can implement your operator like [this][5]. + +## Distributed Execution + +Covered in [Distributed Querying][6]. + +[1]: https://github.com/apache/arrow-datafusion +[2]: https://arrow.apache.org/ +[3]: https://parquet.apache.org +[4]: python-scripts.md +[5]: https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-write-aggregate-function.md +[6]: ../frontend/distributed-querying.md diff --git a/versioned_docs/version-1.0/contributor-guide/datanode/storage-engine.md b/versioned_docs/version-1.0/contributor-guide/datanode/storage-engine.md new file mode 100644 index 0000000000..cc33ef94d9 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/datanode/storage-engine.md @@ -0,0 +1,65 @@ +--- +keywords: [storage engine, LSMT, Mito engine, data model, architecture, compaction] +description: Overview of the storage engine in GreptimeDB, its architecture, components, and data model. +--- + +# Storage Engine + +## Introduction + +The `storage engine` is responsible for storing the data of the database. Mito, based on [LSMT][1] (Log-structured Merge-tree), is the storage engine we use by default. We have made significant optimizations for handling time-series data scenarios, so mito engine is not suitable for general purposes. + +## Architecture + +The picture below shows the architecture and process procedure of the storage engine. + +![Architecture](/storage-engine-arch.png) + +The architecture is the same as a traditional LSMT engine: + +- [WAL][2] + - Guarantees high durability for data that is not yet being flushed. + - Based on the `Log Store` API, thus it doesn't care about the underlying storage + media. + - Log records of the WAL can be stored in the local disk, or a distributed log service which + implements the `Log Store` API. +- Memtables: + - Data is written into the `active memtable`, aka `mutable memtable` first. + - When a `mutable memtable` is full, it will be changed to a `read-only memtable`, aka `immutable memtable`. +- SST + - The full name of SST, aka SSTable is `Sorted String Table`. + - `Immutable memtable` is flushed to persistent storage and produces an SST file. +- Compactor + - Small `SST` is merged into large `SST` by the compactor via compaction. + - The default compaction strategy is [TWCS][3]. +- Manifest + - The manifest stores the metadata of the engine, such as the metadata of the `SST`. +- Cache + - Speed up queries. + +[1]: https://en.wikipedia.org/wiki/Log-structured_merge-tree +[2]: https://en.wikipedia.org/wiki/Write-ahead_logging +[3]: https://cassandra.apache.org/doc/latest/cassandra/operating/compaction/twcs.html + +## Data Model + +The data model provided by the storage engine is between the `key-value` model and the tabular model. + +```txt +tag-1, ..., tag-m, timestamp -> field-1, ..., field-n +``` + +Each row of data contains multiple tag columns, one timestamp column, and multiple field columns. +- `0 ~ m` tag columns + - Tag columns can be nullable. + - Specified during table creation using `PRIMARY KEY`. +- Must include one timestamp column + - Timestamp column cannot be null. + - Specified during table creation using `TIME INDEX`. +- `0 ~ n` field columns + - Field columns can be nullable. +- Data is sorted by tag columns and timestamp column. + +### Region + +Data in the storage engine is stored in `regions`, which are logical isolated storage units within the engine. Rows within a `region` must have the same `schema`, which defines the tag columns, timestamp column, and field columns within the `region`. The data of tables in the database is stored in one or multiple `regions`. diff --git a/versioned_docs/version-1.0/contributor-guide/datanode/wal.md b/versioned_docs/version-1.0/contributor-guide/datanode/wal.md new file mode 100644 index 0000000000..7001f93b93 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/datanode/wal.md @@ -0,0 +1,36 @@ +--- +keywords: [write-ahead logging, WAL, data durability, LSMT, synchronous flush, asynchronous flush] +description: Introduction to Write-Ahead Logging (WAL) in GreptimeDB, its purpose, architecture, and operational modes. +--- + +# Write-Ahead Logging + +## Introduction + +Our storage engine is inspired by the Log-structured Merge Tree (LSMT). Mutating operations are +applied to a MemTable instead of persisting to disk, which significantly improves performance but +also brings durability-related issues, especially when the Datanode crashes unexpectedly. Similar +to all LSMT-like storage engines, GreptimeDB uses a write-ahead log (WAL) to ensure data durability +and is safe from crashing. + +WAL is an append-only file group. All `INSERT`, `UPDATE` and `DELETE` operations are transformed into +operation entries and then appended to WAL. Once operation entries are persisted to the underlying +file, the operation can be further applied to MemTable. + +When the Datanode restarts, operation entries in WAL are replayed to reconstruct the correct +in-memory state. + +![WAL in Datanode](/wal.png) + +## Namespace + +Namespace of WAL is used to separate entries from different tables (different regions). Append and +read operations must provide a Namespace. Currently, region ID is used as the Namespace, because +each region has a MemTable that needs to be reconstructed when Datanode restarts. + +## Synchronous/Asynchronous flush + +By default, appending to WAL is asynchronous, which means the writer will not wait until entries are +flushed to disk. This setting provides higher performance, but may lose data when running host shutdown unexpectedly. In the other hand, synchronous flush provides higher durability at the cost of performance. + +In v0.4 version, the new region worker architecture can use batching to alleviate the overhead of sync flush. diff --git a/versioned_docs/version-1.0/contributor-guide/flownode/arrangement.md b/versioned_docs/version-1.0/contributor-guide/flownode/arrangement.md new file mode 100644 index 0000000000..aed75af777 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/flownode/arrangement.md @@ -0,0 +1,20 @@ +--- +keywords: [arrangement component, state storage, update streams, key-value pairs, querying and updating] +description: Details on the arrangement component in Flownode, which stores state and update streams for querying and updating. +--- + +# Arrangement + +Arrangement stores the state in the dataflow's process. It stores the streams of update flows for further querying and updating. + +The arrangement essentially stores key-value pairs with timestamps to mark their change time. + +Internally, the arrangement receives tuples like +`((Key Row, Value Row), timestamp, diff)` and stores them in memory. One can query key-value pairs at a certain time using the `get(now: Timestamp, key: Row)` method. +The arrangement also assumes that everything older than a certain time (also known as the low watermark) has already been ingested to the sink tables and does not keep a history for them. + +:::tip NOTE + +The arrangement allows for the removal of keys by setting the `diff` to -1 in incoming tuples. Moreover, if a row has been previously added to the arrangement and the same key is inserted with a different value, the original value is overwritten with the new value. + +::: diff --git a/versioned_docs/version-1.0/contributor-guide/flownode/batching_mode.md b/versioned_docs/version-1.0/contributor-guide/flownode/batching_mode.md new file mode 100644 index 0000000000..37fc22b36f --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/flownode/batching_mode.md @@ -0,0 +1,74 @@ +--- +keywords: [streaming process, flow management, Flownode components, Flownode limitations, batching mode] +description: Overview of Flownode's batching mode, a component providing continuous data aggregation capabilities to the database, including its architecture and query execution flow. +--- + +# Flownode Batching Mode Developer Guide + +This guide provides a brief overview of the batching mode in `flownode`. It's intended for developers who want to understand the internal workings of this mode. + +## Overview + +The batching mode in `flownode` is designed for continuous data aggregation. It periodically executes a user-defined SQL query over small, discrete time windows. This is in contrast to a streaming mode where data is processed as it arrives. + +The core idea is to: +1. Define a `flow` with a SQL query that aggregates data from a source table into a sink table. +2. The query typically includes a time window function (e.g., `date_bin`) on a timestamp column. +3. When new data is inserted into the source table, the system marks the corresponding time windows as "dirty." +4. A background task periodically wakes up, identifies these dirty windows, and re-runs the aggregation query for those specific time ranges. +5. The results are then inserted into the sink table, effectively updating the aggregated view. + +## Architecture + +The batching mode consists of several key components that work together to achieve this continuous aggregation. As shown in the diagram below: + +![batching mode architecture](/batching_mode_arch.png) + +### `BatchingEngine` + +The `BatchingEngine` is the heart of the batching mode. It's a central component that manages all active flows. Its primary responsibilities are: + +- **Task Management**: It maintains a map of `FlowId` to `BatchingTask`. It handles the creation, deletion, and retrieval of these tasks. +- **Event Dispatching**: When new data arrives (via `handle_inserts_inner`) or when time windows are explicitly marked as dirty (`handle_mark_dirty_time_window`), the `BatchingEngine` identifies which flows are affected and forwards the information to the corresponding `BatchingTask`s. + +### `BatchingTask` + +A `BatchingTask` represents a single, independent data flow. Each task is associated with one `flow` definition and runs in its own asynchronous loop. + +- **Configuration (`TaskConfig`)**: This struct holds the immutable configuration for a flow, such as the SQL query, source and sink table names, and time window expression. +- **State (`TaskState`)**: This contains the dynamic, mutable state of the task, most importantly the `DirtyTimeWindows`. +- **Execution Loop**: The task runs an infinite loop (`start_executing_loop`) that: + 1. Checks for a shutdown signal. + 2. Waits for a scheduled interval or until it's woken up. + 3. Generates a new query plan (`gen_insert_plan`) based on the current set of dirty time windows. + 4. Executes the query (`execute_logical_plan`) against the database. + 5. Cleans up the processed dirty windows. + +### `TaskState` and `DirtyTimeWindows` + +- **`TaskState`**: This struct tracks the runtime state of a `BatchingTask`. It includes `dirty_time_windows`, which is crucial for determining what work needs to be done. +- **`DirtyTimeWindows`**: This is a key data structure that keeps track of which time windows have received new data since the last query execution. It stores a set of non-overlapping time ranges. When a task's execution loop runs, it consults this structure to build a `WHERE` clause that filters the source table for only the dirty time windows. + +### `TimeWindowExpr` + +The `TimeWindowExpr` is a helper utility for dealing with time window functions like `TUMBLE`. + +- **Evaluation**: It can take a timestamp and evaluate the time window expression to determine the start and end of the window that the timestamp falls into. +- **Window Size**: It can also determine the size (duration) of the time window from the expression. + +This is essential for both marking windows as dirty and for generating the correct filter conditions when querying the source table. + +## Query Execution Flow + +Here's a simplified step-by-step walkthrough of how a query is executed in batch mode: + +1. **Data Ingestion**: New data is written to a source table. +2. **Marking Dirty**: The `BatchingEngine` receives a notification about the new data. It uses the `TimeWindowExpr` associated with each relevant flow to determine which time windows are affected by the new data points. These windows are then added to the `DirtyTimeWindows` set in the corresponding `TaskState`. +3. **Task Wake-up**: The `BatchingTask`'s execution loop wakes up, either due to its periodic schedule or because it was notified of a large backlog of dirty windows. +4. **Plan Generation**: The task calls `gen_insert_plan`. This method: + - Inspects the `DirtyTimeWindows`. + - Generates a series of `OR`'d `WHERE` clauses (e.g., `(ts >= 't1' AND ts < 't2') OR (ts >= 't3' AND ts < 't4') ...`) that cover the dirty windows. + - Rewrites the original SQL query to include this new filter, ensuring that only the necessary data is processed. +5. **Execution**: The modified query plan is sent to the `Frontend` for execution. The database processes the aggregation on the filtered data. +6. **Upsert**: The results are inserted into the sink table. The sink table is typically defined with a primary key that includes the time window column, so new results for an existing window will overwrite (upsert) the old ones. +7. **State Update**: The `DirtyTimeWindows` set is cleared of the windows that were just processed. The task then goes back to sleep until the next interval. \ No newline at end of file diff --git a/versioned_docs/version-1.0/contributor-guide/flownode/dataflow.md b/versioned_docs/version-1.0/contributor-guide/flownode/dataflow.md new file mode 100644 index 0000000000..000a65edb3 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/flownode/dataflow.md @@ -0,0 +1,17 @@ +--- +keywords: [dataflow module, SQL query transformation, execution plan, DAG, map and reduce operations] +description: Explanation of the dataflow module in Flownode, its operations, internal data handling, and future enhancements. +--- + +# Dataflow + +The `dataflow` module (see `flow::compute` module) is the core computing module of `flow`. +It takes a SQL query and transforms it into flow's internal execution plan. +This execution plan is then rendered into an actual dataflow, which is essentially a directed acyclic graph (DAG) of functions with input and output ports. +The dataflow is triggered to run when needed. + +Currently, this dataflow only supports `map` and `reduce` operations. Support for `join` operations will be added in the future. + +Internally, the dataflow handles data in row format, using a tuple `(row, time, diff)`. Here, `row` represents the actual data being passed, which may contain multiple `Value` objects. +`time` is the system time which tracks the progress of the dataflow, and `diff` typically represents the insertion or deletion of the row (+1 or -1). +Therefore, the tuple represents the insert/delete operation of the `row` at a given system `time`. \ No newline at end of file diff --git a/versioned_docs/version-1.0/contributor-guide/flownode/overview.md b/versioned_docs/version-1.0/contributor-guide/flownode/overview.md new file mode 100644 index 0000000000..1a0be544d2 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/flownode/overview.md @@ -0,0 +1,26 @@ +--- +keywords: [streaming process, flow management, standalone mode, Flownode components, Flownode limitations] +description: Overview of Flownode, a component providing streaming process capabilities to the database, including its components and current limitations. +--- + +# Flownode + +## Introduction + + +`Flownode` provides a simple streaming process (known as `flow`) ability to the database. +`Flownode` manages `flows` which are tasks that receive data from the `source` and send data to the `sink`. + +`Flownode` support both `standalone` and `distributed` mode. In `standalone` mode, `Flownode` runs in the same process as the database. In `distributed` mode, `Flownode` runs in a separate process and communicates with the database through the network. + +There are two execution modes for a flow: +- **Streaming Mode**: The original mode where data is processed as it arrives. +- **Batching Mode**: A newer mode designed for continuous data aggregation. It periodically executes a user-defined SQL query over small, discrete time windows. All aggregation queries now use this mode. For more details, see the [Batching Mode Developer Guide](./batching_mode.md). + +## Components + +A `Flownode` contains all the components needed to execute a flow. The specific components involved depend on the execution mode (Streaming vs. Batching). At a high level, the key parts are: + +- **Flow Manager**: A central component responsible for managing the lifecycle of all flows. +- **Task Executor**: The runtime environment where the flow logic is executed. In streaming mode, this is typically a `FlowWorker`; in batching mode, it's a `BatchingTask`. +- **Flow Task**: Represents a single, independent data flow, containing the logic for transforming data from a source to a sink. \ No newline at end of file diff --git a/versioned_docs/version-1.0/contributor-guide/frontend/distributed-querying.md b/versioned_docs/version-1.0/contributor-guide/frontend/distributed-querying.md new file mode 100644 index 0000000000..21ee07d7e8 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/frontend/distributed-querying.md @@ -0,0 +1,33 @@ +--- +keywords: [distributed querying, dist planner, dist plan, logical plan, substrait format] +description: Describes the process of distributed querying in GreptimeDB, focusing on the dist planner and dist plan. +--- + +# Distributed Querying + +Most steps of querying in frontend and datanode are identical. The only difference is that +Frontend have a "special" step in planning phase to make the logical query plan distributed. +Let's reference it as "dist planner" in the following text. + +The modified, distributed logical plan has multiple stages, each of them is executed in different +server node. + +![Frontend query](/frontend-query.png) + +## Dist Planner + +Planner will traverse the input logical plan, and split it into multiple stages by the "[commutativity +rule](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/rfcs/2023-05-09-distributed-planner.md)". + +This rule is under heavy development. At present it will consider things like: +- whether the operator itself is commutative +- how the partition rule is configured +- etc... + +## Dist Plan + +Except the first stage, which have to read data from files in storage. All other stages' leaf node +are actually a gRPC call to its previous stage. + +Sub-plan in a stage is itself a complete logical plan, and can be executed independently without +the follow up stages. The plan is encoded in [substrait format](https://substrait.io). diff --git a/versioned_docs/version-1.0/contributor-guide/frontend/overview.md b/versioned_docs/version-1.0/contributor-guide/frontend/overview.md new file mode 100644 index 0000000000..3a2f63e7ae --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/frontend/overview.md @@ -0,0 +1,44 @@ +--- +keywords: [frontend, proxy, protocol, routing, distributed query, tenant management, authorization, flow control, cloud deployment, endpoints] +description: Overview of GreptimeDB's Frontend component - a stateless proxy service for client requests. +--- + +# Frontend + +The **Frontend** is a stateless service that serves as the entry point for client requests in GreptimeDB. It provides a unified interface for multiple database protocols and acts as a proxy that forwards read/write requests to appropriate Datanodes in the distributed system. + +## Core Functions + +- **Protocol Support**: Multiple database protocols including SQL, PromQL, MySQL, and PostgreSQL. See [Protocols][1] for details +- **Request Routing**: Routes requests to appropriate Datanodes based on metadata +- **Query Distribution**: Splits distributed queries across multiple nodes +- **Response Aggregation**: Combines results from multiple Datanodes +- **Authorization**: Security and access control validation + +## Architecture + +### Key Components +- **Protocol Handlers**: Handle different database protocols +- **Catalog Manager**: Caches metadata from Metasrv to enable efficient request routing and schema validation +- **Dist Planner**: Converts logical plans to distributed execution plans +- **Request Router**: Determines target Datanodes for each request + +### Request Flow + +![request flow](/request_flow.png) + +### Deployment + +The following picture shows a typical deployment of GreptimeDB in the cloud. The `Frontend` instances +form a cluster to serve the requests from clients: + +![frontend](/frontend.png) + +## Details + +- [Table Sharding][2] +- [Distributed Querying][3] + +[1]: /user-guide/protocols/overview.md +[2]: ./table-sharding.md +[3]: ./distributed-querying.md diff --git a/versioned_docs/version-1.0/contributor-guide/frontend/table-sharding.md b/versioned_docs/version-1.0/contributor-guide/frontend/table-sharding.md new file mode 100644 index 0000000000..0684ba0d64 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/frontend/table-sharding.md @@ -0,0 +1,55 @@ +--- +keywords: [table sharding, partition, region, datanode, metasrv, data distribution] +description: Explains how table data in GreptimeDB is sharded and distributed, including the concepts of partition and region. +--- + +# Table Sharding + +The sharding of stored data is essential to any distributed database. This document will describe how table's data in GreptimeDB is being sharded, and distributed. + +## Partition + +For the syntax of creating a partitioned table, please refer to the [Table Sharding](/user-guide/deployments-administration/manage-data/table-sharding.md) section in the User Guide. + +## Region + +The data within a table is logically split after creating partitions. You may ask the question " +how are the data, after being logically partitioned, stored in the GreptimeDB? The answer is in "`Region`"s. + +Each region is corresponding to a partition, and stores the data in the partition. The regions are distributed among +`Datanode`s. Our +`metasrv` will move regions among Datanodes automatically, according to the states of Datanodes. +Also, `metasrv` can split or merge regions according to their data volume or access pattern. + +The relationship between partition and region can be viewed as the following diagram: + +```text + ┌───────┐ + │ │ + │ Table │ + │ │ + └───┬───┘ + │ + Range [Start, end) │ Horizontally Split Data + ┌──────────────────┼──────────────────┐ + │ │ │ + │ │ │ + ┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐ + │ │ │ │ │ │ + │ Partition │ │ Partition │ │ Partition │ + │ │ │ │ │ │ + │ P0 │ │ P1 │ │ Px │ + └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ + │ │ │ + │ │ │ One-to-one mapping of +┌───────┼──────────────────┼───────┐ │ Partition and Region +│ │ │ │ │ +│ ┌─────▼─────┐ ┌─────▼─────┐ │ ┌─────▼─────┐ +│ │ │ │ │ │ │ │ +│ │ Region │ │ Region │ │ │ Region │ +│ │ │ │ │ │ │ │ +│ │ R0 │ │ R1 │ │ │ Ry │ +│ └───────────┘ └───────────┘ │ └───────────┘ +│ │ +└──────────────────────────────────┘ + Could be placed in one Datanode diff --git a/versioned_docs/version-1.0/contributor-guide/getting-started.md b/versioned_docs/version-1.0/contributor-guide/getting-started.md new file mode 100644 index 0000000000..8055cc2a7e --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/getting-started.md @@ -0,0 +1,70 @@ +--- +keywords: [setup, running from source, prerequisites, build dependencies, unit tests] +description: Instructions for setting up and running GreptimeDB from source, including prerequisites, build dependencies, and running unit tests. +--- + +# Getting started + +This page describes how to run GreptimeDB from source in your local environment. + +## Prerequisite + +### System & Architecture + +At the moment, GreptimeDB supports Linux(both amd64 and arm64), macOS (both amd64 and Apple Silicone) and Windows. + +### Build Dependencies + +- [Git](https://git-scm.com/book/en/v2/Getting-Started-The-Command-Line) (optional) +- C/C++ Toolchain: provides essential tools for compiling and linking. This is available either as `build-essential` on ubuntu or a similar name on other platforms. +- Rust ([guide][1]) + - Compile the source code +- Protobuf ([guide][2]) + - Compile the proto file + - Note that the version needs to be >= 3.15. You can check it with `protoc --version` +- Machine: Recommended memory is 16GB or more, or use the [mold](https://github.com/rui314/mold) tool to reduce memory usage during linking. + +[1]: +[2]: + +## Compile and Run + +Start GreptimeDB standalone instance in just a few commands! + +```shell +git clone https://github.com/GreptimeTeam/greptimedb.git +cd greptimedb +cargo run -- standalone start +``` + +Next, you can choose the protocol you like to interact with in GreptimeDB. + +Or if you just want to build the server without running it: + +```shell +cargo build # --release +``` + +The artifacts can be found under `$REPO/target/debug` or `$REPO/target/release`, depending on the build mode (whether the `--release` option is passed) + +## Unit test + +GreptimeDB is well-tested, the entire unit test suite is shipped with source code. To test them, run with [nextest](https://nexte.st/index.html). + +To install nextest using cargo, run: + +```shell +cargo install cargo-nextest --locked +``` + +Or you can check their [docs](https://nexte.st/docs/installation/pre-built-binaries/) for other ways to install. + +After nextest is ready, you can run the test suite with: + +```shell +cargo nextest run +``` + +## Docker + +We also provide pre-build binary via Docker. It's which is available in dockerhub: [https://hub.docker.com/r/greptime/greptimedb](https://hub.docker.com/r/greptime/greptimedb) diff --git a/versioned_docs/version-1.0/contributor-guide/how-to/how-to-trace-greptimedb.md b/versioned_docs/version-1.0/contributor-guide/how-to/how-to-trace-greptimedb.md new file mode 100644 index 0000000000..75941aa0be --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/how-to/how-to-trace-greptimedb.md @@ -0,0 +1,80 @@ +--- +keywords: [tracing, distributed tracing, trace_id, RPC, instrument, span, runtime] +description: Describes how to use Rust's tracing framework in GreptimeDB for distributed tracing, including defining tracing context in RPC, passing it, and instrumenting code. +--- + +# How to trace GreptimeDB + +GreptimeDB uses Rust's [tracing](https://docs.rs/tracing/latest/tracing/) framework for code instrument. For the specific details and usage of tracing, please refer to the official documentation of tracing. + +By transparently transmitting `trace_id` and other information on the entire distributed system, we can record the function call chain of the entire distributed link, know the time of each tracked function take and other related information, so as to monitor the entire system. + +## Define tracing context in RPC + +Because the tracing framework does not natively support distributed tracing, we need to manually pass information such as `trace_id` in the RPC message to correctly identify the function calling relationship. We use standards based on [w3c](https://www.w3.org/TR/trace-context/#traceparent-header-field-values) to encode relevant information into `tracing_context` and attach the message to the RPC header. Mainly defined in: + +- `frontend` interacts with `datanode`: `tracing_context` is defined in [`RegionRequestHeader`](https://github.com/GreptimeTeam/greptime-proto/blob/main/proto/greptime/v1/region/server.proto) +- `frontend` interacts with `metasrv`: `tracing_context` is defined in [`RequestHeader`](https://github.com/GreptimeTeam/greptime-proto/blob/main/proto/greptime/v1/meta/common.proto) +- Client interacts with `frontend`: `tracing_context` is defined in [`RequestHeader`](https://github.com/GreptimeTeam/greptime-proto/blob/main/proto/greptime/v1/common.proto) + +## Pass tracing context in RPC call + +We build a `TracingContext` structure that encapsulates operations related to the tracing context. [Related code](https://github.com/GreptimeTeam/greptimedb/blob/main/src/common/telemetry/src/tracing_context.rs) + +GreptimeDB uses `TracingContext::from_current_span()` to obtain the current tracing context, uses the `to_w3c()` method to encode the tracing context into a w3c-compliant format, and attaches it to the RPC message, so that the tracing context is correctly distributed passed within the component. + +The following example illustrates how to obtain the current tracing context and pass the parameters correctly when constructing the RPC message, so that the tracing context is correctly passed among the distributed components. + + +```rust +let request = RegionRequest { + header: Some(RegionRequestHeader { + tracing_context: TracingContext::from_current_span().to_w3c(), + ..Default::default() + }), + body: Some(region_request::Body::Alter(request)), +}; +``` + +On the receiver side of the RPC message, the tracing context needs to be correctly decoded and used to build the first `span` to trace the function call. For example, the following code will correctly decode the `tracing_context` in the received RPC message using the `TracingContext::from_w3c` method. And use the `attach` method to attach the context message to the newly created `info_span!("RegionServer::handle_read")`, so that the call can be tracked across distributed components. + +```rust +... +let tracing_context = request + .header + .as_ref() + .map(|h| TracingContext::from_w3c(&h.tracing_context)) + .unwrap_or_default(); +let result = self + .handle_read(request) + .trace(tracing_context.attach(info_span!("RegionServer::handle_read"))) + .await?; +... +``` + +## Use `tracing::instrument` to instrument the code + +We use the `instrument` macro provided by tracing to instrument the code. We only need to annotate the `instrument` macro in the function that needs to be instrument. The `instrument` macro will print every function parameter on each function call into the span in the form of `Debug`. For parameters that do not implement the `Debug` trait, or the structure is too large and has too many parameters, resulting in a span that is too large. If you want to avoid these situations, you need to use `skip_all` to skip printing all parameters. + +```rust +#[tracing::instrument(skip_all)] +async fn instrument_function(....) { + ... +} +``` + +## Code instrument across runtime + +Rust's tracing library will automatically handle the nested relationship between instrument functions in the same runtime, but if a function call across the runtime, tracing library cannot automatically trace such calls, and we need to manually pass the context across the runtime. + +```rust +let tracing_context = TracingContext::from_current_span(); +let handle = runtime.spawn(async move { + handler + .handle(query) + .trace(tracing_context.attach(info_span!("xxxxx"))) + ... +}); +``` + +For example, the above code needs to perform tracing across runtimes. We first obtain the current tracing context through `TracingContext::from_current_span()`, create a span in another runtime, and attach the span to the current context, and we are done. The hidden code points that span the runtime are eliminated, and the call chain is correctly traced. \ No newline at end of file diff --git a/versioned_docs/version-1.0/contributor-guide/how-to/how-to-use-tokio-console.md b/versioned_docs/version-1.0/contributor-guide/how-to/how-to-use-tokio-console.md new file mode 100644 index 0000000000..9e95dc395c --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/how-to/how-to-use-tokio-console.md @@ -0,0 +1,35 @@ +--- +keywords: [tokio-console, GreptimeDB, tokio_unstable, build, connect, subscriber] +description: Guides on using tokio-console in GreptimeDB, including building with specific features and connecting to the tokio console subscriber. +--- + +# How to use tokio-console in GreptimeDB + +This document introduces how to use the [tokio-console](https://github.com/tokio-rs/console) in GreptimeDB. + +First, build GreptimeDB with feature `cmd/tokio-console`. Also the `tokio_unstable` cfg must be enabled: + +```bash +RUSTFLAGS="--cfg tokio_unstable" cargo build -F cmd/tokio-console +``` + +Then start GreptimeDB with tokio console binding address config: `--tokio-console-addr`. Remember to run with +the `tokio_unstable` cfg. For example: + +```bash +RUSTFLAGS="--cfg tokio_unstable" greptime --tokio-console-addr="127.0.0.1:6669" standalone start +``` + +Now you can use `tokio-console` to connect to GreptimeDB's tokio console subscriber: + +```bash +tokio-console [TARGET_ADDR] +``` + +"TARGET_ADDR" defaults to "\". + +:::tip Note + +You can refer to [tokio-console](https://github.com/tokio-rs/console) to see the installation of `tokio-console`. + +::: diff --git a/versioned_docs/version-1.0/contributor-guide/how-to/how-to-write-sdk.md b/versioned_docs/version-1.0/contributor-guide/how-to/how-to-write-sdk.md new file mode 100644 index 0000000000..40d0bc3713 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/how-to/how-to-write-sdk.md @@ -0,0 +1,77 @@ +--- +keywords: [gRPC SDK, GreptimeDatabase, Handle, HandleRequests, GreptimeRequest, GreptimeResponse] +description: Explains how to write a gRPC SDK for GreptimeDB, focusing on the GreptimeDatabase service, its methods, and the structure of requests and responses. +--- + +# How to write a gRPC SDK for GreptimeDB + +A GreptimeDB gRPC SDK only needs to handle the writes. The reads are standard SQL and PromQL, can be handled by any JDBC +client or Prometheus client. This is also why GreptimeDB gRPC SDKs are all named +like "`greptimedb-ingester-`". Please make sure your GreptimeDB SDK follow the same naming convention. + +## `GreptimeDatabase` Service + +GreptimeDB defines a custom gRPC service called `GreptimeDatabase`. All you need to do in your SDK are implement it. You +can find its Protobuf +definitions [here](https://github.com/GreptimeTeam/greptime-proto/blob/main/proto/greptime/v1/database.proto). + +The service contains two RPC methods: + +```protobuf +service GreptimeDatabase { + rpc Handle(GreptimeRequest) returns (GreptimeResponse); + + rpc HandleRequests(stream GreptimeRequest) returns (GreptimeResponse); +} +``` + +The `Handle` method is for unary call: when a `GreptimeRequest` is received and processed by a GreptimeDB +server, it responds with a `GreptimeResponse` immediately. + +The `HandleRequests` acts in +a "[Client streaming RPC](https://grpc.io/docs/what-is-grpc/core-concepts/#client-streaming-rpc)" style. It ingests a +stream of `GreptimeRequest`, and handles them on the fly. After all the requests have been handled, it returns a +summarized `GreptimeResponse`. Through `HandleRequests`, we can achieve a very high throughput of requests handling. + +### `GreptimeRequest` + +The `GreptimeRequest` is a Protobuf message defined like this: + +```protobuf +message GreptimeRequest { + RequestHeader header = 1; + oneof request { + InsertRequests inserts = 2; + QueryRequest query = 3; + DdlRequest ddl = 4; + DeleteRequests deletes = 5; + RowInsertRequests row_inserts = 6; + RowDeleteRequests row_deletes = 7; + } +} +``` + +A `RequestHeader` is needed, it includes some context, authentication and others. The "oneof" field contains the request +to the GreptimeDB server. + +Note that we have two types of insertions, one is in the form of "column" (the `InsertRequests`), and the other is " +row" (`RowInsertRequests`). It's generally recommended to use the "row" form, since it's more natural for insertions on +a table, and easier to use. However, if there's a need to insert a large number of columns at once, or there're plenty +of "null" values to insert, the "column" form is better to be used. + +### `GreptimeResponse` + +The `GreptimeResponse` is a Protobuf message defined like this: + +```protobuf +message GreptimeResponse { + ResponseHeader header = 1; + oneof response {AffectedRows affected_rows = 2;} +} +``` + +The `ResponseHeader` contains the response's status code, and error message (if there's any). The "oneof" response only +contains the affected rows for now. + +GreptimeDB has a lot of SDKs now, you can refer to +them [here](https://github.com/GreptimeTeam?q=ingester&type=all&language=&sort=) for some examples. diff --git a/versioned_docs/version-1.0/contributor-guide/metasrv/admin-api.md b/versioned_docs/version-1.0/contributor-guide/metasrv/admin-api.md new file mode 100644 index 0000000000..963e42b67f --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/metasrv/admin-api.md @@ -0,0 +1,262 @@ +--- +keywords: [admin api, health check, leader query, heartbeat, maintenance mode, RESTful API] +description: Details the Admin API for Metasrv, including endpoints for health checks, leader queries, heartbeat data, and maintenance mode. +--- + +# Admin API + +:::tip +Note that all Admin API endpoints in this document listen on Metasrv's `HTTP_PORT`, which defaults to `4000`. +::: + +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. + +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: + +- /health +- /leader +- /heartbeat +- /maintenance + +All these APIs are under the parent resource `/admin`. + +In the following sections, we assume that your metasrv instance is running on localhost port 4000. + +## /health HTTP endpoint + +The `/health` endpoint accepts GET HTTP requests and you can use this endpoint to check the health of your metasrv instance. + +### Definition + +```bash +curl -X GET http://localhost:4000/admin/health +``` + +### Examples + +#### Request + +```bash +curl -X GET http://localhost:4000/admin/health +``` + +#### Response + +```json +OK +``` + +## /leader HTTP endpoint + +The `/leader` endpoint accepts GET HTTP requests and you can use this endpoint to query the leader's addr of your metasrv instance. + +### Definition + +```bash +curl -X GET http://localhost:4000/admin/leader +``` + +### Examples + +#### Request + +```bash +curl -X GET http://localhost:4000/admin/leader +``` + +#### Response + +```json +127.0.0.1:4000 +``` + +## /heartbeat HTTP endpoint + +The `/heartbeat` endpoint accepts GET HTTP requests and you can use this endpoint to query the heartbeat of all datanodes. + +You can also query the heartbeat data of the datanode for a specified `addr`, however, specifying `addr` in the path is optional. + +### Definition + +```bash +curl -X GET http://localhost:4000/admin/heartbeat +``` + +| Query String Parameter | Type | Optional/Required | Definition | +|:-----------------------|:-------|:------------------|:--------------------------| +| addr | String | Optional | The addr of the datanode. | + +### Examples + +#### Request + +```bash +curl -X GET 'http://localhost:4000/admin/heartbeat?addr=127.0.0.1:4100' +``` + +#### Response + +```json +[ + [{ + "timestamp_millis": 1677049348651, + "cluster_id": 0, + "id": 1, + "addr": "127.0.0.1:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049344048, + "cluster_id": 0, + "id": 1, + "addr": "0.0.0.0:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049343624, + "cluster_id": 0, + "id": 1, + "addr": "127.0.0.1:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049339036, + "cluster_id": 0, + "id": 1, + "addr": "0.0.0.0:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049338609, + "cluster_id": 0, + "id": 1, + "addr": "127.0.0.1:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049334019, + "cluster_id": 0, + "id": 1, + "addr": "0.0.0.0:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049333592, + "cluster_id": 0, + "id": 1, + "addr": "127.0.0.1:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049329002, + "cluster_id": 0, + "id": 1, + "addr": "0.0.0.0:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049328573, + "cluster_id": 0, + "id": 1, + "addr": "127.0.0.1:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }, { + "timestamp_millis": 1677049323986, + "cluster_id": 0, + "id": 1, + "addr": "0.0.0.0:4100", + "is_leader": false, + "rcus": 0, + "wcus": 0, + "table_num": 0, + "region_num": 2, + "cpu_usage": 0.0, + "load": 0.0, + "read_io_rate": 0.0, + "write_io_rate": 0.0, + "region_stats": [] + }] +] +``` + +## /maintenance HTTP endpoint + +Cluster Maintenance Mode is a safety feature in GreptimeDB that temporarily disables automatic cluster management operations. This mode is particularly useful during cluster upgrades, planned downtime, and any operation that might temporarily affect cluster stability. For more details, please refer to [Cluster Maintenance Mode](/user-guide/deployments-administration/maintenance/maintenance-mode.md). + +## /procedure-manager HTTP endpoint + +This endpoint is used to manage the Procedure Manager status. For more details, please refer to [Prevent Metadata Changes](/user-guide/deployments-administration/maintenance/prevent-metadata-changes.md). \ No newline at end of file diff --git a/versioned_docs/version-1.0/contributor-guide/metasrv/overview.md b/versioned_docs/version-1.0/contributor-guide/metasrv/overview.md new file mode 100644 index 0000000000..7aa052dd7e --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/metasrv/overview.md @@ -0,0 +1,161 @@ +--- +keywords: [metasrv, metadata, request-router, load balancing, election, high availability, heartbeat] +description: Provides an overview of the Metasrv service, its components, interactions with the Frontend, architecture, and key functionalities like distributed consensus and heartbeat management. +--- + +# Metasrv + +![meta](/meta.png) + +## What's in Metasrv + +- Store metadata (Catalog, Schema, Table, Region, etc.) +- Request-Router. It tells the Frontend where to write and read data. +- Load balancing for Datanode, determines who should handle new table creation requests, more precisely, it makes resource allocation decisions. +- Election & High Availability, GreptimeDB is designed in a Leader-Follower architecture, only Leader nodes can write while Follower nodes can read, the number of Follower nodes is usually >= 1, and Follower nodes need to be able to switch to Leader quickly when Leader is not available. +- Statistical data collection (reported via Heartbeats on each node), such as CPU, Load, number of Tables on the node, average/peak data read/write size, etc., can be used as the basis for distributed scheduling. + +## How the Frontend interacts with Metasrv + +First, the routing table in Request-Router is in the following structure (note that this is only the logical structure, the actual storage structure varies, for example, endpoints may have dictionary compression). + +``` + table_A + table_name + table_schema // for physical plan + 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 + ... +``` + +### Create Table + +1. The Frontend sends `CREATE TABLE` requests to Metasrv. +2. Plan the number of Regions according to the partition rules contained in the request. +3. Check the global view of resources available to Datanodes (collected by Heartbeats) and assign one node to each region. +4. The Frontend creates the table and stores the `Schema` to Metasrv after successful creation. + +### Insert + +1. The Frontend fetches the routes of the specified table from Metasrv. Note that the smallest routing unit is the route of the table (several regions), i.e., it contains the addresses of all regions of this table. +2. The best practice is that the Frontend first fetches the routes from its local cache and forwards the request to the Datanode. If the route is no longer valid, then Datanode is obliged to return an `Invalid Route` error, and the Frontend re-fetches the latest data from Metasrv and updates its cache. Route information does not change frequently, thus, it's sufficient for Frontend uses the Lazy policy to maintain the cache. +3. The Frontend processes a batch of writes that may contain multiple tables and multiple regions, so the Frontend needs to split user requests based on the 'route table'. + +### Select + +1. As with `Insert`, the Frontend first fetches the route table from the local cache. +2. Unlike `Insert`, for `Select`, the Frontend needs to extract the read-only node (follower) from the route table, then dispatch the request to the leader or follower node depending on the priority. +3. The distributed query engine in the Frontend distributes multiple sub-query tasks based on the routing information and aggregates the query results. + +## Metasrv Architecture + +![metasrv-architecture](/metasrv-architecture.png) + +## Distributed Consensus + +As you can see, Metasrv has a dependency on distributed consensus because: + +1. First, Metasrv has to elect a leader, Datanode only sends heartbeats to the leader, and we only use a single metasrv node to receive heartbeats, which makes it easy to do some calculations or scheduling accurately and quickly based on global information. As for how the Datanode connects to the leader, this is for MetaClient to decide (using a redirect, Heartbeat requests becomes a gRPC stream, and using redirect will be less error-prone than forwarding), and it is transparent to the Datanode. +2. Second, Metasrv must provide an election API for Datanode to elect "write" and "read-only" nodes and help Datanode achieve high availability. +3. Finally, `Metadata`, `Schema` and other data must be reliably and consistently stored on Metasrv. Therefore, consensus-based algorithms are the ideal approach for storing them. + +For the first version of Metasrv, we choose Etcd as the consensus algorithm component (Metasrv is designed to consider adapting different implementations and even creating a new wheel) for the following reasons: + +1. Etcd provides exactly the API we need, such as `Watch`, `Election`, `KV`, etc. +2. We only perform two tasks with distributed consensus: elections (using the `Watch` mechanism) and storing (a small amount of metadata), and neither of them requires us to customize our own state machine, nor do we need to customize our own state machine based on raft; the small amount of data also does not require multi-raft-group support. +3. The initial version of Metasrv uses Etcd, which allows us to focus on the capabilities of Metasrv and not spend too much effort on distributed consensus algorithms, which improves the design of the system (avoiding coupling with consensus algorithms) and helps with rapid development at the beginning, as well as allows easy access to good consensus algorithm implementations in the future through good architectural designs. + +## Heartbeat Management + +The primary means of communication between Datanode and Metasrv is the Heartbeat Request/Response Stream, and we want this to be the only way to communicate. This idea is inspired by the design of [TiKV PD](https://github.com/tikv/pd), and we have practical experience in [RheaKV](https://github.com/sofastack/sofa-jraft/tree/master/jraft-rheakv/rheakv-pd). The request sends its state, while Metasrv sends different scheduling instructions via Heartbeat Response. + +A heartbeat will probably carry the data listed below, but this is not the final design, and we are still discussing and exploring exactly which data should be mostly collected. + +``` +service Heartbeat { + // Heartbeat, there may be many contents of the heartbeat, such as: + // 1. Metadata to be registered to metasrv and discoverable by other nodes. + // 2. Some performance metrics, such as Load, CPU usage, etc. + // 3. The number of computing tasks being executed. + rpc Heartbeat(stream HeartbeatRequest) returns (stream HeartbeatResponse) {} +} + +message HeartbeatRequest { + RequestHeader header = 1; + + // Self peer + Peer peer = 2; + // Leader node + bool is_leader = 3; + // Actually reported time interval + TimeInterval report_interval = 4; + // Node stat + NodeStat node_stat = 5; + // Region stats in this node + repeated RegionStat region_stats = 6; + // Follower nodes and stats, empty on follower nodes + repeated ReplicaStat replica_stats = 7; +} + +message NodeStat { + // The read capacity units during this period + uint64 rcus = 1; + // The write capacity units during this period + uint64 wcus = 2; + // Table number in this node + uint64 table_num = 3; + // Region number in this node + uint64 region_num = 4; + + double cpu_usage = 5; + double load = 6; + // Read disk I/O in the node + double read_io_rate = 7; + // Write disk I/O in the node + double write_io_rate = 8; + + // Others + map attrs = 100; +} + +message RegionStat { + uint64 region_id = 1; + TableName table_name = 2; + // The read capacity units during this period + uint64 rcus = 3; + // The write capacity units during this period + uint64 wcus = 4; + // Approximate region size + uint64 approximate_size = 5; + // Approximate number of rows + uint64 approximate_rows = 6; + + // Others + map attrs = 100; +} + +message ReplicaStat { + Peer peer = 1; + bool in_sync = 2; + bool is_learner = 3; +} +``` + +## Central Nervous System (CNS) + +We are to build an algorithmic system, which relies on real-time and historical heartbeat data from each node, should make some smarter scheduling decisions and send them to Metasrv's Autoadmin unit, which distributes the scheduling decisions, either by the Datanode itself or more likely by the PaaS platform. + +## Abstraction of Workloads + +The level of workload abstraction determines the efficiency and quality of the scheduling strategy generated by Metasrv such as resource allocation. + +DynamoDB defines RCUs & WCUs (Read Capacity Units / Write Capacity Units), explaining that a RCU is a read request of 4KB data, and a WCU is a write request of 1KB data. When using RCU and WCU to describe workloads, it's easier to achieve performance measurability and get more informative resource preallocation because we can abstract different hardware capabilities as a combination of RCU and WCU. + +However, GreptimeDB still faces a more complex situation than DynamoDB, in particular, RCU doesn't fit to describe GreptimeDB's read workloads which require a lot of computation. We are working on that. diff --git a/versioned_docs/version-1.0/contributor-guide/metasrv/selector.md b/versioned_docs/version-1.0/contributor-guide/metasrv/selector.md new file mode 100644 index 0000000000..790ffb849b --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/metasrv/selector.md @@ -0,0 +1,47 @@ +--- +keywords: [selector, metasrv, datanode, leasebased, loadbased, roundrobin] +description: Describes the different types of selectors in the Metasrv service, their characteristics, and how to configure them. +--- + +# Selector + +## Introduction + +What is the `Selector`? As its name suggests, it allows users to select specific items from a given `namespace` and `context`. There is a related trait, also named `Selector`, whose definition can be found [below][0]. + +[0]: https://github.com/GreptimeTeam/greptimedb/blob/main/src/meta-srv/src/selector.rs + +There is a specific scenario in `Metasrv` service. When a request to create a table is sent to the `Metasrv` service, it creates a routing table (the details of table creation will not be described here). The `Metasrv` service needs to select the appropriate `Datanode` list when creating a routing table. + +## Selector Type + +The `Metasrv` service currently offers the following types of `Selectors`: + +### LeasebasedSelector + +`LeasebasedSelector` randomly selects from all available (in lease) `Datanode`s, its characteristic is simplicity and fast. + +### LoadBasedSelector + +The `LoadBasedSelector` load value is determined by the number of regions on each `Datanode`, fewer regions indicate lower load, and `LoadBasedSelector` prioritizes selecting low-load `Datanodes`. + +### RoundRobinSelector [default] +`RoundRobinSelector` selects `Datanode`s in a round-robin fashion. It is recommended and the default option in most cases. If you're unsure which to choose, it's usually the right choice. + +## Configuration + +You can configure the `Selector` by its name when starting the `Metasrv` service. + +- LeasebasedSelector: `lease_based` or `LeaseBased` +- LoadBasedSelector: `load_based` or `LoadBased` +- RoundRobinSelector: `round_robin` or `RoundRobin` + +For example: + +```shell +cargo run -- metasrv start --selector round_robin +``` + +```shell +cargo run -- metasrv start --selector RoundRobin +``` diff --git a/versioned_docs/version-1.0/contributor-guide/overview.md b/versioned_docs/version-1.0/contributor-guide/overview.md new file mode 100644 index 0000000000..875b4b1e16 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/overview.md @@ -0,0 +1,25 @@ +--- +keywords: [architecture, key components, user requests, data processing, database components] +description: Overview of GreptimeDB's architecture, key components, and how they interact to process user requests. +--- + +# Contributor Guide + +DeepWiki provides a detailed and clear explanation of GreptimeDB's architecture and implementation. Highly recommended: + +[https://deepwiki.com/GreptimeTeam/greptimedb](https://deepwiki.com/GreptimeTeam/greptimedb) + +## Architecture + +For the architecture and components of GreptimeDB, please see the [Architecture](/user-guide/concepts/architecture.md) document in the user guide. + +For more details on each component, see the following guides: + +- [frontend][1] +- [datanode][2] +- [metasrv][3] + +[1]: /contributor-guide/frontend/overview.md +[2]: /contributor-guide/datanode/overview.md +[3]: /contributor-guide/metasrv/overview.md + diff --git a/versioned_docs/version-1.0/contributor-guide/tests/integration-test.md b/versioned_docs/version-1.0/contributor-guide/tests/integration-test.md new file mode 100644 index 0000000000..5d5f6cb1a5 --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/tests/integration-test.md @@ -0,0 +1,13 @@ +--- +keywords: [integration tests, Rust test harness, multiple components, HTTP testing, gRPC testing] +description: Guide on writing and running integration tests in GreptimeDB, covering scenarios involving multiple components. +--- + +# Integration Test + +## Introduction + +Integration testing is written with Rust test harness (`#[test]`), unlike unit testing, they are placed separately +[here](https://github.com/GreptimeTeam/greptimedb/tree/main/tests-integration). +It covers scenarios involving multiple components, in which one typical case is HTTP/gRPC-related features. You can check +its [documentation](https://github.com/GreptimeTeam/greptimedb/blob/main/tests-integration/README.md) for more information. diff --git a/versioned_docs/version-1.0/contributor-guide/tests/overview.md b/versioned_docs/version-1.0/contributor-guide/tests/overview.md new file mode 100644 index 0000000000..feeefe2b6d --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/tests/overview.md @@ -0,0 +1,8 @@ +--- +keywords: [testing methods, behavior testing, performance testing, test overview, GreptimeDB tests] +description: Overview of the testing methods used in GreptimeDB to ensure its behavior and performance. +--- + +# Tests + +Our team has conducted lots of tests to ensure the behaviours of `GreptimeDB` . This chapter will introduce several significant methods used to test `GreptimeDB`, and how to work with them. diff --git a/versioned_docs/version-1.0/contributor-guide/tests/sqlness-test.md b/versioned_docs/version-1.0/contributor-guide/tests/sqlness-test.md new file mode 100644 index 0000000000..499ef6e19c --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/tests/sqlness-test.md @@ -0,0 +1,61 @@ +--- +keywords: [SQL tests, sqlness, test suite, test cases, test output] +description: Instructions for running SQL tests in GreptimeDB using the `sqlness` test suite, including file types, case organization, and running tests. +--- + +# Sqlness Test + +## Introduction + +SQL is an important user interface for `GreptimeDB`. We have a separate test suite for it (named `sqlness`). + +## Sqlness manual + +### Case file + +Sqlness has three types of file + +- `.sql`: test input, SQL only +- `.result`: expected test output, SQL and its results +- `.output`: different output, SQL and its results + +Both `.result` and `.output` are output (execution result) files. The difference is that `.result` is the +the standard (expected) output, and `.output` is the error output. Therefore, if you see `.output` files generated, +it means this test gets a different result and indicates it fails. You should +check change logs to solve the problem. + +You only need to write test SQL in `.sql` file, and run the test. On the first run it produces +an `.output` file because there is no `.result` to compare with. If you can make sure the content in +`.output` is correct, you can rename it to `.result`, which means it is the expected output. + +And at any time there should only be two file types, `.sql` and `.result` -- otherwise, an existing `.output` +file means your test fails. That's why we should not ignore `.output` file type in `.gitignore`, instead, track +it and make sure it doesn't exist. + +### Case organization + +The root dir of input cases is `tests/cases`. It contains several sub-directories stand for different test +modes. E.g., `standalone/` contains all the tests to run under `greptimedb standalone start` mode. + +Under the first level of sub-directory (e.g. the `cases/standalone`), you can organize your cases as you like. +Sqlness walks through every file recursively and runs them. + +## Run the test + +Unlike other tests, this harness is in a binary target form. You can run it with + +```shell +cargo run --bin sqlness-runner bare +``` + +It automatically finishes the following procedures: compile `GreptimeDB`, start it, grab tests and feed it to +the server, then collect and compare the results. You only need to check whether there are new `.output` files. +If not, congratulations, the test is passed 🥳! + +### Run a specific test + +```shell +cargo sqlness bare -t your_test +``` + +If you specify a second argument, only test cases containing the specified string in their names will be executed. Sqlness also supports filtering based on environment. The filter is accepted as a regex string and the case name will be examined in the format of `env:case`. diff --git a/versioned_docs/version-1.0/contributor-guide/tests/unit-test.md b/versioned_docs/version-1.0/contributor-guide/tests/unit-test.md new file mode 100644 index 0000000000..82e30bf5fa --- /dev/null +++ b/versioned_docs/version-1.0/contributor-guide/tests/unit-test.md @@ -0,0 +1,32 @@ +--- +keywords: [unit tests, Rust, cargo nextest, test runner, coverage] +description: Guide on writing and running unit tests in GreptimeDB using Rust's `#[test]` attribute and `cargo nextest`. +--- + +# Unit Test + +## Introduction + +Unit tests are embedded into the codebase, usually placed next to the logic being tested. +They are written using Rust's `#[test]` attribute and can run with `cargo nextest run`. + +The default test runner ships with `cargo` is not supported in GreptimeDB codebase. It's recommended +to use [`nextest`](https://nexte.st/) instead. You can install it with + +```shell +cargo install cargo-nextest --locked +``` + +And run the tests (here the `--workspace` is not necessary) + +```shell +cargo nextest run +``` + +Notes if your Rust is installed via `rustup`, be sure to install `nextest` with `cargo` rather +than the package manager like `homebrew`. Otherwise it will mess up your local environment. + +## Coverage + +Our continuous integration (CI) jobs have a "coverage checking" step. It will report how many +codes are covered by unit tests. Please add the necessary unit test to your patch. diff --git a/versioned_docs/version-1.0/db-cloud-shared/migrate/_migrate-from-prometheus.md b/versioned_docs/version-1.0/db-cloud-shared/migrate/_migrate-from-prometheus.md new file mode 100644 index 0000000000..162a7ac03a --- /dev/null +++ b/versioned_docs/version-1.0/db-cloud-shared/migrate/_migrate-from-prometheus.md @@ -0,0 +1,33 @@ +GreptimeDB can be used to store time series data for [Prometheus](https://prometheus.io/). +Additionally, GreptimeDB supports the Prometheus query language via its HTTP API. +This allows for an easy migration of your Prometheus long-term storage to GreptimeDB. + +## Data model in difference + +To understand the differences between the data models of Prometheus and GreptimeDB, please refer to the [Data Model](/user-guide/ingest-data/for-observability/prometheus.md#data-model) in the Ingest Data documentation. + +## Prometheus Remote Write + + + +## Prometheus HTTP API and PromQL + +GreptimeDB supports the Prometheus query language (PromQL) via its HTTP API. + + +## Visualize data using Grafana + +For developers accustomed to using Grafana for visualizing Prometheus data, +you can continue to use the same Grafana dashboards to visualize data stored in GreptimeDB. + + + +## Reference + +For tutorials and user stories on integrating GreptimeDB with Prometheus, please refer to the following blog posts: + +- [Setting Up GreptimeDB for Long-Term Prometheus Storage](https://greptime.com/blogs/2024-08-09-prometheus-backend-tutorial) +- [Scale Prometheus - Deploying GreptimeDB Cluster as Long-Term Storage for Prometheus in K8s](https://greptime.com/blogs/2024-10-07-scale-prometheus) +- [User Story — Why We Switched from Thanos to GreptimeDB for Prometheus Long-Term Storage](https://greptime.com/blogs/2024-10-16-thanos-migration-to-greptimedb) + +If you need a more detailed migration plan or example scripts, please provide the specific table structure and data volume. The [GreptimeDB official community](https://github.com/orgs/GreptimeTeam/discussions) will offer further support. Welcome to join the [Greptime Slack](http://greptime.com/slack). diff --git a/versioned_docs/version-1.0/db-cloud-shared/migrate/migrate-from-influxdb.md b/versioned_docs/version-1.0/db-cloud-shared/migrate/migrate-from-influxdb.md new file mode 100644 index 0000000000..233419071b --- /dev/null +++ b/versioned_docs/version-1.0/db-cloud-shared/migrate/migrate-from-influxdb.md @@ -0,0 +1,259 @@ +This guide will help you understand the differences between the data models of GreptimeDB and InfluxDB, and guide you through the migration process. + +## Data model in difference + +To understand the differences between the data models of InfluxDB and GreptimeDB, please refer to the [Data Model](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md#data-model) in the Ingest Data documentation. + +## Database connection information + +Before you begin writing or querying data, it's crucial to comprehend the differences in database connection information between InfluxDB and GreptimeDB. + +- **Token**: The InfluxDB API token, used for authentication, aligns with the GreptimeDB authentication. When interacting with GreptimeDB using InfluxDB's client libraries or HTTP API, you can use `` as the token. +- **Organization**: Unlike InfluxDB, GreptimeDB does not require an organization for connection. +- **Bucket**: In InfluxDB, a bucket serves as a container for time series data, which is equivalent to the database name in GreptimeDB. + + + +## Ingest data + +GreptimeDB is compatible with both v1 and v2 of InfluxDB's line protocol format, +facilitating a seamless migration from InfluxDB to GreptimeDB. + +### HTTP API + +To write a measurement to GreptimeDB, you can use the following HTTP API request: + + + +### Telegraf + +GreptimeDB's support for the Influxdb line protocol ensures its compatibility with Telegraf. +To configure Telegraf, simply add GreptimeDB URL into Telegraf configurations: + + + +### Client libraries + +Writing data to GreptimeDB is a straightforward process when using InfluxDB client libraries. +Simply include the URL and authentication details in the client configuration. + +For example: + + + +In addition to the languages previously mentioned, +GreptimeDB also accommodates client libraries for other languages supported by InfluxDB. +You can code in your language of choice by referencing the connection information and code snippets provided earlier. + +## Query data + +GreptimeDB does not support Flux and InfluxQL, opting instead for SQL and PromQL. + +SQL is a universal language designed for managing and manipulating relational databases. +With flexible capabilities for data retrieval, manipulation, and analytics, +it is also reduce the learning curve for users who are already familiar with SQL. + +PromQL (Prometheus Query Language) allows users to select and aggregate time series data in real time, +The result of an expression can either be shown as a graph, viewed as tabular data in Prometheus's expression browser, +or consumed by external systems via the [HTTP API](/user-guide/query-data/promql.md#prometheus-http-api). + +Suppose you are querying the maximum cpu usage from the `monitor` table, recorded over the past 24 hours. +In influxQL, the query might look something like this: + +```sql [InfluxQL] +SELECT + MAX("cpu") +FROM + "monitor" +WHERE + time > now() - 24h +GROUP BY + time(1h) +``` + +This InfluxQL query computes the maximum value of the `cpu` field from the `monitor` table, +considering only the data where the time is within the last 24 hours. +The results are then grouped into one-hour intervals. + +In Flux, the query might look something like this: + +```flux [Flux] +from(bucket: "public") + |> range(start: -24h) + |> filter(fn: (r) => r._measurement == "monitor") + |> aggregateWindow(every: 1h, fn: max) +``` + +The similar query in GreptimeDB SQL would be: + +```sql [SQL] +SELECT + greptime_timestamp, + host, + AVG(cpu) RANGE '1h' as mean_cpu +FROM + monitor +WHERE + greptime_timestamp > NOW() - '24 hours'::INTERVAL +ALIGN '1h' TO NOW +ORDER BY greptime_timestamp DESC; +``` + +In this SQL query, +the `RANGE` clause determines the time window for the `AVG(cpu)` aggregation function, +while the `ALIGN` clause sets the alignment time for the time series data. +For more information on time window grouping, please refer to the [Aggregate data by time window](/user-guide/query-data/sql.md#aggregate-data-by-time-window) document. + +The similar query in PromQL would be something like: + +```promql +avg_over_time(monitor[1h]) +``` +To query time series data from the last 24 hours, +you need to execute this PromQL, using the `start` and `end` parameters of the HTTP API to define the time range. +For more information on PromQL, please refer to the [PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/) document. + +## Visualize data + + + +## Migrate data + +For a seamless migration of data from InfluxDB to GreptimeDB, you can follow these steps: + +![Double write to GreptimeDB and InfluxDB](/migrate-influxdb-to-greptimedb.drawio.svg) + +1. Write data to both GreptimeDB and InfluxDB to avoid data loss during migration. +2. Export all historical data from InfluxDB and import the data into GreptimeDB. +3. Stop writing data to InfluxDB and remove the InfluxDB server. + +### Write data to both GreptimeDB and InfluxDB simultaneously + +Writing data to both GreptimeDB and InfluxDB simultaneously is a practical strategy to avoid data loss during migration. +By utilizing InfluxDB's [client libraries](#client-libraries), +you can set up two client instances - one for GreptimeDB and another for InfluxDB. +For guidance on writing data to GreptimeDB using the InfluxDB line protocol, please refer to the [Ingest Data](#ingest-data) section. + +If retaining all historical data isn't necessary, +you can simultaneously write data to both GreptimeDB and InfluxDB for a specific period to accumulate the required recent data. +Subsequently, cease writing to InfluxDB and continue exclusively with GreptimeDB. +If a complete migration of all historical data is needed, please proceed with the following steps. + +### Export data from InfluxDB v1 Server + +Create a temporary directory to store the exported data of InfluxDB. + +```shell +mkdir -p /path/to/export +``` + +Use the [`influx_inspect export` command](https://docs.influxdata.com/influxdb/v1/tools/influx_inspect/#export) of InfluxDB to export data. + +```shell +influx_inspect export \ + -database \ + -end \ + -lponly \ + -datadir /var/lib/influxdb/data \ + -waldir /var/lib/influxdb/wal \ + -out /path/to/export/data +``` + +- The `-database` flag specifies the database to be exported. +- The `-end` flag specifies the end time of the data to be exported. +Must be in [RFC3339 format](https://datatracker.ietf.org/doc/html/rfc3339), such as `2024-01-01T00:00:00Z`. +You can use the timestamp when simultaneously writing data to both GreptimeDB and InfluxDB as the end time. +- The `-lponly` flag specifies that only the Line Protocol data should be exported. +- The `-datadir` flag specifies the path to the data directory, as configured in the [InfluxDB data settings](https://docs.influxdata.com/influxdb/v1/administration/config/#data-settings). +- The `-waldir` flag specifies the path to the WAL directory, as configured in the [InfluxDB data settings](https://docs.influxdata.com/influxdb/v1/administration/config/#data-settings). +- The `-out` flag specifies the output directory. + +The exported data in InfluxDB line protocol looks like the following: + +```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 +... +``` + +### Export Data from InfluxDB v2 Server + +Create a temporary directory to store the exported data of InfluxDB. + +```shell +mkdir -p /path/to/export +``` + +Use the [`influx inspect export-lp` command](https://docs.influxdata.com/influxdb/v2/reference/cli/influxd/inspect/export-lp/) of InfluxDB to export data in the bucket to line protocol. + +```shell +influxd inspect export-lp \ + --bucket-id \ + --engine-path /var/lib/influxdb2/engine/ \ + --end \ + --output-path /path/to/export/data +``` + +- The `--bucket-id` flag specifies the bucket ID to be exported. +- The `--engine-path` flag specifies the path to the engine directory, as configured in the [InfluxDB data settings](https://docs.influxdata.com/influxdb/v2.0/reference/config-options/#engine-path). +- The `--end` flag specifies the end time of the data to be exported. Must be in [RFC3339 format](https://datatracker.ietf.org/doc/html/rfc3339), such as `2024-01-01T00:00:00Z`. +You can use the timestamp when simultaneously writing data to both GreptimeDB and InfluxDB as the end time. +- The `--output-path` flag specifies the output directory. + +The outputs look like the following: + +```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"} +``` + +The exported data in InfluxDB line protocol looks like the following: + +```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 +... +``` + +### Import Data to GreptimeDB + +Before importing data to GreptimeDB, if the data file is too large, it's recommended to split the data file into multiple slices: + +```shell +split -l 100000 -d -a 10 data data. +# -l [line_count] Create split files line_count lines in length. +# -d Use a numeric suffix instead of a alphabetic suffix. +# -a [suffix_length] Use suffix_length letters to form the suffix of the file name. +``` + +You can import data using the HTTP API as described in the [write data section](#http-api). +The script provided below will help you in reading data from the files and importing it into GreptimeDB. + +Suppose you are in the directory where the data files are stored: + +```shell +. +├── data.0000000000 +├── data.0000000001 +├── data.0000000002 +... +``` + +Replace the following placeholders with your GreptimeDB connection information to setup the environment variables: + +```shell +export GREPTIME_USERNAME= +export GREPTIME_PASSWORD= +export GREPTIME_HOST= +export GREPTIME_DB= +``` + +Import the data from the files into GreptimeDB: + + + +If you need a more detailed migration plan or example scripts, please provide the specific table structure and data volume. The [GreptimeDB official community](https://github.com/orgs/GreptimeTeam/discussions) will offer further support. Welcome to join the [Greptime Slack](http://greptime.com/slack). diff --git a/versioned_docs/version-1.0/enterprise/autopilot/region-balancer.md b/versioned_docs/version-1.0/enterprise/autopilot/region-balancer.md new file mode 100644 index 0000000000..8303ad1888 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/autopilot/region-balancer.md @@ -0,0 +1,39 @@ +--- +keywords: [region balancer, load balancing, configuration, datanodes, migration] +description: Configuration guide for the region balancer plugin in GreptimeDB Enterprise, which balances write loads across datanodes to prevent frequent region migrations. +--- + +# Region Balancer + +This plugin balances the write load of regions across datanodes, using specified window sizes and load thresholds to prevent frequent region migrations. You can enable the Auto Rebalancer feature by adding the following configuration to Metasrv. + +```toml +[[plugins]] +[plugins.region_balancer] + +window_size = "45s" + +window_stability_threshold = 2 + +min_load_threshold = "10MB" + +tick_interval = "45s" +``` + +## Configuration Parameters + +- `window_size`: string + - **Description**: Defines the time span for the sliding window used to calculate the short-term average load of a region. This window helps smooth out temporary spikes in load, reducing the chance of unnecessary rebalancing. + - **Units**: Time (e.g., `"45s"` represents 45 seconds). + - **Recommendation**: Adjust according to load volatility. Larger values smooth more effectively but may delay load balancing responses. +- `window_stability_threshold`: integer + - **Description**: Specifies the number of consecutive windows that must meet the load-balancing criteria before a region migration is triggered. This threshold helps prevent frequent balancing actions, ensuring region migration only occurs when imbalance is sustained. + - **Recommendation**: Higher values delay rebalancing triggers and suit environments with volatile loads; a value of 2 means that at least two consecutive windows must meet the threshold before triggering. +- `min_load_threshold`: string + - **Description**: Minimum write load threshold (in bytes per second) to trigger region migration. Nodes with load below this value will not trigger rebalancing. + - **Units**: Bytes (e.g., `"10MB"` represents 10 MiB). + - **Recommendation**: Set an appropriate minimum to avoid triggering region migration with low load. Adjust based on typical traffic. +- `tick_interval`: string + - **Description**: Interval at which the balancer checks and potentially triggers a rebalancing task. + - **Units**: Time (e.g., `"45s"` represents 45 seconds). + - **Recommendation**: Set based on desired responsiveness and load volatility. Shorter intervals allow faster responses but may increase overhead. \ No newline at end of file diff --git a/versioned_docs/version-1.0/enterprise/console-ui.md b/versioned_docs/version-1.0/enterprise/console-ui.md new file mode 100644 index 0000000000..3f0b5ff82e --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/console-ui.md @@ -0,0 +1,58 @@ +--- +keywords: [enterprise, management console, dashboard, cluster management, monitoring, observability, UI] +description: The GreptimeDB Enterprise Management Console provides an enhanced dashboard interface with advanced cluster management, monitoring, and operational capabilities for enterprise users. +--- + +# Management Console + +The GreptimeDB Enterprise Management Console is an enhanced version of the standard GreptimeDB dashboard, designed specifically for enterprise users who require advanced cluster observability and operational capabilities. It provides comprehensive monitoring, management, and operational tools that go beyond the standard dashboard functionality. + + +## Overview + +The **Overview** page displays the overall cluster status and resource usage. + +- **Service Overview**: CPU, memory, and storage usage; data ingestion rate; request rates by protocol. +- **Storage Overview**: Number of databases, tables, and regions; sizes of Manifest, WAL, and Index files. +- **Cluster**: Node types; node status and resource usage. + +![Overview](/enterprise-console-overview.png) + +## Region Management + +**Region Management** provides region-level operational capabilities for advanced cluster administration. + +- **Datanodes view**: View details of each datanode and its regions, including region ID, associated table, storage size, WAL/Manifest/Index usage, and row count. +- **Tables view**: View region distribution by table with expandable region details for comprehensive analysis. +- **Region maintenance**: Execute Flush and Compact operations to optimize storage and performance. +- **Region migration**: Migrate regions between nodes with configurable timeout settings and real-time progress tracking. + +![Region Management - Datanodes](/enterprise-console-region-datanodes.png) + +![Region Management - Tables](/enterprise-console-region-tables.png) + +## Data Management + +The **Data Management** page provides SQL/PromQL queries, data ingestion, logs queries, logs pipelines, traces queries, and Flow management. These features are consistent with the open-source Dashboard and Cloud Dashboard. + +## Monitoring + +The **Monitoring** page provides comprehensive metrics and log monitoring capabilities for enterprise-grade observability. + +### Metrics + +Provides multiple groups of monitoring panels including Overview, Ingestion, Queries, Resources, Frontend Requests, Frontend to Datanode, Mito Engine, OpenDAL, Metasrv, and Flownode. These panels cover essential cluster metrics such as operational status, request rates, latency, and resource utilization. + +![Metrics](/enterprise-console-monitor-metrics.png) + +### Instance Logs + +Enables advanced log filtering and analysis with support for filtering by role, instance, log level, time range, and keywords. Log results can be exported to JSON format for further analysis. + +![Instance Logs](/enterprise-console-instance-logs.png) + +### Slow Query + +Displays long-running SQL and PromQL queries with detailed execution time and query text information. Includes **Explain Query** functionality for execution plan analysis and query optimization. + +![Slow Query](/enterprise-console-slow-query.png) diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/authentication.md b/versioned_docs/version-1.0/enterprise/deployments-administration/authentication.md new file mode 100644 index 0000000000..ed0985f33b --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/authentication.md @@ -0,0 +1,89 @@ +--- +keywords: [LDAP, authentication, configuration, simple bind, search bind, user provider] +description: Configuration guide for LDAP authentication in GreptimeDB Enterprise, detailing both simple bind and search bind modes. +--- + +# LDAP Authentication + +In addition to the built-in [static user provider](/user-guide/deployments-administration/authentication/static.md) in GreptimeDB OSS, +GreptimeDB Enterprise offers the capability to connect to an external LDAP server for authentication. + +## Configuration + +Similar to [LDAP in PostgreSQL](https://www.postgresql.org/docs/current/auth-ldap.html), in GreptimeDB, LDAP authentication is +operated in two modes: "simple bind" and "search bind", too. + +In the "simple bind" mode, GreptimeDB will bind to the "DN"(distinguished name) constructed as +`{prefix}{username}{suffix}`. Typically, the `prefix` parameter is used to specify `cn=`, and the `suffix` is used to +specify the remaining part of the DN. The `username`, of course, is provided by the client. + +Here's the configuration file example for the "simple bind" mode in GreptimeDB's LDAP user provider: + +```toml +# Name or IP address of the LDAP server to connect to. +server = "127.0.0.1" +# Port number on LDAP server to connect to. +port = 636 +# Set to "ldap" to use LDAP, "ldaps" to use LDAPS. +# The connection between GreptimeDB and the LDAP server starts as an initially unencrypted one, +# then upgrades to TLS as the first action against the server, per the LDAPv3 standard ("StartTLS"). +scheme = "ldaps" + +# The authentication mode to the LDAP server, either `bind = "simple"` or `bind = "search"`. +[auth_mode] +# The following options are used in simple bind mode only: +bind = "simple" +# String to prepend to the username when forming the DN to bind as, when doing simple bind authentication. +prefix = "cn=" +# String to append to the username when forming the DN to bind as, when doing simple bind authentication. +suffix = ",dc=example,dc=com" +``` + +In the "search bind" mode, GreptimeDB will first try to bind to the LDAP directory with a fixed username and password, +which are set in the configuration file (`bind_dn` and `bind_passwd`), Then GreptimeDB performs a search for the user +trying to log in to the database. The search will be performed over the subtree at `base_dn`, filtered by the +`search_filter`, and will try to do an exact match of the attribute specified in `search_attribute`. Once the user has +been found in this search, GreptimeDB re-binds to the directory as this user, using the password specified by the +client, to verify that the login is correct. This method allows for significantly more flexibility in where the user +objects are located in the directory, but will cause two additional requests to the LDAP server to be made. + +The following toml snippets show the configuration file example for the "search bind" mode in GreptimeDB's LDAP user +provider. The common parts of `server`, `port`, and `scheme` as shown in the "simple bind" mode configuration file above +are omitted: + +```toml +[auth_mode] +# The following options are used in search bind mode only: +bind = "search" +# Root DN to begin the search for the user in, when doing search bind authentication. +base_dn = "ou=people,dc=example,dc=com" +# DN of user to bind to the directory with to perform the search when doing search bind authentication. +bind_dn = "cn=admin,dc=example,dc=com" +# Password for user to bind to the directory with to perform the search when doing search bind authentication. +bind_passwd = "secret" +# Attribute to match against the username in the search when doing search bind authentication. +# If no attribute is specified, the uid attribute will be used. +search_attribute = "cn" +# The search filter to use when doing search bind authentication. +# Occurrences of "$username" will be replaced with the username. +# This allows for more flexible search filters than search_attribute. +search_filter = "(cn=$username)" +``` + +## Use LDAP user provider in GreptimeDB + +To use the LDAP user provider, first config your LDAP authentication mode like above, then start GreptimeDB with the +`--user-provider` parameter set to `ldap_user_provider:`. For example, if you have +a configuration file `/home/greptimedb/ldap.toml`, you can start a GreptimeDB standalone server with the following +command: + +```shell +greptime standalone start --user-provider=ldap_user_provider:/home/greptimedb/ldap.toml +``` + +Now you can create a connection to GreptimeDB using your LDAP user accounts. + +:::tip NOTE +If you are using the MySQL CLI to connect to GreptimeDB that is configured with LDAP user provider, you need +to specify the `--enable-cleartext-plugin` in the MySQL CLI. +::: diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/backup.md b/versioned_docs/version-1.0/enterprise/deployments-administration/backup.md new file mode 100644 index 0000000000..b28a8c2650 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/backup.md @@ -0,0 +1,25 @@ +--- +keywords: [backup metadata, backup database, GreptimeDB backup] +description: GreptimeDB backup guide, including steps for backing up metadata and databases. +--- + +# Backup + +## Backup Metadata + +The metadata store of a GreptimeDB cluster can be stored in etcd or a relational database. +For production clusters, +it is recommended to use cloud provider managed relational database services (RDS) with periodic backup features enabled. + +Please refer to [Metadata Export & Import documentation](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md) for the details. + +## Backup Database + +Since object storage typically maintains multiple replicas, +if GreptimeDB data is stored on object storage, +additional database backups are usually unnecessary. +You may also consider enabling versioning features of object storage to prevent data loss from accidental operations. + +You can also use GreptimeDB's `COPY DATABASE` functionality to create backups. +For more information, please refer to the [Data Export & Import documentation](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md). + diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups.md b/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups.md new file mode 100644 index 0000000000..e75ac840e3 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups.md @@ -0,0 +1,100 @@ +--- +keywords: [Kubernetes, deployment, GreptimeDB, datanode groups, CRD, installation, verification] +description: Step-by-step guide to deploying a GreptimeDB cluster with datanode groups on Kubernetes, including prerequisites, configuration, installation, and verification. +--- + +# Deploy a GreptimeDB Cluster with Datanode Groups + +In this guide, you will learn how to deploy a GreptimeDB cluster on Kubernetes with a datanode group consisting of multiple datanode instances. + +## Prerequisites + +- [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 +- [GreptimeDB Operator](https://github.com/GrepTimeTeam/greptimedb-operator) >= v0.3.0 + +## Upgrade operator + +Install the GreptimeDB Operator, setting the image version to be greater than or equal to `v0.3.0`. +For detailed instructions on upgrading the operator, please refer to the [GreptimeDB Operator Management](/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md#upgrade) guide. + +## Datanode Groups Configuration + +In the enterprise edition, you can configure **datanode groups** to separate read and write workloads into different groups. +The datanode accepts a `workload_types` field to distinguish its workload type. Supported types are **`hybrid`**, **`query`**, and **`ingest`**: + +* **`hybrid`** is the default and acts as a superset of `query` and `ingest`, allowing the datanode to handle both workloads. +* **`query`** is optimized for read workloads, datanode only handle read workload. +* **`ingest`** is optimized for write workloads, datanode only handle write workload. + +While `hybrid` is convenient, running both reads and writes on the same datanode may cause them to interfere with each other, for example, a large query may occupy too many resources, thus affecting the online ingestion. For best performance, it is recommended to separate read and write workloads into different datanode groups. + +When configuring datanode groups, ensure that each group includes a `name` field. The following `values.yaml` example demonstrates how to define separate datanode groups: + +```yaml +danodata: + enabled: false + +datanodeGroups: + - name: write + replicas: 1 + config: | + workload_types = ["ingest"] + template: + main: + resources: + requests: + cpu: 4 + memory: 8Gi + storage: + fs: + storageClassName: ${storageClassName} + storageSize: 100Gi + - name: read + replicas: 1 + config: | + workload_types = ["query"] + template: + main: + resources: + limits: + cpu: 8 + memory: 16Gi + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: + - "etcd.etcd-cluster.svc.cluster.local:2379" + +frontend: + replicas: 1 +``` + +For guidance on configuring alternative metadata storage backends for Metasrv, refer to the [Metadata Storage Configuration](/user-guide/deployments-administration/manage-metadata/configuration.md) documentation. + +You can use the following command to apply the configuration: +``` +helm upgrade --install ${release-name} greptime/greptimedb-cluster --namespace ${namespace} -f values.yaml +``` + +## Verify the Installation + +Check the status of the pods: + +```bash +kubectl get pods -n default +NAME READY STATUS RESTARTS AGE +weny-cluster-datanode-read-0 1/1 Running 0 30s +weny-cluster-datanode-write-0 1/1 Running 0 30s +weny-cluster-frontend-774c76cffc-znvrw 1/1 Running 0 30s +weny-cluster-meta-58977b7897-8k2sf 1/1 Running 0 90s +``` + +## Next steps + +- For best performance, it is recommended to [Configure frontend groups](/user-guide/deployments-administration/deploy-on-kubernetes/configure-frontend-groups.md), which ensures complete separation of read and write traffic, achieving maximum isolation. + +- Add Read Replica for your table, please refer to [Read Replica](/enterprise/read-replicas/overview.md). diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/installation.md b/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/installation.md new file mode 100644 index 0000000000..b7e1788c1b --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/installation.md @@ -0,0 +1,46 @@ +--- +keywords: [Kubernetes deployment, GreptimeDB Enterprise, install GreptimeDB, start GreptimeDB, private docker registry, helm chart] +description: Steps to install GreptimeDB Enterprise on Kubernetes, including obtaining images and starting GreptimeDB. +--- + +# Deploy GreptimeDB Cluster + +GreptimeDB Enterprise is released as docker images. +We provide each customer with a separate private docker registry hosted on Cloud, +which you can pull directly using the docker pull command or configure in helm charts. + +## Get GreptimeDB Enterprise Image + +You need to configure the image in the `values.yaml` file of the helm chart to obtain the dedicated GreptimeDB Enterprise, +for example: + +```yaml +customImageRegistry: + enabled: true + # -- pull secret name, customizable, must match `image.pullSecrets` + secretName: greptimedb-custom-image-pull-secret + registry: + username: + password: + +image: + registry: + repository: + tag: + pullSecrets: + - greptimedb-custom-image-pull-secret +``` + +In the above configuration, +the `registry`, `username` and `password` in `customImageRegistry` are used to create the k8s pull secret, +the `registry`, `repository` and `tag` in `image` are used to specify the GreptimeDB Enterprise image, +therefore `customImageRegistry.secretName` and `image.pullSecrets` must be consistent to ensure that the correct authentication information can be found when pulling the image. + +Please contact Greptime staff to obtain the specific values for the above configuration items. +When Greptime staff first deliver GreptimeDB Enterprise to you, +they will inform you of the docker registry address, username and password via email. +Please keep them safe and do not share them with external personnel! + +## Installation and Startup + +Please refer to the [Deploy GreptimeDB Cluster on Kubernetes](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md) documentation. diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/overview.md b/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/overview.md new file mode 100644 index 0000000000..61989c71fd --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/overview.md @@ -0,0 +1,18 @@ +--- +keywords: [Kubernetes deployment, Operator pattern, automated management, cluster deployment, standalone instance, private cloud, public cloud] +description: Overview of deploying GreptimeDB on Kubernetes, including cluster installation, upgrades, and monitoring. +--- + +# Deploy GreptimeDB on Kubernetes + +The deployment process for GreptimeDB Enterprise on Kubernetes is almost the same as the open-source version. +This chapter focuses on the specific deployment configurations and features of the enterprise version. + +## Installation + +To learn how to start GreptimeDB through Helm Chart, please see the [Install GreptimeDB](./installation.md) page. + +## Upgrade + +Please visit the [Upgrade GreptimeDB](./upgrade.md) page to learn how to upgrade GreptimeDB enterprise. + diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/upgrade.md b/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/upgrade.md new file mode 100644 index 0000000000..bfbd64e36f --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/deploy-on-kubernetes/upgrade.md @@ -0,0 +1,24 @@ +--- +keywords: [upgrade GreptimeDB, Metasrv maintenance mode] +description: Steps to upgrade GreptimeDB on Kubernetes, including direct upgrade and upgrading clusters without using GreptimeDB Operator. +--- + +# Upgrade + +## Upgrade Cluster with GreptimeDB Operator + +Upgrading the GreptimeDB Enterprise Edition image is straightforward. +Simply modify the `tag` in the Helm chart and restart. + +## Upgrading Cluster Without GreptimeDB Operator + +When upgrading a cluster without the GreptimeDB Operator, +you must manually enable Metasrv maintenance mode before operating on each component (e.g., rolling upgrade of Datanode nodes). + +After the upgrade is complete, +wait for all components to return to a healthy state before disabling Metasrv maintenance mode. +When Metasrv maintenance mode is enabled, +the Auto Balancing (if enabled) and Region Failover (if enabled) mechanisms in the cluster will be suspended until maintenance mode is disabled. + +Please refer to [Managing Maintenance Mode](/user-guide/deployments-administration/maintenance/maintenance-mode.md#managing-maintenance-mode) for detailed instructions on how to enable and disable Metasrv maintenance mode. + diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/disaster-recovery/dr-solution-based-on-active-active-failover.md b/versioned_docs/version-1.0/enterprise/deployments-administration/disaster-recovery/dr-solution-based-on-active-active-failover.md new file mode 100644 index 0000000000..be93575181 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/disaster-recovery/dr-solution-based-on-active-active-failover.md @@ -0,0 +1,59 @@ +--- +keywords: [disaster recovery, active-active failover, RPO, RTO, read/write modes, configuration] +description: Detailed explanation of the active-active failover disaster recovery solution in GreptimeDB Enterprise, including read/write modes, RPO, and RTO configurations. +--- + +# DR Solution Based on Active-Active Failover + +## RPO + +In GreptimeDB's "Active-Active Failover" architecture, there are two nodes. Both nodes can provide the ability to execute reads and writes from clients. However, to achieve the goals of the RTO and RPO, we need to do some configurations about them. First of all, let me introduce the modes to reads and writes. + +For reads: + +- `SingleRead`: a read operation is executed in one node only, and the results are returned to the client directly. +- `DualRead`: a read operation is executed in both nodes. The results are merged and deduplicated before returning to the client. + +The following picture illustrates the difference between the two read modes: + +![disaster-recovery-read-mode](/disaster-recovery-read-mode.png) + +For writes: + +- `SyncWrite`: a write operation is executed in both nodes, and is considered success only if it is succeeded in both nodes before returning to the clients. +- `AsyncWrite`: a write operation is still executed in both nodes, but the result is returned to the clients when it is done on the issued node. The other node will receive a copy of the write operation from the issued node, asynchronously. + +The following picture illustrates the difference between the two write modes: + +![disaster-recovery-write-mode](/disaster-recovery-write-mode.png) + +So there are four combinations on reads and writes, and their RPOs are: + +| RPO | `SingleRead` | `DualRead` | +| - | - | - | +| `SyncWrite` | 0 | 0 | +| `AsyncWrite` | network latency between two nodes | 0 | + +Since the writes are synchronized between the two nodes in `SyncWrite` mode, the RPO is always zero regardless what read mode is. However, `SyncWrite` requires both nodes functioned well simultaneously to handle writes. If your workload is write-light-read-heavy, and can tolerate some system unavailable time to bring back the healthiness of both nodes when the disaster happened, we recommend the `SyncWrite + SingleRead` combination. + +Another combination that can achieve 0 RPO is `AsyncWrite + DualRead`. It's the opposite of the said above, suitable for the workload of write-heavy-read-light, and the restriction of the system availability can be relaxed. + +The final combination is `AsyncWrite + SingleRead`. This is the most relaxed setup. If the network between the nodes is good, and the nodes are hosted reliably, for example, the two nodes are hosted in a virtual machine system inside one AZ (Available Zone, or "Data Center"), you may prefer this combination. Of course, just remember that the RPO is not zero. + +## RTO + +To retain the minimality of requirements of our active-active architecture, we don't have a third node or a third service to handle the failover of GreptimeDB. Generally speaking, there are several ways to handle the failover: + +- Through a LoadBalancer. If you can spare another node for deploying a LoadBalancer like the [Nginx](https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/), or if you have your own LoadBalance service can be used, we recommend this way. + DR-LoadBalancer +- By client SDK's failover mechanism. For example, if you are using MySQL Connector/j, you can configure the failover by setting multiple hosts and ports in the connection URL (see its document [here](https://dev.mysql.com/doc/connector-j/en/connector-j-config-failover.html)). PostgreSQL's driver [has the same mechanism](https://jdbc.postgresql.org/documentation/use/#connection-fail-over). This is the most easy way to handle the failover, but not every client SDK supports this failover mechanism. + DR-SDK +- Custom endpoint update mechanism. If you can detect the fall of nodes, you can retroactively update the GreptimeDB's endpoint set in your code. + +:::tip NOTE +To compare the RPO and RTO across different disaster recovery solutions, please refer to "[Solution Comparison](/user-guide/deployments-administration/disaster-recovery/overview.md#solution-comparison)". +::: + +## Summary + +You can choose different read/write modes combination to achieve your goal for RPO. This is inherent to GreptimeDB active-active architecture. As to RTO, we rely on external efforts to handle the failover. A LoadBalancer is best suited for this job. diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/disaster-recovery/overview.md b/versioned_docs/version-1.0/enterprise/deployments-administration/disaster-recovery/overview.md new file mode 100644 index 0000000000..d446ce7807 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/disaster-recovery/overview.md @@ -0,0 +1,14 @@ +--- +keywords: [disaster recovery, high availability, data protection, active-active failover, architecture] +description: Overview of disaster recovery solutions in GreptimeDB Enterprise, focusing on the active-active failover architecture for high availability and data protection. +--- + +# Disaster Recovery + +GreptimeDB is a distributed database designed to withstand disasters. + +Please refer to the [Disaster Recovery Overview](/user-guide/deployments-administration/disaster-recovery/overview.md) in the GreptimeDB OSS documentation to learn about all the disaster recovery solutions provided by Greptime. +This section only introduces the solutions provided in GreptimeDB Enterprise. + +- [DR Solution Based on Active-Active Failover](./dr-solution-based-on-active-active-failover.md) + diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/audit-logging.md b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/audit-logging.md new file mode 100644 index 0000000000..a1bee6a13c --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/audit-logging.md @@ -0,0 +1,91 @@ +--- +keywords: [audit logging, configuration, monitoring, compliance, user activity] +description: Guide to configuring audit logging in GreptimeDB Enterprise, including examples and configuration options to monitor and record database activities. +--- + +# Audit Logging + +Database audit logging is the process of recording the actions performed on the database. The audit logs help monitor +user activities, detect suspicious actions, and ensure compliance with regulations inside or outside of an organization. +This document provides an overview of audit logging in GreptimeDB and how to configure it. + +## Overview + +A statement (SQL or PromQL) that is executed on GreptimeDB is recorded in the audit log (if it is configured to be +audited, of course). This is an example record in the audit log: + +```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" +} +``` + +As you can see, the record is formatted as a JSON string. It contains the following fields: + +- `time`: The time when the statement was executed. It's formatted as an ISO 8601 date and time string with UTC timezone. +- `user`: The user who sends the request. +- `source`: The protocol used to connect to GreptimeDB. +- `class`: The class of the statement, like "Read", "Write" or "DDL" etc. +- `command`: The command of the statement, like "Select", "Insert" or "Create" etc. +- `object_type`: The type of the object that the statement operates on, like "Database", "Table" or "Flow" etc. +- `object_names`: The names of the objects that the statement operates on. +- `statement`: The statement itself. + +## Configuration + +Audit logging is provided as a plugin in GreptimeDB. To enable and configure it, add the following TOML to your +GreptimeDB config file: + +```toml +[[plugins]] +# Add the audit log plugin to your GreptimeDB. +[plugins.audit_log] +# Whether to enable audit logging, defaults to true. +enable = true +# The directory to store the audit log files. Defaults to "./greptimedb_data/logs". +dir = "./greptimedb_data/logs/" +# The allowed auditing sources. This option works as a filter: +# if a statement is not coming from one of these configured sources, it won't be recorded in the audit logs. +# Multiple sources are separated by comma(","). +# All sources are: "Http", "Mysql" and "Postgres". +# A special "all" (which is the default value) means all the sources. +sources = "all" +# The allowed auditing classes. This option works as a filter: +# if a statement's class do not match one of these configured values, it won't be recorded in the audit logs. +# Multiple classes are separated by comma(","). +# All classes are: "Read", "Write", "Admin", "DDL" and "Misc". +# A special "all" means all the classes. +# Defaults to "DDL" and "Admin". +classes = "ddl,admin" +# The allowed auditing commands. This option works as a filter: +# if a statement's command do not match one of these configured values, they won't be recorded in the audit logs. +# Multiple commands are separated by comma(","). +# All commands are: "Promql", "Select", "Copy", "Insert", "Delete", "Create", "Alter", "Truncate", "Drop", "Admin" and "Misc". +# A special "all" (which is the default value) means all the commands. +commands = "all" +# The allowed auditing object types. This option works as a filter: +# if a statement's target object do not match one of these configured values, they won't be recorded in the audit logs. +# Multiple object types are separated by comma(","). +# All object types are: "Database", "Table", "View", "Flow", "Index", and "Misc". +# A special "all" (which is the default value) means all the object types. +object_types = "all" +# The max retained audit log files. Defaults to 30. +# A audit log is rotated daily. +max_log_files = 30 +``` + +## Caveats + +Audit logs can be huge if not properly configured. For example, in a busy loaded GreptimeDB, setting "`all`" to all the +`sources`, `classes`, `commands` and `object_types` will record all the statements executed on GreptimeDB, resulting in +a very large audit log file. That could easily explode the disk space. So, it's highly recommended to configure the +audit log plugin properly to avoid such a situation. diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/check-db-status.md b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/check-db-status.md new file mode 100644 index 0000000000..281eda9fdd --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/check-db-status.md @@ -0,0 +1,9 @@ +--- +keywords: [GreptimeDB health check, GreptimeDB status, GreptimeDB deployment status, GreptimeDB metrics] +description: Check GreptimeDB health status, deployment status, and runtime metrics through HTTP endpoints. +--- + +# Check GreptimeDB Status + +Please refer to the [OSS GreptimeDB documentation](/user-guide/deployments-administration/monitoring/check-db-status.md) for details on how to check the health status of GreptimeDB. + diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/key-logs.md b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/key-logs.md new file mode 100644 index 0000000000..a11895a65b --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/key-logs.md @@ -0,0 +1,26 @@ +--- +keywords: [key logs, error logs, operational logs, GreptimeDB logs] +description: Understand GreptimeDB's operational status and troubleshoot errors through key logs. +--- + +# Key Logs + +During operation, GreptimeDB outputs key operations and unexpected error information to logs. +You can use these logs to understand GreptimeDB's operational status and troubleshoot errors. + +## GreptimeDB Operational Logs + +Refer to the [important logs](/user-guide/deployments-administration/monitoring/key-logs.md) outlined in the GreptimeDB OSS documentation for recommended monitoring practices. + +## License Expiration Logs + +For the Enterprise Edition of GreptimeDB, +it is crucial to monitor license expiration logs to ensure uninterrupted access to enterprise features. +When the license expires, +the metasrv component will generate the following warning log. +Promptly contact GreptimeDB to renew your license: + +```bash +License is expired at xxx, please contact your GreptimeDB vendor to renew it +``` + diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/key-metrics.md b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/key-metrics.md new file mode 100644 index 0000000000..b2b1e67bbe --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/key-metrics.md @@ -0,0 +1,29 @@ +--- +keywords: [monitoring key metrics, GreptimeDB monitoring, GreptimeDB key metrics, GreptimeDB cluster monitoring] +description: Monitor key metrics of GreptimeDB clusters, including CPU, memory, disk I/O, and network bandwidth usage. +--- + +# Key Metrics + +The key metrics for monitoring include CPU, memory, disk I/O, and network bandwidth usage. + +## Alert Metrics + +Since each company typically has its own alerting system with potentially different configuration methods, this document does not provide specific alert configuration procedures. Instead, it lists key metrics that should be monitored. You can configure alerts based on whether these metrics remain at abnormal values for extended periods (several minutes). You should set alert thresholds according to your specific circumstances. + +| Metric | Description | Reference Rule | +| --- | --- | --- | +| `sum(process_resident_memory_bytes{}) by (instance, pod)` | Process memory usage | Usage rate continuously exceeds threshold | +| `sum(rate(process_cpu_seconds_total{}[$__rate_interval]) * 1000) by (instance, pod)` | Process CPU usage, displayed in millicores | Utilization rate continuously exceeds threshold | +| `sum by(instance, pod) (greptime_mito_write_stall_total{instance=~"$datanode"})` | Number of backlogged write requests on datanode | Remains greater than 0 for n minutes | +| `sum(rate(greptime_table_operator_ingest_rows{instance=~"$frontend"}[$__rate_interval]))` | Current rows written per second | Drops to 0 (or below threshold) for n minutes | +| `greptime_mito_compaction_failure_total` | Compaction failures | Recent increase greater than 0 | +| `greptime_mito_flush_failure_total` | Flush failures | Recent increase greater than 0 | +| `sum by(instance, pod, path, method, code) (rate(greptime_servers_http_requests_elapsed_count{path!~"/health\|/metrics"}[$__rate_interval]))` | HTTP request count and response codes | HTTP 200 request count below threshold for n minutes or non-200 response count above normal threshold for n minutes | +| `sum by (instance, pod) (rate(greptime_mito_write_rows_total{instance=~"$datanode"}[$__rate_interval]))` | Storage engine write row count | Below normal threshold for n minutes | + +We also recommend configuring disk alerts at the Pod level to trigger when disk usage exceeds a certain threshold. +Additionally, you can monitor the following events based on keywords from error logs listed in the operational [key logs](key-logs.md): + +- Region lease renewal failures +- Region failover diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/overview.md b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/overview.md new file mode 100644 index 0000000000..f3d7f53a3b --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/overview.md @@ -0,0 +1,13 @@ +--- +keywords: [monitoring, GreptimeDB monitoring, monitoring metrics, monitoring configuration, monitoring logs] +description: GreptimeDB monitoring overview, introducing GreptimeDB monitoring metrics, configuration, and logs. +--- + +import DocCardList from '@theme/DocCardList'; + +# Monitoring + +Effective database management relies heavily on monitoring. +You can monitor GreptimeDB using the following methods: + + diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/self-monitor-cluster.md b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/self-monitor-cluster.md new file mode 100644 index 0000000000..3db15a58dd --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/monitoring/self-monitor-cluster.md @@ -0,0 +1,115 @@ +--- +keywords: [Kubernetes deployment, enterprise cluster, monitoring, GreptimeDB Enterprise Management Console] +description: Complete guide to deploying self-monitoring for GreptimeDB enterprise clusters on Kubernetes, including GreptimeDB Enterprise Management Console setup and configuration options +--- + +# Self-Monitoring GreptimeDB Clusters + +Before reading this document, ensure you understand how to [deploy a GreptimeDB enterprise cluster on Kubernetes](/enterprise/deployments-administration/deploy-on-kubernetes/installation.md). +This guide will walk you through configuring monitoring when deploying a GreptimeDB cluster. + +## Quick Start +You can enable monitoring and the [GreptimeDB Enterprise Management Console](/enterprise/console-ui.md) by adding configurations to the `values.yaml` file when deploying the GreptimeDB cluster using Helm Chart. +Here's a complete example of a `values.yaml` file for deploying a minimal GreptimeDB cluster with monitoring and the GreptimeDB Enterprise Management Console: + +```yaml +customImageRegistry: + enabled: true + # -- pull secret name, customizable, must match `image.pullSecrets` + secretName: greptimedb-custom-image-pull-secret + registry: + username: + password: + +image: + registry: + repository: + tag: + pullSecrets: + - greptimedb-custom-image-pull-secret + +initializer: + # Consult GreptimeDB Enterprise staff + registry: + repository: greptime/greptimedb-initializer + # Consult GreptimeDB Enterprise staff + tag: + +monitoring: + # Enable monitoring + enabled: true + +greptimedb-enterprise-dashboard: + # Enable greptimedb-enterprise-dashboard deployment. + # Requires monitoring to be enabled first (monitoring.enabled: true) + enabled: true + image: + # Consult staff for repository and tag + repository: + tag: + +frontend: + replicas: 1 + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + +datanode: + replicas: 1 +``` + +When `monitoring` is enabled, GreptimeDB Operator launches an additional GreptimeDB Standalone instance to collect metrics and logs from the GreptimeDB cluster. +To collect log data, GreptimeDB Operator starts a [Vector](https://vector.dev/) sidecar container in each Pod. + +When `greptimedb-enterprise-dashboard` is enabled, an enterprise dashboard is deployed that uses the GreptimeDB Standalone instance configured for cluster monitoring as its data source and provides management features for the GreptimeDB cluster. + +Then install the GreptimeDB cluster with the above `values.yaml` file: + +```bash +helm upgrade --install mycluster \ + greptime/greptimedb-cluster \ + --values /path/to/values.yaml \ + -n default +``` + +Then refer to the [Access GreptimeDB Management Console](#access-greptimedb-management-console) section below for details on accessing it. + +## Monitoring Configuration + +For detailed monitoring configuration options, please refer to the [monitoring configuration](/user-guide/deployments-administration/monitoring/cluster-monitoring-deployment.md#monitoring-configuration) documentation of the open source GreptimeDB. + +## GreptimeDB Management Console Configuration + +### Enable GreptimeDB Management Console + +To enable GreptimeDB Management Console deployment, add the following configuration to `values.yaml`. +Note that monitoring must be enabled first (`monitoring.enabled: true`): + +```yaml +monitoring: + enabled: true + +greptimedb-enterprise-dashboard: + enabled: true +``` + +### Access GreptimeDB Management Console + +You can access the GreptimeDB Management Console by port-forwarding the service to your local machine: + +```bash +kubectl -n ${namespace} port-forward svc/${cluster-name}-greptimedb-enterprise-console 18080:19095 +``` + +Then open `http://localhost:18080` to access the GreptimeDB Enterprise Management Console. + +For detailed information on using the Management Console features and interface, please refer to the [Management Console](/enterprise/console-ui.md) documentation. + + +## Cleanup the PVCs + +Please refer to the [Cleanup the PVCs](/user-guide/deployments-administration/monitoring/cluster-monitoring-deployment.md#cleanup-the-pvcs) section of the open source GreptimeDB documentation. + diff --git a/versioned_docs/version-1.0/enterprise/deployments-administration/overview.md b/versioned_docs/version-1.0/enterprise/deployments-administration/overview.md new file mode 100644 index 0000000000..49be0505e8 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/deployments-administration/overview.md @@ -0,0 +1,26 @@ +--- +keywords: [authentication, deployment, monitoring, Kubernetes, GreptimeDB Enterprise] +description: Comprehensive deployment guide for GreptimeDB Enterprise, covering authentication options, Kubernetes deployment procedures, and operational monitoring setup. +--- + +# Deployments & Administration + +Before reading this document, +it is recommended to review the [Deployments & Administration documentation](/user-guide/deployments-administration/overview.md) of the GreptimeDB open-source database version, +which covers all features that are also available in the enterprise edition. + +The following sections describe the enterprise-specific features and capabilities. + +## Configuration and Deployment + +- [Deploy GreptimeDB Enterprise on Kubernetes](./deploy-on-kubernetes/overview.md): Learn how to obtain the dedicated GreptimeDB Enterprise image. +- [LDAP Authentication](authentication.md): Enhanced authentication capabilities for GreptimeDB Enterprise. + +## Monitoring + +The [monitoring](./monitoring/overview.md) section describes the enterprise version specific metrics and logs. + +## Disaster Recovery + +The [disaster recovery](./disaster-recovery/overview.md) section provides strategies and best practices for ensuring data durability and availability in GreptimeDB Enterprise. + diff --git a/versioned_docs/version-1.0/enterprise/elasticsearch-compatible/aggregate.md b/versioned_docs/version-1.0/enterprise/elasticsearch-compatible/aggregate.md new file mode 100644 index 0000000000..29928925a2 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/elasticsearch-compatible/aggregate.md @@ -0,0 +1,27 @@ +--- +keywords: [ES, Elasticsearch, GreptimeDB, QueryDSL] +description: QueryDSL syntax supported by GreptimeDB Enterprise Edition +--- + +# Aggregation Queries + +## Metric Aggregations + +In GreptimeDB, metric aggregations are used to perform statistical calculations on numeric fields, such as sum, average, maximum, minimum, etc. + +| Aggregation | Status | Description | +| ----------- | ------ | ------------------------------------------------------------ | +| sum | | Aggregates to calculate the sum of numeric fields. | +| avg | | Aggregates to calculate the average of numeric fields. | +| max | | Aggregates to calculate the maximum value of numeric fields. | +| min | | Aggregates to calculate the minimum value of numeric fields. | +| count | ✅ | Aggregates to calculate the number of documents. | + +## Bucket Aggregations + +In GreptimeDB, bucket aggregations are used to group documents, such as bucketing by time, category, or other fields. + +| Aggregation | Status | Description | +| -------------- | ------ | ------------------------------------------ | +| date_histogram | ✅ | Aggregates to bucket by time fields. | +| terms | | Aggregates to group by values of specified | diff --git a/versioned_docs/version-1.0/enterprise/elasticsearch-compatible/overview.md b/versioned_docs/version-1.0/enterprise/elasticsearch-compatible/overview.md new file mode 100644 index 0000000000..76c40c9abb --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/elasticsearch-compatible/overview.md @@ -0,0 +1,54 @@ +--- +keywords: [ES, Elasticsearch, GreptimeDB] +description: Overview of GreptimeDB Enterprise Edition's compatibility with Elasticsearch, including comparisons of data models, query syntax, and API interfaces. +--- + +# Overview + +The Elasticsearch compatibility layer in GreptimeDB is designed to provide a certain degree of compatibility with Elasticsearch, allowing users to migrate existing Elasticsearch applications to GreptimeDB with relative ease. + +However, GreptimeDB does not fully support all features and functionalities of Elasticsearch. In some cases, users may need to adjust or modify their applications to achieve the same functionality in GreptimeDB. + +## Principle + +Essentially, GreptimeDB receives Elasticsearch QueryDSL syntax, converts it to GreptimeDB's query syntax, and returns data in the Elasticsearch API format to achieve compatibility. + +## Supported API List + +| API | Method | Description | +| ------------------------------ | ------ | -------------------- | +| /\{table_name\}/\_search | POST | Execute search query | +| /\{table_name\}/\_async_search | POST | Execute search query | +| /\_resolve/index/\{schema_name\} | POST | Index document | +| /\{table_name\}/\_field_caps | GET | Get field info | + +## Supported Query List + +| Query | Description | +| ------------ | ----------------- | +| match | Match query | +| match_phrase | Phrase match | +| match_all | Match all | +| term | Exact match | +| prefix | Prefix match | +| range | Range query | +| exists | Field existence | +| bool | Compound query | +| aggregation | Aggregation query | + +## Supported Aggregation List + +| Aggregation | Status | Description | +| -------------- | ------ | -------------- | +| avg | | Average value | +| sum | | Sum | +| min | | Minimum value | +| max | | Maximum value | +| count | ✅ | Count | +| date_histogram | ✅ | Date histogram | +| histogram | | Histogram | +| terms | | Terms | + +## Querying GreptimeDB with Kibana + +For more information, please contact us. diff --git a/versioned_docs/version-1.0/enterprise/elasticsearch-compatible/query.md b/versioned_docs/version-1.0/enterprise/elasticsearch-compatible/query.md new file mode 100644 index 0000000000..e15bed4eec --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/elasticsearch-compatible/query.md @@ -0,0 +1,63 @@ +--- +keywords: [ES, Elasticsearch, GreptimeDB, QueryDSL] +description: QueryDSL syntax supported by GreptimeDB Enterprise Edition +--- + +# Query + +Since GreptimeDB and Elasticsearch are designed for different purposes, many features are not compatible. We have provided corresponding alternatives as much as possible. For each specific interface, we will explain GreptimeDB's implementation and the differences from Elasticsearch. + +:::tip +All features related to boost scores are not supported. + +The `_id` field is not automatically added or maintained. If you need to use it, please include this field in your original data. + +Using @timestamp as a time field is not supported. + +It is not allowed to include both query and aggregation in the same request. +::: + +## Query Syntax + +### match + +In GreptimeDB, the `match` query is used to match one or more terms in a text field. + +The following options are not supported: analyzer, auto_generate_synonyms_phrase_query, fuzziness, max_expansions, prefix_length, fuzzy_transpositions, fuzzy_rewrite, lenient, operator, minimum_should_match, zero_terms_query. + +### match_phrase + +In GreptimeDB, the `match_phrase` query is used to match a phrase in a text field. Different queries are generated based on the data type. If the data type is text, it is converted to a LIKE query. For other data types, it is converted to an equivalent value query. + +The following options are not supported: analyzer, auto_generate_synonyms_phrase_query, fuzziness, max_expansions, prefix_length, fuzzy_transpositions, fuzzy_rewrite, lenient, operator, minimum_should_match, zero_terms_query. + +### match_all + +In GreptimeDB, the `match_all` query is used to match all documents. + +### term + +In GreptimeDB, the `term` query is used to match an exact value in a text field. The query is mainly converted to an equality query. + +Currently, case_insensitive is not supported. + +### prefix + +In GreptimeDB, the `prefix` query is used to match a prefix in a text field. The query is mainly converted to a LIKE query. +For example, if you query for text starting with `yi`, it will be converted to `LIKE 'yi%'`. + +The following options are not supported: rewrite, case_insensitive. + +### range + +In GreptimeDB, the `range` query is used to match a range in a text field. The query is mainly converted to greater than or equal to and less than or equal to conditions. + +Currently, format, relation, time_zone, and boost are not supported. + +### exists + +In GreptimeDB, the `exists` query is used to match values that exist in a text field. The query is mainly converted to an existence condition. + +### bool + +In GreptimeDB, the `bool` query is used to match multiple query conditions. The query is mainly converted to a combination of AND and OR conditions. \ No newline at end of file diff --git a/versioned_docs/version-1.0/enterprise/overview.md b/versioned_docs/version-1.0/enterprise/overview.md new file mode 100644 index 0000000000..5a6d0c6014 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/overview.md @@ -0,0 +1,47 @@ +--- +keywords: [enterprise, features, solutions, cloud, edge, IoT, observability, LDAP, audit logging] +description: Overview of GreptimeDB Enterprise, detailing its advanced features, solutions, and enhancements over the open-source version to optimize data efficiency and reduce costs. +--- + +# Enterprise + +GreptimeDB Enterprise is a powerful time-series database solution designed to meet the specific needs of enterprises. +In addition to the features available in the open-source version of GreptimeDB, +the Enterprise edition offers enhancements that help businesses optimize data efficiency and significantly reduce costs, enabling smarter and faster decision-making with time-series data. + +GreptimeDB Enterprise solutions include: + +- **Bring Your Own Cloud (BYOC)**: Leverage your own cloud infrastructure to host GreptimeDB, offering extensive customization and flexibility tailored to your business needs. This service includes comprehensive management of your cloud resources and robust security measures to protect your infrastructure. +- **Fully Managed Dedicated Cloud**: GreptimeDB team offers a fully managed, dedicated cloud environment, ensuring peak performance, enhanced security, and exceptional reliability tailored to your enterprise needs. +- **[Edge-Cloud Integrated Solution](https://greptime.com/product/carcloud)**: A comprehensive solution for managing time-series data from edge devices to the cloud, enabling real-time analytics and insights across your entire infrastructure. +- Industry-specific solutions for the Internet of Things (IoT), observability, and more. + +## Features + +GreptimeDB Enterprise supports all features available in the open-source version, +which you can read about in the [User Guide](/user-guide/overview.md) documentation. +To understand the differences between the open-source and enterprise versions, +please visit our [Pricing Page](https://greptime.com/pricing) or [contact us](https://greptime.com/contactus). + +GreptimeDB Enterprise includes the following advanced features, +which are described in detail in the documentation in this section: + +- [Active-Active Failover Disaster Recovery Solution](./deployments-administration/disaster-recovery/overview.md): Ensure uninterrupted service and data protection with advanced disaster recovery solution. +- [LDAP Authentication](./deployments-administration/authentication.md): Secure your system with LDAP-based authentication for access management. +- [Audit Logging](./deployments-administration/monitoring/audit-logging.md): Track and monitor + user activity with detailed audit logs. +- [Automatic region load balance](./autopilot/region-balancer.md): Auto balance + datanodes workload by moving regions between them. +- [Elasticsearch query compatibility](./elasticsearch-compatible/overview.md): Use GreptimeDB backed Kibana for your logs. +- [Greptime Enterprise Management Console](./console-ui.md): An enhanced version of our dashboard UI, + carries more cluster management and monitoring features. +- [Read Replica](./read-replicas/overview.md): Read-only datanode instances for heavy query workloads such as + analytical queries. +- [Triggers](./trigger.md): Periodically evaluate your rules and trigger external + webhook. Compatible with Prometheus AlterManager. +- Reliability features for Flow. + +## Release Notes + +- [25.05](./release-notes/release-25_05.md) +- [24.11](./release-notes/release-24_11.md) diff --git a/versioned_docs/version-1.0/enterprise/read-replicas/manage-read-replicas.md b/versioned_docs/version-1.0/enterprise/read-replicas/manage-read-replicas.md new file mode 100644 index 0000000000..9b9e26ec84 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/read-replicas/manage-read-replicas.md @@ -0,0 +1,181 @@ +--- +keywords: [enterprise, cluster, read replicas, leader region, follower region] +description: An overview, key concepts, and step-by-step guides for managing read replicas in GreptimeDB Enterprise. +--- + +# Manage Read Replicas + +This guide explains how to manage **Read Replicas (follower regions)** in GreptimeDB Enterprise, including how to add and remove read replicas at both the table and region levels, inspect the current regions distribution with the `SHOW REGION`, and apply placement constraints and recommended best practices for performance. + +## Adding Read Replicas to a Table + +Adding a Read Replica is as simple as executing one SQL command: + +```sql +ADMIN ADD_TABLE_FOLLOWER() +``` + +Read Replica peers for each region are allocated based on the workload types of the datanodes. **For optimal performance, it is strongly recommended to [configure Datanode groups](/enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups.md) to separate read and write workloads into different datanode groups.** + +This is the function in GreptimeDB for adding read replicas to. The parameters are: + +- `table_name`: The name of the table to add read replicas to. + +Next is an example to illustrate steps to add read replicas to a table. + +First start a GreptimeDB Enterprise Cluster with 3 Datanodes. Then create a table: + +```sql +CREATE TABLE foo ( + ts TIMESTAMP TIME INDEX, + i INT PRIMARY KEY, + s STRING, +) PARTITION ON COLUMNS ('i') ( + i <= 0, + i > 0, +); +``` + + +Using the `SHOW REGION`, we can find the regions distribution information: + +```sql +SHOW REGION FROM foo; + ++-------+---------------+------+--------+ +| Table | Region | Peer | Leader | ++-------+---------------+------+--------+ +| foo | 4398046511104 | 0 | Yes | +| foo | 4398046511105 | 1 | Yes | ++-------+---------------+------+--------+ +``` + +This shows two write replicas (leader regions) on Datanodes `1` and `2`. + +Then to add read replicas (Follower regions): + +```sql +ADMIN ADD_TABLE_FOLLOWER('foo'); +``` + +After the read replicas are added, find the regions distribution information: + +```sql +SHOW REGION FROM foo; + ++-------+---------------+------------+--------+ +| Table | Region | Peer | Leader | ++-------+---------------+------------+--------+ +| foo | 4398046511104 | 0 | Yes | +| foo | 4398046511104 | 4294967296 | No | +| foo | 4398046511105 | 1 | Yes | +| foo | 4398046511105 | 4294967297 | No | ++-------+---------------+------------+--------+ +``` + +Now, read replicas can be found on Datanode `4294967296` and `4294967297`. + +## Removing Read Replicas from a Table + +Removing a Read Replica is as simple as executing one SQL command: + +```sql +ADMIN REMOVE_TABLE_FOLLOWER() +``` + +This is the function in GreptimeDB for removing read replicas from a table. The parameters are: + +- `table_name`: The name of the table to remove read replicas from. + +This command removes **the most recently added read replica' peers from each region**. + +For example, before running the command: + +```sql +SHOW REGION FROM foo; ++-------+---------------+------------+--------+ +| Table | Region | Peer | Leader | ++-------+---------------+------------+--------+ +| foo | 4398046511104 | 0 | Yes | +| foo | 4398046511104 | 4294967296 | No | +| foo | 4398046511104 | 4294967297 | No | +| foo | 4398046511105 | 1 | Yes | +| foo | 4398046511105 | 4294967296 | No | +| foo | 4398046511105 | 4294967297 | No | ++-------+---------------+------------+--------+ +``` + +Here, region `4398046511104` has two read replicas on peers (`4294967296`, `4294967297`), and region `4398046511105` also has two read replicas on peers (`4294967296`, `4294967297`). +After executing: + +```sql +ADMIN REMOVE_TABLE_FOLLOWER('foo'); ++------------------------------------+ +| ADMIN REMOVE_TABLE_FOLLOWER('foo') | ++------------------------------------+ +| 0 | ++------------------------------------+ +``` + +The most recently added read replicas' peers of each region are removed: + +* Region `4398046511104`: removed read replica on peer `4294967297`. +* Region `4398046511105`: removed read replica on peer `4294967296`. + +Result: + +```sql +SHOW REGION FROM foo; ++-------+---------------+------------+--------+ +| Table | Region | Peer | Leader | ++-------+---------------+------------+--------+ +| foo | 4398046511104 | 0 | Yes | +| foo | 4398046511104 | 4294967296 | No | +| foo | 4398046511105 | 1 | Yes | +| foo | 4398046511105 | 4294967297 | No | ++-------+---------------+------------+--------+ +``` + +## Adding Read Replica to a Region +```sql +ADMIN ADD_REGION_FOLLOWER(, ) +``` + +This is the function in GreptimeDB for adding read replicas to a region. The parameters are: + +- `region_id`: The id of the region to add Read Replica to. +- `datanode_id`: The id of the datanode to add Read Replica to. + +A read replica and a write replica cannot be placed on the same datanode. Additionally, each datanode can host only one read replica per region. + +Example: + +```sql +-- Add a read replica for region 4398046511104 on datanode 2 +ADMIN ADD_REGION_FOLLOWER(4398046511104, 2); +``` + +If the specified datanode already hosts a read replica for that region, or is the write replica (leader) of that region, the command will be rejected. + +## Removing Read Replica from a Region +```sql +ADMIN REMOVE_REGION_FOLLOWER(, ) +``` + +This is the function in GreptimeDB for removing read replicas from a region. The parameters are: + +- `region_id`: The id of the region to remove read replica from. +- `datanode_id`: The id of the datanode to remove read replica from. + + +Example: + +```sql +-- Remove the read replica on datanode 2 for region 4398046511104 +ADMIN REMOVE_REGION_FOLLOWER(4398046511104, 2); +``` + + +## Next steps + +* [Query Read Replicas](/enterprise/read-replicas/query-read-replicas.md) diff --git a/versioned_docs/version-1.0/enterprise/read-replicas/overview.md b/versioned_docs/version-1.0/enterprise/read-replicas/overview.md new file mode 100644 index 0000000000..13569addfc --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/read-replicas/overview.md @@ -0,0 +1,50 @@ +--- +keywords: [enterprise, cluster, read replica, leader region, follower region] +description: Overview, principles, and how-tos of read replica feature in GreptimeDB Enterprise. +--- + +# Overview + +Read Replica is a key feature in GreptimeDB's Enterprise Cluster Edition, designed to enhance the overall read-write performance and scalability of the database system. + +In the Read Replica mechanism, clients write data to the **Leader Region (write replica)**, which then synchronizes the data to **Follower Regions (read replicas)**. Follower Regions serve as read-only replicas of the Leader Region. By [configuring Datanode groups](/enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups.md), Leader Regions and Follower Regions can be deployed on different Datanode nodes, read and write requests are effectively isolated, preventing resource contention and delivering a smoother experience: + +

+ read-replica-overview +

+ + +## Principles + +GreptimeDB's Enterprise Cluster Edition leverages its architecture to enable near-zero-cost data synchronization between replicas. Additionally, Read Replicas can access newly written data with minimal latency. Below is a brief explanation of the data synchronization and read mechanisms. + +### Data Synchronization + +In GreptimeDB, storage and compute resources are disaggregated. All data is stored in SST files on object storage. Thus, synchronizing data between Leader and Follower Regions does not require copying SST files -- only their metadata needs to be synced. Metadata is significantly smaller than SST files, making synchronization effortless. Once metadata is synced, the Read Replica "possesses" the same SST files and can access the data: + +![read-replica-data-sync](/read-replica-data-sync.png) + +In practice, SST files metadata is persisted in a special manifest file, also stored in object storage. Each manifest file has a unique version number. Synchronizing metadata between Leader and Follower Regions essentially involves syncing this version number -- a simple integer, ensuring minimal overhead. After receiving the version number, the Follower Region fetches the manifest file from object storage, thereby obtaining the SST files metadata generated by the Leader Region. + +The manifest version number is synchronized via heartbeats between Regions and Metasrv. The Leader Region includes the version number in its heartbeat to Metasrv, which then forwards it to Follower Regions in their heartbeat responses: + +![read-replica-heartbeat](/read-replica-heartbeat.png) + +It's easy to see, if there were only SST files synchronization mechanism in place, the delay for Read Replica to access written data would be the sum of the heartbeat intervals between Leader/Follower Regions and Metasrv. For example, with a default 3-second heartbeat interval, Read Replica would only see the data that are written to SST files and flushed to object store 3 to 6 seconds prior. While this suffices for clients with relaxed freshness requirements, additional mechanisms are needed for near-real-time reads. + +### Data Read + +Newly written data are stored in the Leader Region’s memtable. To access the latest data, Follower Region needs to request the memtable data from the Leader Region. By combining this with SST files data (obtained via data sync above), the Follower Region provides clients with a complete dataset, including the most recent writes: + +

+ read-replica-data-read +

+ +Follower Region fetch memtable data from Leader Region via an internal gRPC interface. While this imposes some read load on the Leader Region, the impact is minimal since the memtable data resides in memory and is finite in size. + +## Next steps + +* [Manage Read Replicas](/enterprise/read-replicas/manage-read-replicas.md) +* [Query Read Replicas](/enterprise/read-replicas/query-read-replicas.md) + + diff --git a/versioned_docs/version-1.0/enterprise/read-replicas/query-read-replicas.md b/versioned_docs/version-1.0/enterprise/read-replicas/query-read-replicas.md new file mode 100644 index 0000000000..012083b7c4 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/read-replicas/query-read-replicas.md @@ -0,0 +1,100 @@ +--- +keywords: [enterprise, cluster, read replica, leader region, follower region] +description: Overview, key concepts, and step-by-step instructions for managing and querying read replicas in GreptimeDB Enterprise. +--- + +# Query Read Replicas + +GreptimeDB allows you to read from **Region Replicas (follower regions)** to reduce load on Write Replicas (Leader regions) and improve query scalability. You can control the read preference through both **SQL** and **HTTP** protocols. + +## Read Preference Options + +The `READ_PREFERENCE` setting accepts the following values: + +* **`leader`** + Always read from write replicas. + +* **`follower`** + Read only from read replicas The query will fail if no read replicas exist. + +* **`follower_preferred`** + Prefer read replicas but fall back to write replicas if read replicas are unavailable. + +## SQL Protocol + +You can set the read preference in a SQL session: + +```sql +SET READ_PREFERENCE = 'follower'; +``` + +--- + +## HTTP Protocol + +For HTTP requests, specify the `X-Greptime-Read-Preference` header. + +Example: + +```bash +curl -X POST \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -H "X-Greptime-Read-Preference: follower" \ + -d "sql=select * from monitoring" \ + http://localhost:4000/v1/sql +``` + +--- + +## Example: Reading from Read Replicas + +Before reading from Read Replicas, you need to add Read Replicas to the table. See [Replica Management](/enterprise/read-replicas/manage-read-replicas.md) for more details. + +Insert some data into a table: + +```sql +INSERT INTO foo (ts, i, s) +VALUES + (1, -1, 's1'), + (2, 0, 's2'), + (3, 1, 's3'); +``` + +Set the read preference to read replicas: + +```sql +SET READ_PREFERENCE = 'follower'; +``` + +Query the data: + +```sql +SELECT * FROM foo ORDER BY ts; + ++----------------------------+------+------+ +| ts | i | s | ++----------------------------+------+------+ +| 1970-01-01 00:00:00.001000 | -1 | s1 | +| 1970-01-01 00:00:00.002000 | 0 | s2 | +| 1970-01-01 00:00:00.003000 | 1 | s3 | ++----------------------------+------+------+ +``` + +--- + +## Verifying Follower Reads + +To confirm that queries are served by read replicas, use `EXPLAIN ANALYZE`: + +```sql +EXPLAIN ANALYZE SELECT * FROM foo ORDER BY ts; +``` + +* A **non-zero `other_ranges`** value indicates read replicas were involved. +* With the `VERBOSE` option, you can see details like this: + +```plaintext +extension_ranges: [LeaderMemtableRange{leader: Peer { id: 1, addr: "192.168.50.189:14101" }, num_rows: 2, time_range: (1::Millisecond, 2::Millisecond) ... +``` + +If the query runs only on leaders, this `extension_ranges` section will not appear. diff --git a/versioned_docs/version-1.0/enterprise/release-notes/release-24_11.md b/versioned_docs/version-1.0/enterprise/release-notes/release-24_11.md new file mode 100644 index 0000000000..0b2c6a79c9 --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/release-notes/release-24_11.md @@ -0,0 +1,60 @@ +--- +keywords: [release notes, region rebalancing, management console, LDAP, audit logs, new features] +description: Release notes for GreptimeDB Enterprise version 24.11, highlighting new features like region rebalancing, management console, LDAP user provider, and audit logs. +--- + +# Release 24.11 + +We are pleased to introduce the 24.11 release of GreptimeDB Enterprise. + +## Feature Highlights + +### Region Rebalance + +To enhance the overall resilience of GreptimeDB, region rebalancing enables +flexible relocation of regions among data nodes, whether initiated manually or +dynamically. + +This proactive approach facilitates several key benefits, including +redistributing workload across nodes and efficiently migrating regions to ensure +uninterrupted operation during planned maintenance activities. + +### GreptimeDB Enterprise Management Console + +Introducing the Console UI for Managing GreptimeDB Enterprise + +This initial release provides a comprehensive set of features, including: + +* In-depth slow query analysis and troubleshooting +* Detailed cluster topology information +* Real-time cluster metrics and log viewer + +### LDAP User Provider + +Bridging your own LDAP user database and authentication to GreptimeDB +Enterprise. We implemented flexible configuration options for LDAP connections, +supporting both simple and complex authentication mechanisms. + +### Audit Logs + +We provided logs to track queries in the database, with information of: + +- Query type: read, write, DDL or others +- Command: select, insert, etc. +- Object type: target of the operation, for example, table, database, etc. + +## Features From GreptimeDB OSS + +This release is based on GreptimeDB OSS v0.10. The OSS base introduces a few +new features includes + +- Vector data type support for similarity search. +- Secondary index update: user can now create secondary index on any columns. +- Alter table options are added for updating table TTL, compaction parameters + and full-text index settings. +- JSON data type and functions support. +- More geospatial UDF: spatial relation and measurement, S2 index and etc. +- Initial release of Loki remote write support. + +See [this](https://docs.greptime.com/release-notes/release-0-10-0) for a +complete changelog of 0.10 diff --git a/versioned_docs/version-1.0/enterprise/release-notes/release-25_05.md b/versioned_docs/version-1.0/enterprise/release-notes/release-25_05.md new file mode 100644 index 0000000000..7a40767c4e --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/release-notes/release-25_05.md @@ -0,0 +1,71 @@ +--- +keywords: [release notes, elasticsearch, read replicas, triggers] +description: Release notes for GreptimeDB Enterprise version 25.05, highlighting new features like elasticsearch compatibility, read replicas and triggers. +--- + +# GreptimeDB Enterprise 25.05 + +We are pleased to introduce the 25.05 release of GreptimeDB Enterprise. + +## Feature Highlights + +### Elasticsearch Compatibility + +The compatibility layer in GreptimeDB Enterprise for Elasticsearch. This layer +allows user to configure GreptimeDB Enterprise as the backend of Kibana UI, for +log search, aggregation and dashboard. + +Queries supported in this release: + +- match +- match_all +- multi_match +- term +- terms +- prefix +- wildcard +- regexp +- range +- exists +- bool + +### Read Replicas + +To serve analytical and other heavy queries better, we introduce dedicated query +nodes in this release. These type of nodes are responsible for serve queries +only, so we can push them to resource limit without affecting data ingestion. + +Thanks to our compute-storage disaggregated architecture, it's not a huge +refactoring to add read replicas to current architecture. A new type of +datanodes will play the role. It's dedicated to process query workloads. Because +data are available on object storage, there will be no data replication between +these types of datanodes and those original ones who take writes. User will be +able to add hint to their queries to specify whether the query should run on +read replicas. + +### Triggers + +Trigger evaluate data with your predefined rules periodically and invoke +webhooks if it matches. This is the initial version of triggers. Of course we +designed it to work with Prometheus AlertManager. + +```sql +CREATE TRIGGER IF NOT EXISTS cpu_monitor + ON (SELECT host AS host_label, cpu, memory FROM machine_monitor WHERE cpu > 1 and ts >= now() - '5 minutes'::INTERVAL) + EVERY '5 minute'::INTERVAL + LABELS (severity = 'warning') + ANNOTATIONS (summary = 'CPU utilization is too high', link = 'http://...') + NOTIFY( + WEBHOOK alert_manager URL 'http://127.0.0.1:9093' WITH (timeout="1m") + ); +``` + +### Flow Reliability + +Reliability features are added to flow, our light-weighted streaming engine: + +- Task migration: move tasks between flow nodes for load balancing. + +## Features From GreptimeDB OSS + +This release is based on GreptimeDB OSS v0.14. diff --git a/versioned_docs/version-1.0/enterprise/trigger.md b/versioned_docs/version-1.0/enterprise/trigger.md new file mode 100644 index 0000000000..5e07b7f38e --- /dev/null +++ b/versioned_docs/version-1.0/enterprise/trigger.md @@ -0,0 +1,154 @@ +--- +keywords: [Trigger, GreptimeDB Enterprise, SQL, Webhook] +description: The overview of GreptimeDB Trigger. +--- + +# Trigger + +Trigger allows you to define evaluation rules with SQL. +GreptimeDB evaluates these rules periodically; once the condition is met, a +notification is sent out. + +The following content is a quick start example that sets up a Trigger to monitor system load and raise alerts step by step. +For details on how to write a Trigger, +please refer to the [Syntax](/reference/sql/trigger-syntax.md) documentation. + +## Quick Start Example + +This section walks through an end-to-end example that uses Trigger to monitor +system load and raise an alert. + +The diagram illustrates the complete end-to-end workflow of the example. + +![Trigger demo architecture](/trigger-demo-architecture.png) + +1. Vector continuously scrapes host metrics and writes them to GreptimeDB. +2. A Trigger in GreptimeDB evaluates a rule every minute; whenever the condition + is met, it sends a notification to Alertmanager. +3. Alertmanager applies its own policies and finally delivers the alert to Slack. + +### Use Vector to Scrape Host Metrics + +Use Vector to scrape host metrics and write it to GreptimeDB. Below is a Vector +configuration example: + +```toml +[sources.in] +type = "host_metrics" +scrape_interval_secs = 15 + +[sinks.out] +inputs = ["in"] +type = "greptimedb" +endpoint = "localhost:4001" +``` + +GreptimeDB auto-creates tables on the first write. The `host_load1` table stores +the system load averaged over the last minute. It is a key performance indicator +for measuring system activity. We can create a monitoring rule to track values +in this table. The schema of this table is shown below: + +```sql ++-----------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-----------+----------------------+------+------+---------+---------------+ +| ts | TimestampMillisecond | PRI | NO | | TIMESTAMP | +| collector | String | PRI | YES | | TAG | +| host | String | PRI | YES | | TAG | +| val | Float64 | | YES | | FIELD | ++-----------+----------------------+------+------+---------+---------------+ +``` + +### Set up Alertmanager with a Slack Receiver + +The payload of GreptimeDB Trigger's Webhook is compatible with [Prometheus +Alertmanager](https://prometheus.io/docs/alerting/latest/alertmanager/), so we +can reuse Alertmanager’s grouping, inhibition, silencing and routing features +without any extra glue code. + +You can refer to the [official documentation](https://prometheus.io/docs/alerting/latest/configuration/) +to configure Prometheus Alertmanager. Below is a minimal message template you +can use: + +```text +{{ define "slack.text" }} +{{ range .Alerts }} + +Labels: +{{- range .Labels.SortedPairs }} +- {{ .Name }}: {{ .Value }} +{{ end }} + +Annotations: +{{- range .Annotations.SortedPairs }} +- {{ .Name }}: {{ .Value }} +{{ end }} + +{{ end }} +{{ end }} +``` + +Generating a Slack message using the above template will iterate over all alerts +and display the labels and annotations for each alert. + +Start Alertmanager once the configuration is ready. + +### Create Trigger + +Connect to GreptimeDB with MySql client and run the following SQL: + +```sql +CREATE TRIGGER IF NOT EXISTS load1_monitor + ON ( + SELECT collector AS label_collector, + host as label_host, + val + FROM host_load1 WHERE val > 10 and ts >= now() - '1 minutes'::INTERVAL + ) EVERY '1 minute'::INTERVAL + LABELS (severity=warning) + ANNOTATIONS (comment='Your computer is smoking, should take a break.') + NOTIFY( + WEBHOOK alert_manager URL 'http://localhost:9093' WITH (timeout="1m") + ); +``` + +The above SQL will create a trigger named `load1_monitor` that runs every minute. +It evaluates the last 60 seconds of data in `host_load1`; if any load1 value +exceeds 10, the `WEBHOOK` option in the `NOTIFY` syntax specifies that this +trigger will send a notification to Alertmanager which running on localhost with +port 9093. + +You can execute `SHOW TRIGGERS` to view the list of created Triggers. + +```sql +SHOW TRIGGERS; +``` + +The output should look like this: + +```text ++---------------+ +| Triggers | ++---------------+ +| load1_monitor | ++---------------+ +``` + +### Test Trigger + +Use [stress-ng](https://github.com/ColinIanKing/stress-ng) to simulate high CPU +load for 60s: + +```bash +stress-ng --cpu 100 --cpu-load 10 --timeout 60 +``` + +The load1 will rise quickly, the Trigger notification will fire, and within a +minute Slack channel will receive an alert like: + +![Trigger slack alert](/trigger-slack-alert.png) + +## Reference + +- [Syntax](/reference/sql/trigger-syntax.md): The syntax for SQL statements related to `TRIGGER`. + diff --git a/versioned_docs/version-1.0/faq-and-others/faq.md b/versioned_docs/version-1.0/faq-and-others/faq.md new file mode 100644 index 0000000000..7bc97261e0 --- /dev/null +++ b/versioned_docs/version-1.0/faq-and-others/faq.md @@ -0,0 +1,431 @@ +--- +keywords: [unified observability, metrics, logs, traces, performance, OpenTelemetry, Prometheus, Grafana, cloud-native, SQL, PromQL] +description: Frequently Asked Questions about GreptimeDB - the unified observability database for metrics, logs, and traces. +--- + +# Frequently Asked Questions + +## Core Capabilities + +### What is GreptimeDB? + +GreptimeDB is an open-source, cloud-native unified observability database designed to store and analyze metrics, logs, and traces in a single system. Built with Rust for high performance, it offers: +- Up to 50x lower operational and storage costs +- Sub-second query responses on petabyte-scale datasets +- Native OpenTelemetry support +- SQL, PromQL, and stream processing capabilities +- Compute-storage separation for flexible scaling + +### How is GreptimeDB's performance compared to other solutions? + +GreptimeDB delivers superior performance across observability workloads: + +**Write Performance**: +- **2-4.7x faster** than Elasticsearch (up to 470% throughput) +- **1.5x faster** than Loki (121k vs 78k rows/s) +- **2x faster** than InfluxDB (250k-360k rows/s) +- **Matches ClickHouse** performance (111% throughput) + +**Query Performance**: +- **40-80x faster** than Loki for log queries +- **500x faster** for repeated queries (with caching) +- **2-11x faster** than InfluxDB for complex time-series queries +- Competitive with ClickHouse across different query patterns + +**Storage & Cost Efficiency**: +- **87% less storage** than Elasticsearch (12.7% footprint) +- **50% less storage** than ClickHouse +- **50% less storage** than Loki (3.03GB vs 6.59GB compressed) +- **Up to 50x lower** operational costs vs traditional stacks + +**Resource Optimization**: +- **40% less CPU** usage compared to previous versions +- **Lowest memory consumption** among tested databases +- Consistent performance on object storage (S3/GCS) +- Superior high-cardinality data handling + +**Unique Advantages**: +- Single database for metrics, logs, and traces +- Native cloud-native architecture +- Horizontal scalability (handles 1.15B+ rows) +- Full-text search with native indexing + +Benchmark reports: [vs InfluxDB](https://greptime.com/blogs/2024-08-07-performance-benchmark) | [vs Loki](https://greptime.com/blogs/2025-08-07-beyond-loki-greptimedb-log-scenario-performance-report) | [Log Benchmark](https://greptime.com/blogs/2025-03-10-log-benchmark-greptimedb) + +### How does GreptimeDB handle metrics, logs, and traces? + +GreptimeDB is designed as a unified observability database that natively supports all three telemetry types: +- **Metrics**: Full Prometheus compatibility with PromQL support +- **Logs**: Full-text indexing, Loki protocol support, and efficient compression +- **Traces**: Experimental OpenTelemetry trace storage with scalable querying + +This unified approach eliminates data silos and enables cross-signal correlation without complex data pipelines. + +For detailed documentation: +- [Log Overview](/user-guide/logs/overview.md) +- [Trace Overview](/user-guide/traces/overview.md) +- [OpenTelemetry compatibility](/user-guide/ingest-data/for-observability/opentelemetry.md) +- [Prometheus compatibility](/user-guide/ingest-data/for-observability/prometheus.md) +- [Loki protocol compatibility](/user-guide/ingest-data/for-observability/loki.md) +- [Elasticsearch compatibility](/user-guide/ingest-data/for-observability/elasticsearch.md) +- [Vector compatibility](/user-guide/ingest-data/for-observability/vector.md) + +### What are the main use cases for GreptimeDB? + +GreptimeDB excels in: +- **Unified Observability**: Replace complex monitoring stacks with a single database +- **Edge and Cloud Data Management**: Seamless data synchronization across environments +- **IoT and Automotive**: Process high-volume sensor data efficiently +- **AI/LLM Monitoring**: Track model performance and behavior +- **Real-time Analytics**: Sub-second queries on petabyte-scale datasets + +## Architecture & Performance + +### Can GreptimeDB replace my Prometheus setup? + +Yes, GreptimeDB provides: +- Native PromQL support with near 100% compatibility +- Prometheus remote write protocol support +- Efficient handling of high-cardinality metrics +- Long-term storage without downsampling +- Better resource efficiency than traditional Prometheus+Thanos stacks + +### What indexing capabilities does GreptimeDB offer? + +GreptimeDB provides rich indexing options: +- **Inverted indexes**: Fast lookups on tag columns +- **Full-text indexes**: Efficient log searching +- **Skipping indexes**: Accelerate range queries +- **Vector indexes**: Support for AI/ML workloads + +These indexes enable sub-second queries even on petabyte-scale datasets. + +For configuration details, see [Index Management](/user-guide/manage-data/data-index.md). + +### How does GreptimeDB achieve cost efficiency? + +GreptimeDB reduces costs through: +- **Columnar storage**: Superior compression ratios +- **Compute-storage separation**: Independent scaling of resources +- **Efficient cardinality management**: Handles high-cardinality data without explosion +- **Unified platform**: Eliminates need for multiple specialized databases + +Result: Up to 50x lower operational and storage costs compared to traditional stacks. + +### What makes GreptimeDB cloud-native? + +GreptimeDB is purpose-built for Kubernetes with: +- **Disaggregated architecture**: Separate compute and storage layers +- **Elastic scaling**: Add/remove nodes based on workload +- **Multi-cloud support**: Run across AWS, GCP, Azure seamlessly +- **Kubernetes operators**: Simplified deployment and management +- **Object storage backend**: Use S3, GCS, or Azure Blob for data persistence + +For Kubernetes deployment details, see the [Kubernetes Deployment Guide](/user-guide/deployments-administration/deploy-on-kubernetes/overview.md). + +### Does GreptimeDB support schemaless data ingestion? + +Yes, GreptimeDB supports automatic schema creation when using: +- gRPC protocol +- InfluxDB Line Protocol +- OpenTSDB protocol +- Prometheus Remote Write +- OpenTelemetry protocol +- Loki protocol (for log data) +- Elasticsearch-compatible APIs (for log data) + +Tables and columns are created automatically on first write, eliminating manual schema management. + +## Integration & Compatibility + +### What protocols and tools does GreptimeDB support? + +GreptimeDB provides extensive compatibility: +- **Protocols**: OpenTelemetry, Prometheus Remote Write, InfluxDB Line, Loki, Elasticsearch, MySQL, PostgreSQL (see [Protocols Overview](/user-guide/protocols/overview.md)) +- **Query Languages**: SQL, PromQL +- **Visualization**: [Grafana integration](/user-guide/integrations/grafana.md), any MySQL/PostgreSQL compatible tool +- **Data Pipeline**: Vector, Fluent Bit, Telegraf, Kafka +- **SDKs**: Go, Java, Rust, Erlang, Python + +### Is GreptimeDB compatible with Grafana? + +Yes, GreptimeDB offers: +- [Grafana integration](/user-guide/integrations/grafana.md) with official plugin +- [MySQL/PostgreSQL protocol support](/user-guide/integrations/grafana.md#mysql-data-source) for standard Grafana data sources +- [Native PromQL](/user-guide/query-data/promql.md) for Prometheus-style queries +- SQL support for complex analytics + +### How does GreptimeDB integrate with OpenTelemetry? + +GreptimeDB is OpenTelemetry-native: +- Direct OTLP ingestion for metrics, logs, and traces +- No translation layer or data loss +- Supports OpenTelemetry Collector and SDKs +- Preserves semantic conventions and resource attributes + +### What SDKs are available for GreptimeDB? + +- **Go**: [greptimedb-ingester-go](https://github.com/GreptimeTeam/greptimedb-ingester-go) +- **Java**: [greptimedb-ingester-java](https://github.com/GreptimeTeam/greptimedb-ingester-java) +- **Rust**: [greptimedb-ingester-rust](https://github.com/GreptimeTeam/greptimedb-ingester-rust) +- **Erlang**: [greptimedb-ingester-erl](https://github.com/GreptimeTeam/greptimedb-ingester-erl) +- **Python**: Via SQL drivers (MySQL/PostgreSQL compatible) + +### How can I migrate from other databases to GreptimeDB? + +GreptimeDB provides migration guides for popular databases: +- **From ClickHouse**: Table schema and data migration +- **From InfluxDB**: Line protocol and data migration +- **From Prometheus**: Remote write and historical data migration +- **From MySQL/PostgreSQL**: SQL-based migration + +For detailed migration instructions, see [Migration Overview](/user-guide/migrate-to-greptimedb/overview.md). + +### What disaster recovery options does GreptimeDB provide? + +GreptimeDB offers multiple disaster recovery strategies to meet different availability requirements: + +- **Standalone DR Solution**: Uses remote WAL and object storage, achieving RPO=0 and RTO in minutes for small-scale scenarios +- **Region Failover**: Automatic failover for individual regions with minimal downtime +- **Active-Active Failover** (Enterprise): Synchronous request replication between nodes for high availability +- **Cross-Region Single Cluster**: Spans three regions with zero RPO and region-level error tolerance +- **Backup and Restore**: Periodic data backups with configurable RPO based on backup frequency + +Choose the appropriate solution based on your availability requirements, deployment scale, and cost considerations. For detailed guidance, see [Disaster Recovery Overview](/user-guide/deployments-administration/disaster-recovery/overview.md). + +## Data Management & Processing + +### How does GreptimeDB handle data lifecycle? + +**Retention Policies**: +- Database-level and table-level TTL settings +- Automatic data expiration without manual cleanup +- Configurable via [TTL Documentation](/reference/sql/create.md#table-options) + +**Data Export**: +- [`COPY TO` command](/reference/sql/copy.md#connect-to-s3) for S3, local files +- Standard SQL queries via any compatible client +- Export functionality for backup and disaster recovery: [Back up & Restore Data](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md) + +### How does GreptimeDB handle high-cardinality and real-time processing? + +**High-Cardinality Management**: +- Advanced indexing strategies prevent cardinality explosion +- Columnar storage with intelligent compression +- Distributed query execution with data pruning +- Handles millions of unique time series efficiently + +Learn more about indexing: [Index Management](/user-guide/manage-data/data-index.md) + +**Real-Time Processing**: +- **[Flow Engine](/user-guide/flow-computation/overview.md)**: Real-time stream processing system that enables continuous, incremental computation on streaming data with automatic result table updates +- **[Pipeline](/reference/pipeline/pipeline-config.md)**: Data parsing and transformation mechanism for processing incoming data in real-time, with configurable processors for field extraction and data type conversion across multiple data formats +- **Output Tables**: Persist processed results for analysis + + +### What are GreptimeDB's scalability characteristics? + +**Scale Limits**: +- No strict limitations on table or column count +- Hundreds of tables with minimal performance impact +- Performance scales with primary key design, not table count +- Column-oriented storage ensures efficient partial reads + +**Partitioning & Distribution**: +- Automatic time-based organization within regions +- Manual distributed sharding via PARTITION clause (see [Table Sharding Guide](/user-guide/deployments-administration/manage-data/table-sharding.md)) +- Automatic region splitting planned for future releases +- **Dynamic partitioning without configuration** (Enterprise feature) + +**Core Scalability Features**: +- **Multi-tiered caching**: Write cache (disk-backed) and read cache (LRU policy) for optimal performance +- **Object storage backend**: Virtually unlimited storage via S3/GCS/Azure Blob +- **Asynchronous WAL**: Efficient write-ahead logging with optional per-table controls +- **Distributed query execution**: Multi-node coordination for large datasets +- **Manual Compaction**: Available via [admin commands](/reference/sql/admin.md) + +**Enterprise Scale Features**: +- Advanced partitioning and automatic rebalancing +- Enhanced multi-tenancy and isolation +- Enterprise-grade monitoring and management tools + +For architecture details, see the [storage architecture blog](https://greptime.com/blogs/2025-03-26-greptimedb-storage-architecture). + +### What are GreptimeDB's design trade-offs? + +GreptimeDB is optimized for observability workloads with intentional limitations: +- **No ACID transactions**: Prioritizes high-throughput writes over transactional consistency +- **Limited delete operations**: Designed for append-heavy observability data +- **Time-series focused**: Optimized for IoT, metrics, logs, and traces rather than general OLTP +- **Simplified joins**: Optimized for time-series queries over complex relational operations + +## Deployment & Operations + +### What are the deployment options for GreptimeDB? + +**Cluster Deployment** (Production): +- Minimum 3 nodes for high availability +- Services: metasrv, frontend, and datanode on each node +- Can separate services for larger scale deployments +- See [Capacity Planning Guide](/user-guide/deployments-administration/capacity-plan.md) + +**Edge & Standalone**: +- Android ARM64 platforms (prebuilt binaries available) +- Raspberry Pi and constrained environments +- Single-node mode for development/testing +- Efficient resource usage for IoT scenarios + +**Storage Backends**: +- **Production**: S3, GCS, Azure Blob for data persistence +- **Development**: Local storage for testing +- **Metadata**: MySQL/PostgreSQL backend support for metasrv + +For deployment and administration details: [Deployments & Administration Overview](/user-guide/deployments-administration/overview.md) + +### How does data distribution work? + +**Current State**: +- Manual partitioning via PARTITION clause during table creation (see [Table Sharding Guide](/user-guide/deployments-administration/manage-data/table-sharding.md)) +- Time-based automatic organization within regions +- Manual region migration support for load balancing (see [Region Migration Guide](/user-guide/deployments-administration/manage-data/region-migration.md)) +- Automatic region failover for disaster recovery (see [Region Failover](/user-guide/deployments-administration/manage-data/region-failover.md)) + +**Roadmap**: +- Automatic region splitting and rebalancing +- Dynamic workload distribution across nodes + +### How do I monitor and troubleshoot GreptimeDB? + +GreptimeDB provides comprehensive monitoring capabilities including metrics collection, health checks, and observability integrations. For detailed monitoring setup and troubleshooting guides, see the [Monitoring Overview](/user-guide/deployments-administration/monitoring/overview.md). + +## Open Source vs Enterprise vs Cloud + +### What are the differences between GreptimeDB versions? + +**Open Source Version**: +- High-performance ingestion and query capabilities +- Cluster deployment with basic read-write separation +- Multiple protocol support (OpenTelemetry, Prometheus, InfluxDB, etc.) +- Basic authentication and access control +- Basic data encryption +- Community support + +**Enterprise Version** (all Open Source features plus): +- Cost-based query optimizer for better performance +- Advanced read-write separation and active-active failover (see [Active-Active Failover](/enterprise/deployments-administration/disaster-recovery/dr-solution-based-on-active-active-failover.md)) +- Automatic scaling, indexing, and load balancing +- Layered caching and enterprise-level web console +- Enterprise authorization (RBAC/LDAP integration) +- Enhanced security and audit features +- One-on-one technical support with 24/7 service response +- Professional customization services + +**GreptimeCloud** (fully managed, all Enterprise features plus): +- Serverless autoscaling with pay-as-you-go pricing +- Fully managed deployment with seamless upgrades +- Independent resource pools with isolated networks +- Configurable read/write capacity and unlimited storage +- Advanced dashboard with Prometheus workbench +- SLA guarantees and automated disaster recovery + +For detailed comparison, see [Pricing & Features](https://greptime.com/pricing#differences). + +### What security features are available? + +**Open Source**: +- Basic username/password authentication +- TLS/SSL support for connections + +**Enterprise/Cloud**: +- Role-based access control (RBAC) +- Team management and API keys +- Data encryption at rest +- Audit logging for compliance + +## Technical Details + +### How does GreptimeDB extend Apache DataFusion? + +GreptimeDB builds on DataFusion with: +- **Query Languages**: Native PromQL alongside SQL +- **Distributed Execution**: Multi-node query coordination +- **Custom Functions**: Time-series specific UDFs/UDAFs +- **Optimizations**: Rules tailored for observability workloads +- **Counter Handling**: Automatic reset detection in `rate()` and `delta()` functions + +For custom function development: [Function Documentation](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-write-aggregate-function.md) + +### What's the difference between GreptimeDB and InfluxDB? + +Key differences: +- **Open Source**: GreptimeDB's entire distributed system is fully open source +- **Architecture**: Region-based design optimized for observability workloads +- **Query Languages**: SQL + PromQL vs InfluxQL + SQL +- **Unified Model**: Native support for metrics, logs, and traces in one system +- **Storage**: Pluggable engines with dedicated optimizations +- **Cloud-Native**: Built for Kubernetes with disaggregated compute/storage (see [Kubernetes Deployment Guide](/user-guide/deployments-administration/deploy-on-kubernetes/overview.md)) + +For detailed comparisons, see [GreptimeDB vs InfluxDB](https://greptime.com/compare/influxdb). Additional product comparisons (vs. ClickHouse, Loki, etc.) are available in the Resources menu on our website. + +### How does GreptimeDB's storage engine work? + +**LSM-Tree Architecture**: +- Based on Log-Structured Merge Tree (LSMT) design +- WAL can use local disk or distributed services (e.g., Kafka) via Log Store API +- SST files are flushed to object storage (S3/GCS) or local disk +- Designed for cloud-native environments with object storage as primary backend +- Optimized for time-series workloads with TWCS (Time-Window Compaction Strategy) + +**Performance Considerations**: +- **Timestamps**: Datetime formats (yyyy-MM-dd HH:mm:ss) have no performance impact +- **Compression**: Measure only data directory; WAL is cyclically reused +- **Append-only tables**: Recommended for better write and query performance, especially for log scenarios +- **Flow Engine**: Currently SQL-based; PromQL support under evaluation + +### What are best practices for specific use cases? + +**Network Monitoring** (e.g., thousands of NICs): +- Use Flow tables for continuous aggregation +- Manual downsampling via Flow Engine for data reduction +- Output to regular tables for long-term storage + +**Log Analytics**: +- Use append-only tables for better write and query performance +- Create indexes on frequently queried fields ([Index Management](/user-guide/manage-data/data-index.md)) +- Storage efficiency: 50% of ClickHouse, 12.7% of Elasticsearch + +**Table Design & Performance**: +- For table modeling guidance: [Design Table](/user-guide/deployments-administration/performance-tuning/design-table.md) +- For performance optimization: [Performance Tuning Tips](/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md) + + +## Getting Started + +### Where can I find documentation and benchmarks? + +**Performance & Benchmarks**: +- [TSBS Benchmarks](https://github.com/GreptimeTeam/greptimedb/tree/main/docs/benchmarks/tsbs) +- [Performance Comparisons](/user-guide/concepts/features-that-you-concern.md#how-is-greptimedbs-performance-compared-to-other-solutions) +- [vs InfluxDB](https://greptime.com/blogs/2024-08-07-performance-benchmark) +- [vs Loki](https://greptime.com/blogs/2025-08-07-beyond-loki-greptimedb-log-scenario-performance-report) +- [Log Benchmark](https://greptime.com/blogs/2025-03-10-log-benchmark-greptimedb) + +**Installation & Deployment**: +- [Installation Guide](/getting-started/installation/overview.md) +- [Capacity Planning](/user-guide/deployments-administration/capacity-plan.md) +- [Configuration Guide](/user-guide/deployments-administration/configuration.md) + +### How can I contribute to GreptimeDB? + +Welcome to the community! Get started: +- **Code**: [Contribution Guide](https://github.com/GreptimeTeam/greptimedb/blob/main/CONTRIBUTING.md) +- **First Issues**: [Good First Issues](https://github.com/GreptimeTeam/greptimedb/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+first+issue%22) +- **Community**: [Slack Channel](https://greptime.com/slack) +- **Documentation**: [Help improve these docs!](https://github.com/GreptimeTeam/docs) + +### What's next? + +1. **Try GreptimeCloud**: [Free serverless tier](https://greptime.com/product/cloud) +2. **Self-host**: Follow the [installation guide](/getting-started/installation/overview.md) +3. **Explore Integrations**: GreptimeDB supports extensive integrations with Prometheus, Vector, Kafka, Telegraf, EMQX, Metabase, and many more. See [Integrations Overview](/user-guide/integrations/overview.md) for the complete list, or start with [OpenTelemetry](/user-guide/ingest-data/for-observability/opentelemetry.md) or [Prometheus](/user-guide/ingest-data/for-observability/prometheus.md) +4. **Join Community**: Connect with users and maintainers on [Slack](https://greptime.com/slack) \ No newline at end of file diff --git a/versioned_docs/version-1.0/faq-and-others/overview.md b/versioned_docs/version-1.0/faq-and-others/overview.md new file mode 100644 index 0000000000..26db3af01a --- /dev/null +++ b/versioned_docs/version-1.0/faq-and-others/overview.md @@ -0,0 +1,8 @@ +--- +keywords: [FAQ, questions] +description: In this section, we present the most frequently asked questions and some additional information. +--- + +# FAQ and Others + +In this section, we present the [most frequently asked questions](./faq.md) and some additional information. diff --git a/versioned_docs/version-1.0/getting-started/installation/greptimedb-cluster.md b/versioned_docs/version-1.0/getting-started/installation/greptimedb-cluster.md new file mode 100644 index 0000000000..18cf2aff60 --- /dev/null +++ b/versioned_docs/version-1.0/getting-started/installation/greptimedb-cluster.md @@ -0,0 +1,54 @@ +--- +keywords: [cluster mode, Kubernetes, Docker Compose, deployment] +description: Instructions to deploy GreptimeDB in cluster mode using Kubernetes or Docker Compose, including steps for setup and cleanup. +--- + +# GreptimeDB Cluster + +The GreptimeDB cluster can run in cluster mode to scale horizontally. + +## Deploy the GreptimeDB cluster in Kubernetes + +For production environments, we recommend deploying the GreptimeDB cluster in Kubernetes. Please refer to [Deploy on Kubernetes](/user-guide/deployments-administration/deploy-on-kubernetes/overview.md). + +## Use Docker Compose + +:::tip NOTE +Although Docker Compose is a convenient way to run the GreptimeDB cluster, it is only for development and testing purposes. + +For production environments or benchmarking, we recommend using Kubernetes. +::: + +### Prerequisites + +Using Docker Compose is the easiest way to run the GreptimeDB cluster. Before starting, make sure you have already installed the Docker. + +### Step1: Download the YAML file for Docker Compose + +``` +wget https://raw.githubusercontent.com/GreptimeTeam/greptimedb/VAR::greptimedbVersion/docker/docker-compose/cluster-with-etcd.yaml +``` + +### Step2: Start the cluster + +``` +GREPTIMEDB_VERSION=VAR::greptimedbVersion \ + docker compose -f ./cluster-with-etcd.yaml up +``` + +If the cluster starts successfully, it will listen on 4000-4003. , you can access the cluster by referencing the [Quick Start](../quick-start.md). + +### Clean up + +You can use the following command to stop the cluster: + +``` +docker compose -f ./cluster-with-etcd.yaml down +``` + +By default, the data will be stored in `./greptimedb-cluster-docker-compose`. You also can remove the data directory if you want to clean up the data. + + +## Next Steps + +Learn how to write data to GreptimeDB in [Quick Start](../quick-start.md). diff --git a/versioned_docs/version-1.0/getting-started/installation/greptimedb-dashboard.md b/versioned_docs/version-1.0/getting-started/installation/greptimedb-dashboard.md new file mode 100644 index 0000000000..f1a1ab7a47 --- /dev/null +++ b/versioned_docs/version-1.0/getting-started/installation/greptimedb-dashboard.md @@ -0,0 +1,17 @@ +--- +keywords: [dashboard, data visualization, SQL queries, PromQL queries, time series data] +description: Information on accessing and using the GreptimeDB Dashboard for visualizing time series data. +--- + +# GreptimeDB Dashboard + +Visualization plays a crucial role in effectively utilizing time series data. To help users leverage the various features of GreptimeDB, Greptime offers a simple [dashboard](https://github.com/GreptimeTeam/dashboard). + +The Dashboard is embedded into GreptimeDB's binary since GreptimeDB v0.2.0. After starting [GreptimeDB Standalone](greptimedb-standalone.md) or [GreptimeDB Cluster](greptimedb-cluster.md), the dashboard can be accessed via the HTTP endpoint `http://localhost:4000/dashboard`. The dashboard supports multiple query languages, including [SQL queries](/user-guide/query-data/sql.md), and [PromQL queries](/user-guide/query-data/promql.md). + +We offer various chart types to choose from based on different scenarios. The charts become more informative when you have sufficient data. + +![line](/dashboard-line.png) +![scatter](/dashboard-scatter.png) + +We are committed to the ongoing development and iteration of this open-source project, and we plan to expand the application of time series data in monitoring, analysis, and other relevant fields in the future. diff --git a/versioned_docs/version-1.0/getting-started/installation/greptimedb-standalone.md b/versioned_docs/version-1.0/getting-started/installation/greptimedb-standalone.md new file mode 100644 index 0000000000..977e9943c5 --- /dev/null +++ b/versioned_docs/version-1.0/getting-started/installation/greptimedb-standalone.md @@ -0,0 +1,135 @@ +--- +keywords: [standalone mode, binary installation, Docker, configuration] +description: Guide to install and run GreptimeDB in standalone mode using binary or Docker, including binding address configuration. +--- + +# GreptimeDB Standalone + +We use the simplest configuration for you to get started. For a comprehensive list of configurations available in GreptimeDB, see the [configuration documentation](/user-guide/deployments-administration/configuration.md). + +## Deploy the GreptimeDB standalone in Kubernetes + +For production environments, we recommend deploying the GreptimeDB standalone in Kubernetes. Please refer to [Deploy on Kubernetes](/user-guide/deployments-administration/deploy-on-kubernetes/overview.md). + +## Binary + +### Download from website + +You can try out GreptimeDB by downloading the latest stable build releases from the [Download page](https://greptime.com/download). + +### Linux and macOS + +For Linux and macOS users, you can download the latest build of the `greptime` binary by using the following commands: + +```shell +curl -fsSL \ + https://raw.githubusercontent.com/greptimeteam/greptimedb/main/scripts/install.sh | sh -s VAR::greptimedbVersion +``` + +Once the download is completed, the binary file `greptime` will be stored in your current directory. + +You can run GreptimeDB in the standalone mode: + +```shell +./greptime standalone start +``` + +### Windows + +If you have WSL([Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/about)) enabled, you can launch a latest Ubuntu and run GreptimeDB like above! + +Otherwise please download the GreptimeDB binary for Windows at our [official site](https://greptime.com/resources), and unzip the downloaded artifact. + +To run GreptimeDB in standalone mode, open a terminal (like Powershell) at the directory where the GreptimeDB binary locates, and execute: + +```shell +.\greptime standalone start +``` + +## Docker + +Make sure the [Docker](https://www.docker.com/) is already installed. If not, you can follow the official [documents](https://www.docker.com/get-started/) to install Docker. + +```shell +docker run -p 127.0.0.1:4000-4003:4000-4003 \ + -v "$(pwd)/greptimedb_data:/greptimedb_data" \ + --name greptime --rm \ + greptime/greptimedb:VAR::greptimedbVersion standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-bind-addr 0.0.0.0:4001 \ + --mysql-addr 0.0.0.0:4002 \ + --postgres-addr 0.0.0.0:4003 +``` + +:::tip NOTE +To avoid accidentally exit the Docker container, you may want to run it in the "detached" mode: add the `-d` flag to +the `docker run` command. +::: + +The data will be stored in the `greptimedb_data/` directory in your current directory. + +If you want to use another version of GreptimeDB's image, you can download it from our [GreptimeDB Dockerhub](https://hub.docker.com/r/greptime/greptimedb). In particular, we support GreptimeDB based on CentOS, and you can try image `greptime/greptimedb-centos`. + +:::tip NOTE +If you are using a Docker version lower than [v23.0](https://docs.docker.com/engine/release-notes/23.0/), you may experience problems with insufficient permissions when trying to run the command above, due to a [bug](https://github.com/moby/moby/pull/42681) in the older version of Docker Engine. + +You can: + +1. Set `--security-opt seccomp=unconfined`, for example: + + ```shell + docker run --security-opt seccomp=unconfined -p 4000-4003:4000-4003 \ + -v "$(pwd)/greptimedb_data:/greptimedb_data" \ + --name greptime --rm \ + greptime/greptimedb:VAR::greptimedbVersion standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-bind-addr 0.0.0.0:4001 \ + --mysql-addr 0.0.0.0:4002 \ + --postgres-addr 0.0.0.0:4003 + ``` + +2. Upgrade the Docker version to v23.0.0 or higher; +::: + +## Binding address + +GreptimeDB binds to `127.0.0.1` by default. If you need to accept connections from other addresses, you can start with the following parameters. + +> :::danger Warning +> If the computer running GreptimeDB is directly exposed to the internet, binding to `0.0.0.0` is dangerous and will expose the instance to everybody on the internet. + + + + + +```shell +./greptime standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-bind-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_data:/greptimedb_data" \ + --name greptime --rm \ + greptime/greptimedb:VAR::greptimedbVersion standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-bind-addr 0.0.0.0:4001 \ + --mysql-addr 0.0.0.0:4002 \ + --postgres-addr 0.0.0.0:4003 +``` + + + + +You can also refer to the [Configuration](/user-guide/deployments-administration/configuration.md) document to modify the bind address in the configuration file. + +## Next Steps + +Learn how to write data to GreptimeDB in the [Quick Start](../quick-start.md). diff --git a/versioned_docs/version-1.0/getting-started/installation/overview.md b/versioned_docs/version-1.0/getting-started/installation/overview.md new file mode 100644 index 0000000000..f11cf50dfb --- /dev/null +++ b/versioned_docs/version-1.0/getting-started/installation/overview.md @@ -0,0 +1,30 @@ +--- +keywords: [installation, health check, quick start, GreptimeDB standalone, GreptimeDB cluster] +description: Instructions to install GreptimeDB, check its health status, and proceed to the quick start guide. +--- + + +# Installation + +Follow these instructions to install GreptimeDB: + +- [GreptimeDB Standalone](greptimedb-standalone.md) runs as a standalone system in a single process. +- [GreptimeDB Cluster](greptimedb-cluster.md) runs as a distributed, clustered time series database. + +## Check database health + +After starting GreptimeDB, you can check its status to ensure it is running. + +```shell +curl http://localhost:4000/health +``` + +If the GreptimeDB instance is running healthily, you will see the following response: + +```json +{} +``` + +## Next steps + +- [Quick Start](/getting-started/quick-start.md): Ingest and query data in GreptimeDB using MySQL or PostgreSQL clients. diff --git a/versioned_docs/version-1.0/getting-started/overview.md b/versioned_docs/version-1.0/getting-started/overview.md new file mode 100644 index 0000000000..494c99e03f --- /dev/null +++ b/versioned_docs/version-1.0/getting-started/overview.md @@ -0,0 +1,11 @@ +--- +keywords: [getting started, overview, installation, quick start] +description: Get started with GreptimeDB quickly. +--- + +# Getting Started + +Get started with GreptimeDB quickly by following these steps: + +- [Installation](./installation/overview.md): Learn how to install GreptimeDB as a standalone or cluster. +- [Quick Start](./quick-start.md): Get started with GreptimeDB using your preferred protocols or languages. diff --git a/versioned_docs/version-1.0/getting-started/quick-start.md b/versioned_docs/version-1.0/getting-started/quick-start.md new file mode 100644 index 0000000000..fdbac53cf9 --- /dev/null +++ b/versioned_docs/version-1.0/getting-started/quick-start.md @@ -0,0 +1,531 @@ +--- +keywords: [quick start, SQL, create tables, insert data, query data, GreptimeDB dashboard] +description: A guide to quickly start with GreptimeDB, including connecting to the database, creating tables, inserting data, querying data, and using the GreptimeDB dashboard. +--- + +# Quick Start + +Before proceeding, please ensure you have [installed GreptimeDB](./installation/overview.md). + +This guide will walk you through creating a metric table and a log table, highlighting the core features of GreptimeDB. + +You’ll learn (10–15 minutes) +* Start and connect to GreptimeDB locally +* Create metrics and logs tables and insert sample data +* Query and aggregate data +* Compute p95 and ERROR counts in 5-second windows and align them +* Join metrics with logs to spot anomalous hosts and time periods +* Combine SQL and PromQL to query data + +## Connect to GreptimeDB + +GreptimeDB supports [multiple protocols](/user-guide/protocols/overview.md) for interacting with the database. +In this quick start document, we use SQL for simplicity. + +If your GreptimeDB instance is running on `127.0.0.1` with the MySQL client default port `4002` or the PostgreSQL client default port `4003`, +you can connect to GreptimeDB using the following commands. + +By default, GreptimeDB does not have [authentication](/user-guide/deployments-administration/authentication/overview.md) enabled. +You can connect to the database without providing a username and password in this section. + +```shell +mysql -h 127.0.0.1 -P 4002 +``` + +Or + +```shell +psql -h 127.0.0.1 -p 4003 -d public +``` + +You can also use your browser to access the built-in DB dashboard at `http://127.0.0.1:4000/dashboard` to run the SQL queries in this document. + +## Create tables + +Suppose you have an event table named `grpc_latencies` that stores the gRPC services and processing latencies of your application. +The table schema is as follows: + +```sql +-- Metrics: gRPC call latency in milliseconds +CREATE TABLE grpc_latencies ( + ts TIMESTAMP TIME INDEX, + host STRING INVERTED INDEX, + method_name STRING, + latency DOUBLE, + PRIMARY KEY (host, method_name) +); +``` + +- `ts`: The timestamp when the metric was collected. It is the time index column. +- `host`: The hostname of the application server, enabling [inverted index](/user-guide/manage-data/data-index.md#inverted-index). +- `method_name`: The name of the RPC request method. +- `latency`: The latency of the RPC request. + +Additionally, there is a table `app_logs` for storing application logs: + +```sql +-- Logs: application logs +CREATE TABLE app_logs ( + ts TIMESTAMP TIME INDEX, + host STRING INVERTED INDEX, + api_path STRING, + log_level STRING, + log_msg STRING FULLTEXT INDEX WITH('case_sensitive' = 'false'), + PRIMARY KEY (host, log_level) +) with('append_mode'='true'); +``` + +- `ts`: The timestamp of the log entry. It is the time index column. +- `host`: The hostname of the application server, enabling inverted index. +- `api_path`: The API path. +- `log_level`: The log level of the log entry. +- `log_msg`: The log message, enabling [fulltext index](/user-guide/manage-data/data-index.md#fulltext-index). + +And it's [append only](/user-guide/deployments-administration/performance-tuning/design-table.md#when-to-use-append-only-tables) by setting `append_mode` to true, which is good for performance. Other table options, such as data retention, are supported too. + + ::::tip +We use SQL to ingest the data below, so we need to create the tables manually. However, GreptimeDB is [schemaless](/user-guide/ingest-data/overview.md#automatic-schema-generation) and can automatically generate schemas when using other ingestion methods. +:::: +## Write data + +Let's insert some mocked data to simulate collected metrics and error logs. + +Two application servers, `host1` and `host2`, +have been recording gRPC latencies. Starting from `2024-07-11 20:00:10`, +`host1` experienced a significant increase in latency. + +The following image shows the unstable latencies of `host1`. + +unstable latencies + +The following SQL statements insert the mocked data. + +Before `2024-07-11 20:00:10`, the hosts were functioning normally: + +```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); +``` + +After `2024-07-11 20:00:10`, `host1`'s latencies becomes unstable, fluctuating greatly with occasional spikes of several thousand milliseconds: + +```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); +``` + +Some error logs were collected when the `host1` latencies of RPC requests encounter latency issues: + +```sql +INSERT INTO app_logs (ts, host, api_path, log_level, log_msg) 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'); +``` + +## Query data + +### Filter by tags and time index + +You can filter data using the `WHERE` clause. +For example, to query the latency of `host1` after `2024-07-11 20:00:15`: + +```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) +``` + +You can also use functions when filtering the data. +For example, you can use `approx_percentile_cont` to calculate the 95th percentile of the latency grouped by the host: + +```sql +SELECT + approx_percentile_cont(0.95) WITHIN GROUP (ORDER BY latency) 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) +``` + +### Search logs by keyword + +Filter the log messages by keyword `timeout`: +```sql +SELECT + * +FROM + app_logs +WHERE + lower(log_msg) @@ 'timeout' + AND ts > '2024-07-11 20:00:00' +ORDER BY + ts; +``` + +```sql ++---------------------+-------+------------------+-----------+--------------------+ +| ts | host | api_path | log_level | log_msg | ++---------------------+-------+------------------+-----------+--------------------+ +| 2024-07-11 20:00:10 | host1 | /api/v1/billings | ERROR | Connection timeout | +| 2024-07-11 20:00:10 | host1 | /api/v1/resource | ERROR | Connection timeout | +| 2024-07-11 20:00:14 | host1 | /api/v1/billings | ERROR | Timeout | +| 2024-07-11 20:00:14 | host1 | /api/v1/resource | ERROR | Timeout | ++---------------------+-------+------------------+-----------+--------------------+ +``` + +The `@@` operator is used for [term searching](/user-guide/logs/fulltext-search.md). + +### Range query + +You can use [range queries](/reference/sql/range.md#range-query) to monitor latencies in real-time. +For example, to calculate the p95 latency of requests using a 5-second window: + +```sql +SELECT + ts, + host, + approx_percentile_cont(0.95) WITHIN GROUP (ORDER BY latency) + RANGE '5s' AS p95_latency +FROM + grpc_latencies +ALIGN '5s' FILL PREV +ORDER BY + host,ts; +``` + +```sql ++---------------------+-------+-------------+ +| ts | host | p95_latency | ++---------------------+-------+-------------+ +| 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 | +| 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 | ++---------------------+-------+-------------+ +8 rows in set (0.06 sec) +``` + +The range query is very powerful for querying and aggregating data based on time windows, please read the [manual](/reference/sql/range.md#range-query) to learn more. + +### Correlate Metrics and Logs + +By combining the data from the two tables, +you can easily and quickly determine the time of failure and the corresponding logs. +The following SQL query uses the `JOIN` operation to correlate the metrics and logs: + +```sql +-- Align metrics and logs into 5s buckets, then join +WITH + -- metrics: per-host p95 latency in 5s buckets + metrics AS ( + SELECT + ts, + host, + approx_percentile_cont(0.95) WITHIN GROUP (ORDER BY latency) RANGE '5s' AS p95_latency + FROM grpc_latencies + ALIGN '5s' FILL PREV + ), + -- logs: per-host ERROR counts in the same 5s buckets + logs AS ( + SELECT + ts, + host, + count(log_msg) RANGE '5s' AS num_errors + FROM app_logs + WHERE log_level = 'ERROR' + ALIGN '5s' + ) +SELECT + m.ts, + m.p95_latency, + COALESCE(l.num_errors, 0) AS num_errors, + m.host +FROM metrics m +LEFT JOIN logs l + ON m.host = l.host AND m.ts = l.ts +ORDER BY m.ts, m.host; +``` + + +```sql ++---------------------+-------------+------------+-------+ +| ts | p95_latency | num_errors | host | ++---------------------+-------------+------------+-------+ +| 2024-07-11 20:00:05 | 104.5 | 0 | host1 | +| 2024-07-11 20:00:05 | 114 | 0 | host2 | +| 2024-07-11 20:00:10 | 4200 | 10 | host1 | +| 2024-07-11 20:00:10 | 111 | 0 | host2 | +| 2024-07-11 20:00:15 | 3500 | 4 | host1 | +| 2024-07-11 20:00:15 | 115 | 0 | host2 | +| 2024-07-11 20:00:20 | 2500 | 0 | host1 | +| 2024-07-11 20:00:20 | 95 | 0 | host2 | ++---------------------+-------------+------------+-------+ +8 rows in set (0.02 sec) +``` + +We can see that during the time window when the gRPC latencies increases, the number of error logs also increases significantly, and we've identified that the problem is on `host1`. + +### Query data via PromQL + +GreptimeDB supports [Prometheus Query Language and its APIs](/user-guide/query-data/promql.md), allowing you to query metrics using PromQL. For example, you can retrieve the p95 latency over the last 1 minute per host with this query: + +```promql +quantile_over_time(0.95, grpc_latencies{host!=""}[1m]) +``` + +To test this, use the following curl command: +```bash +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + --data-urlencode 'query=quantile_over_time(0.95, grpc_latencies{host!=""}[1m])' \ + --data-urlencode 'start=2024-07-11 20:00:00Z' \ + --data-urlencode 'end=2024-07-11 20:00:20Z' \ + --data-urlencode 'step=1m' \ + 'http://localhost:4000/v1/prometheus/api/v1/query_range' +``` + +We set the `step` to 1 minute. + +Output: +```json +{ + "status": "success", + "data": { + "resultType": "matrix", + "result": [ + { + "metric": { + "__name__": "grpc_latencies", + "host": "host1", + "method_name": "GetUser" + }, + "values": [ + [ + 1720728000.0, + "103" + ] + ] + }, + { + "metric": { + "__name__": "grpc_latencies", + "host": "host2", + "method_name": "GetUser" + }, + "values": [ + [ + 1720728000.0, + "113" + ] + ] + } + ] + } +} +``` + +Even more powerful, you can use SQL to execute PromQL and mix the two, for example: +```sql +TQL EVAL ('2024-07-11 20:00:00Z', '2024-07-11 20:00:20Z','1m') + quantile_over_time(0.95, grpc_latencies{host!=""}[1m]); +``` + +This SQL query will produce: +```sql ++---------------------+---------------------------------------------------------+-------+-------------+ +| ts | prom_quantile_over_time(ts_range,latency,Float64(0.95)) | host | method_name | ++---------------------+---------------------------------------------------------+-------+-------------+ +| 2024-07-11 20:00:00 | 113 | host2 | GetUser | +| 2024-07-11 20:00:00 | 103 | host1 | GetUser | ++---------------------+---------------------------------------------------------+-------+-------------+ +``` + +Rewrite the correlation example: +```sql +WITH + metrics AS ( + TQL EVAL ('2024-07-11 20:00:00Z', '2024-07-11 20:00:20Z', '5s') + quantile_over_time(0.95, grpc_latencies{host!=""}[5s]) + ), + logs AS ( + SELECT + ts, + host, + COUNT(log_msg) RANGE '5s' AS num_errors + FROM app_logs + WHERE log_level = 'ERROR' + ALIGN '5s' + ) +SELECT + m.*, + COALESCE(l.num_errors, 0) AS num_errors +FROM metrics AS m +LEFT JOIN logs AS l + ON m.host = l.host + AND m.ts = l.ts +ORDER BY + m.ts, + m.host; +``` + +```sql ++---------------------+---------------------------------------------------------+-------+-------------+------------+ +| ts | prom_quantile_over_time(ts_range,latency,Float64(0.95)) | host | method_name | num_errors | ++---------------------+---------------------------------------------------------+-------+-------------+------------+ +| 2024-07-11 20:00:05 | 103 | host1 | GetUser | 0 | +| 2024-07-11 20:00:05 | 113 | host2 | GetUser | 0 | +| 2024-07-11 20:00:10 | 140.89999999999998 | host1 | GetUser | 10 | +| 2024-07-11 20:00:10 | 113.8 | host2 | GetUser | 0 | +| 2024-07-11 20:00:15 | 3400 | host1 | GetUser | 4 | +| 2024-07-11 20:00:15 | 114 | host2 | GetUser | 0 | +| 2024-07-11 20:00:20 | 3375 | host1 | GetUser | 0 | +| 2024-07-11 20:00:20 | 115 | host2 | GetUser | 0 | ++---------------------+---------------------------------------------------------+-------+-------------+------------+ +``` + +By using [TQL](/reference/sql/tql.md) commands, you can combine the power of SQL and PromQL, making correlation analysis and complex queries no longer difficult. + + + +## GreptimeDB Dashboard + +GreptimeDB offers a [dashboard](./installation/greptimedb-dashboard.md) for data exploration and management. + +### Explore data + +Once GreptimeDB is started as mentioned in the [installation section](./installation/overview.md), you can access the dashboard through the HTTP endpoint `http://localhost:4000/dashboard`. + +To add a new query, click on the `+` button, write your SQL command in the command text, and then click on `Run All`. +The following SQL will retrieve all the data from the `grpc_latencies` table. + +```sql +SELECT * FROM grpc_latencies; +``` + +Then click on the `Chart` button in the result panel to visualize the data. + +![select gRPC latencies](/select-grpc-latencies.png) + +### Ingest data by InfluxDB Line Protocol + +Besides SQL, GreptimeDB also supports multiple protocols, one of the most popular is InfluxDB Line Protocol. +By click `Ingest` icon in the dashboard, you can upload data in InfluxDB Line Protocol format. + +For example, paste the following data into the input box: + +```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 +``` + +Then click the `Write` button to ingest the data to the table `grpc_metrics`. +The `grpc_metrics` table will be created automatically if it does not exist. + +## Next steps + +You have now experienced the core features of GreptimeDB. +To further explore and utilize GreptimeDB: + +- [Visualize data using Grafana](/user-guide/integrations/grafana.md) +- [Explore more demos of GreptimeDB](https://github.com/GreptimeTeam/demo-scene/) +- [Learn GreptimeDB by user guide](/user-guide/overview.md) diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/create-service.md b/versioned_docs/version-1.0/greptimecloud/getting-started/create-service.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/create-service.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/create-service.md diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/go.md b/versioned_docs/version-1.0/greptimecloud/getting-started/go.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/go.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/go.md diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/influxdb.md b/versioned_docs/version-1.0/greptimecloud/getting-started/influxdb.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/influxdb.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/influxdb.md diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/java.md b/versioned_docs/version-1.0/greptimecloud/getting-started/java.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/java.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/java.md diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/mysql.md b/versioned_docs/version-1.0/greptimecloud/getting-started/mysql.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/mysql.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/mysql.md diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/node.md b/versioned_docs/version-1.0/greptimecloud/getting-started/node.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/node.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/node.md diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/overview.md b/versioned_docs/version-1.0/greptimecloud/getting-started/overview.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/overview.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/overview.md diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/prometheus.md b/versioned_docs/version-1.0/greptimecloud/getting-started/prometheus.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/prometheus.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/prometheus.md diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/python.md b/versioned_docs/version-1.0/greptimecloud/getting-started/python.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/python.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/python.md diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/vector.md b/versioned_docs/version-1.0/greptimecloud/getting-started/vector.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/vector.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/vector.md diff --git a/versioned_docs/version-0.17/greptimecloud/getting-started/visualize-data.md b/versioned_docs/version-1.0/greptimecloud/getting-started/visualize-data.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/getting-started/visualize-data.md rename to versioned_docs/version-1.0/greptimecloud/getting-started/visualize-data.md diff --git a/versioned_docs/version-0.17/greptimecloud/greptimeai/langchain.md b/versioned_docs/version-1.0/greptimecloud/greptimeai/langchain.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/greptimeai/langchain.md rename to versioned_docs/version-1.0/greptimecloud/greptimeai/langchain.md diff --git a/versioned_docs/version-0.17/greptimecloud/greptimeai/openai.md b/versioned_docs/version-1.0/greptimecloud/greptimeai/openai.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/greptimeai/openai.md rename to versioned_docs/version-1.0/greptimecloud/greptimeai/openai.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/alloy.md b/versioned_docs/version-1.0/greptimecloud/integrations/alloy.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/alloy.md rename to versioned_docs/version-1.0/greptimecloud/integrations/alloy.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/dbeaver.md b/versioned_docs/version-1.0/greptimecloud/integrations/dbeaver.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/dbeaver.md rename to versioned_docs/version-1.0/greptimecloud/integrations/dbeaver.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/emqx.md b/versioned_docs/version-1.0/greptimecloud/integrations/emqx.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/emqx.md rename to versioned_docs/version-1.0/greptimecloud/integrations/emqx.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/fluent-bit.md b/versioned_docs/version-1.0/greptimecloud/integrations/fluent-bit.md similarity index 99% rename from versioned_docs/version-0.17/greptimecloud/integrations/fluent-bit.md rename to versioned_docs/version-1.0/greptimecloud/integrations/fluent-bit.md index aefbdfd4eb..cb3f5db26b 100644 --- a/versioned_docs/version-0.17/greptimecloud/integrations/fluent-bit.md +++ b/versioned_docs/version-1.0/greptimecloud/integrations/fluent-bit.md @@ -28,7 +28,7 @@ Fluent Bit can be configured to send logs to GreptimeCloud using the HTTP protoc http_Passwd ``` -In this example, the `http` output plugin is used to send logs to GreptimeCloud. For more information, and extra options, refer to the [Logs HTTP API](https://docs.greptime.com/reference/pipeline/write-log-api#http-api) guide. +In this example, the `http` output plugin is used to send logs to GreptimeCloud. For more information, and extra options, refer to the [Logs HTTP API](https://docs.greptime.com/reference/pipeline/write-log-api/#http-api) guide. ## Prometheus Remote Write diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/grafana.md b/versioned_docs/version-1.0/greptimecloud/integrations/grafana.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/grafana.md rename to versioned_docs/version-1.0/greptimecloud/integrations/grafana.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/influxdb.md b/versioned_docs/version-1.0/greptimecloud/integrations/influxdb.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/influxdb.md rename to versioned_docs/version-1.0/greptimecloud/integrations/influxdb.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/kafka.md b/versioned_docs/version-1.0/greptimecloud/integrations/kafka.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/kafka.md rename to versioned_docs/version-1.0/greptimecloud/integrations/kafka.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/metabase.md b/versioned_docs/version-1.0/greptimecloud/integrations/metabase.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/metabase.md rename to versioned_docs/version-1.0/greptimecloud/integrations/metabase.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/mindsdb.md b/versioned_docs/version-1.0/greptimecloud/integrations/mindsdb.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/mindsdb.md rename to versioned_docs/version-1.0/greptimecloud/integrations/mindsdb.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/mysql.md b/versioned_docs/version-1.0/greptimecloud/integrations/mysql.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/mysql.md rename to versioned_docs/version-1.0/greptimecloud/integrations/mysql.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/otlp.md b/versioned_docs/version-1.0/greptimecloud/integrations/otlp.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/otlp.md rename to versioned_docs/version-1.0/greptimecloud/integrations/otlp.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/postgresql.md b/versioned_docs/version-1.0/greptimecloud/integrations/postgresql.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/postgresql.md rename to versioned_docs/version-1.0/greptimecloud/integrations/postgresql.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/prometheus.md b/versioned_docs/version-1.0/greptimecloud/integrations/prometheus.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/prometheus.md rename to versioned_docs/version-1.0/greptimecloud/integrations/prometheus.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/sdk-libraries/go.md b/versioned_docs/version-1.0/greptimecloud/integrations/sdk-libraries/go.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/sdk-libraries/go.md rename to versioned_docs/version-1.0/greptimecloud/integrations/sdk-libraries/go.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/sdk-libraries/java.md b/versioned_docs/version-1.0/greptimecloud/integrations/sdk-libraries/java.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/sdk-libraries/java.md rename to versioned_docs/version-1.0/greptimecloud/integrations/sdk-libraries/java.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/streamlit.md b/versioned_docs/version-1.0/greptimecloud/integrations/streamlit.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/streamlit.md rename to versioned_docs/version-1.0/greptimecloud/integrations/streamlit.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/superset.md b/versioned_docs/version-1.0/greptimecloud/integrations/superset.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/superset.md rename to versioned_docs/version-1.0/greptimecloud/integrations/superset.md diff --git a/versioned_docs/version-0.17/greptimecloud/integrations/vector.md b/versioned_docs/version-1.0/greptimecloud/integrations/vector.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/integrations/vector.md rename to versioned_docs/version-1.0/greptimecloud/integrations/vector.md diff --git a/versioned_docs/version-0.17/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md b/versioned_docs/version-1.0/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md rename to versioned_docs/version-1.0/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md diff --git a/versioned_docs/version-0.17/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md b/versioned_docs/version-1.0/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md rename to versioned_docs/version-1.0/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md diff --git a/versioned_docs/version-0.17/greptimecloud/overview.md b/versioned_docs/version-1.0/greptimecloud/overview.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/overview.md rename to versioned_docs/version-1.0/greptimecloud/overview.md diff --git a/versioned_docs/version-0.17/greptimecloud/usage-&-billing/billing.md b/versioned_docs/version-1.0/greptimecloud/usage-&-billing/billing.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/usage-&-billing/billing.md rename to versioned_docs/version-1.0/greptimecloud/usage-&-billing/billing.md diff --git a/versioned_docs/version-0.17/greptimecloud/usage-&-billing/dedicated.md b/versioned_docs/version-1.0/greptimecloud/usage-&-billing/dedicated.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/usage-&-billing/dedicated.md rename to versioned_docs/version-1.0/greptimecloud/usage-&-billing/dedicated.md diff --git a/versioned_docs/version-0.17/greptimecloud/usage-&-billing/hobby.md b/versioned_docs/version-1.0/greptimecloud/usage-&-billing/hobby.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/usage-&-billing/hobby.md rename to versioned_docs/version-1.0/greptimecloud/usage-&-billing/hobby.md diff --git a/versioned_docs/version-0.17/greptimecloud/usage-&-billing/overview.md b/versioned_docs/version-1.0/greptimecloud/usage-&-billing/overview.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/usage-&-billing/overview.md rename to versioned_docs/version-1.0/greptimecloud/usage-&-billing/overview.md diff --git a/versioned_docs/version-0.17/greptimecloud/usage-&-billing/request-capacity-unit.md b/versioned_docs/version-1.0/greptimecloud/usage-&-billing/request-capacity-unit.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/usage-&-billing/request-capacity-unit.md rename to versioned_docs/version-1.0/greptimecloud/usage-&-billing/request-capacity-unit.md diff --git a/versioned_docs/version-0.17/greptimecloud/usage-&-billing/serverless.md b/versioned_docs/version-1.0/greptimecloud/usage-&-billing/serverless.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/usage-&-billing/serverless.md rename to versioned_docs/version-1.0/greptimecloud/usage-&-billing/serverless.md diff --git a/versioned_docs/version-0.17/greptimecloud/usage-&-billing/shared-storage-capacity.md b/versioned_docs/version-1.0/greptimecloud/usage-&-billing/shared-storage-capacity.md similarity index 100% rename from versioned_docs/version-0.17/greptimecloud/usage-&-billing/shared-storage-capacity.md rename to versioned_docs/version-1.0/greptimecloud/usage-&-billing/shared-storage-capacity.md diff --git a/versioned_docs/version-1.0/index.md b/versioned_docs/version-1.0/index.md new file mode 100644 index 0000000000..f907ebb3e3 --- /dev/null +++ b/versioned_docs/version-1.0/index.md @@ -0,0 +1,42 @@ +--- +keywords: [observability database, open source observability database, observability data, observability tools, cloud native database, data observability, observability platform, edge database, IoT edge computing, edge cloud computing, log management, log aggregation, high cardinality, sql query examples, opentelemetry collector, GreptimeDB] +description: Introduction to GreptimeDB, an open-source unified observability database for metrics, logs, and events, with links to getting started, user guide, contributor guide, and more. +--- +# Introduction + +

+ GreptimeDB Logo +

+ +**GreptimeDB** is an open-source, cloud-native, unified observability database for metrics, logs and traces. You can gain real-time insights from edge to cloud—at any scale. + +GreptimeDB is also on cloud as [GreptimeCloud](https://greptime.com/product/cloud), +a fully-managed observability database service that features serverless scalability, +seamless integration with rich ecosystems. + +Our core developers have been building observability data platforms for years. Based on their best-practices, GreptimeDB is born to give you: + +- **All-in-One Observability Database**: Process metrics, logs, and traces in real-time through a unified database with native [SQL](/user-guide/query-data/sql.md), [PromQL](/user-guide/query-data/promql.md), and [streaming processing](/user-guide/flow-computation/overview.md) support. It replaces complex legacy data stacks with a high-performance single solution. +- **High-Performance Engine**: Built with Rust for high performance and reliability. Rich [indexing options](/user-guide/manage-data/data-index.md) (inverted, full-text, skip list, and vector indexing) accelerate queries, enabling sub-second responses on petabyte-scale datasets and handling hundreds of thousands of concurrent requests. +- **Significant Cost Reduction**: Achieve 50x lower operational and storage costs through a compute-storage separation [architecture](/user-guide/concepts/architecture.md). Scale flexibly across cloud storage systems (e.g., S3, Azure Blob Storage) with a fully-managed cloud service [GreptimeCloud](https://greptime.com/product/cloud), for simplified management. +- **Infinity Scalability**: Purpose-built for [Kubernetes](/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md) and cloud environments with industry-leading compute-storage separation. Enables unlimited scaling across cloud environments while efficiently managing cardinality explosion at a massive scale. +- **Developer-Friendly**: Features standardized SQL and PromQL interfaces, a built-in web dashboard, REST API, and support for MySQL/PostgreSQL protocols. Widely compatible with popular data [ingestion protocols](/user-guide/protocols/overview.md) for seamless migration and integration. +- **Flexible Deployment Options**: Deploy anywhere, from ARM-based edge devices to cloud environments, with unified APIs and bandwidth-efficient data synchronization. Query edge and cloud data seamlessly using identical APIs. + +Before getting started, please read the following documents that include instructions for setting up, fundamental concepts, architectural designs, and tutorials: + +- [Getting Started][1]: Provides an introduction to GreptimeDB for those who are new to it, including installation and database operations. +- [User Guide][2]: For application developers to use GreptimeDB or build custom integration. +- [GreptimeCloud][6]: For users of GreptimeCloud to get started. +- [Contributor Guide][3]: For contributors interested in learning more about the technical details and enhancing GreptimeDB. +- [Roadmap][7]: The latest GreptimeDB roadmap. +- [Release Notes][4]: Presents all historical version release notes. +- [FAQ][5]: Provides answers to the most frequently asked questions. + +[1]: ./getting-started/overview.md +[2]: ./user-guide/overview.md +[3]: ./contributor-guide/overview.md +[4]: /release-notes +[5]: ./faq-and-others/faq.md +[6]: ./greptimecloud/overview.md +[7]: https://greptime.com/blogs/2025-02-06-greptimedb-roadmap2025 diff --git a/versioned_docs/version-1.0/reference/about-greptimedb-engines.md b/versioned_docs/version-1.0/reference/about-greptimedb-engines.md new file mode 100644 index 0000000000..b007e7ef30 --- /dev/null +++ b/versioned_docs/version-1.0/reference/about-greptimedb-engines.md @@ -0,0 +1,50 @@ +--- +keywords: [greptimedb engine, Mito engine, Metric engine, File engine, Table engine] +description: Overview of all the table engines in GreptimeDB. +--- + +# GreptimeDB Table Engines + +## Overview + +GreptimeDB offers multiple specialized table engines, each designed to excel at specific workloads and use cases. This document provides a comprehensive introduction to these engines and guidance on when to use each one. + +### Mito Engine + +Mito is the default `storage engine` of GreptimeDB, responsible for efficiently storing and managing database data. Built on the [LSMT][1] (Log-structured Merge-tree) architecture, Mito has been extensively optimized for time-series data workloads. + +The engine features a robust architecture including Write-Ahead Logging (WAL) for durability, a memory table system, and an efficient compaction strategy based on Time Window Compaction Strategy (TWCS). This design enables Mito to handle high-throughput write operations while maintaining excellent query performance. + +Mito seamlessly integrates with various object storage solutions including S3, GCS, and Azure Blob Storage, providing native support without additional plugins. It implements a tiered cache system on top of object storage, optimizing both storage costs and access speeds for time-series data at any scale. + +[1]: https://en.wikipedia.org/wiki/Log-structured_merge-tree + +### Metric Engine + +As the name suggests, the Metric Engine is designed to process metrics data efficiently. It specializes in handling scenarios with a large number of small tables typical in observability and monitoring workloads. + +The key innovation of the Metric Engine is its use of synthetic wide physical tables to store data from numerous small tables. This approach enables efficient column and metadata reuse across tables, significantly reducing storage overhead while enhancing columnar compression efficiency. Under the Metric Engine, tables become lightweight logical constructs, making it ideal for cloud-native monitoring scenarios where thousands of small metric tables are common. + +The Metric Engine is built on top of the Mito Engine, meaning that its data is actually stored in the Mito Engine. This architecture leverages Mito's robust storage capabilities while adding specialized optimizations for metrics data management. + +### File Engine + +The File Engine is a specialized storage engine in GreptimeDB designed for handling file-based data sources. It allows GreptimeDB to directly query and process data stored in external files without requiring data import or conversion. + +This engine supports various file formats commonly used in data analytics workflows, enabling seamless integration with existing data pipelines. By treating external files as virtual tables, the File Engine provides SQL query capabilities over file-based data while maintaining the performance optimizations of GreptimeDB's query engine. + +The File Engine is particularly useful for scenarios where data already exists in file formats, allowing users to analyze this data alongside time-series data stored in other GreptimeDB engines. This capability makes GreptimeDB more versatile as a unified analytics platform that can work with diverse data sources. + +## Engine Selection Guide + +### When to Use Each Engine + +- **Mito Engine**: As the default storage engine, Mito is suitable for most general time-series workloads. It's an excellent choice when you need a balance of write throughput, query performance, and storage efficiency. Use Mito for applications requiring durable storage with good all-around performance characteristics. + +- **Metric Engine**: Choose the Metric Engine when dealing with observability and monitoring scenarios that involve thousands of small tables with similar schemas. This engine excels at reducing storage overhead and improving query performance in cloud-native monitoring environments where metrics data is predominant. + +- **File Engine**: Opt for the File Engine when you need to query data that already exists in external files without importing it into the database. This is ideal for data exploration, one-time analysis tasks, or when integrating with existing file-based data pipelines. + +### Specifying Engine Type in SQL + +When creating a table in GreptimeDB, you can specify which engine to use through the `ENGINE` clause in your CREATE TABLE statement. For more detailed information on syntax and options, please refer to the [CREATE TABLE](/reference/sql/create.md#create-table) documentation. \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/about-greptimedb-version.md b/versioned_docs/version-1.0/reference/about-greptimedb-version.md new file mode 100644 index 0000000000..ab087a55fb --- /dev/null +++ b/versioned_docs/version-1.0/reference/about-greptimedb-version.md @@ -0,0 +1,31 @@ +--- +keywords: [version numbering, Semantic Versioning, major release, minor release, revision number] +description: Explanation of GreptimeDB's version numbering scheme, including the significance of major, minor, and revision numbers. +--- + +# About GreptimeDB Version Number + +GreptimeDB follows the [Semantic Versioning](https://semver.org/) scheme: + +1.2.3 where: +- 1 is the major release +- 2 is the minor release +- 3 is the revision number + +## Major release(1) +The major version indicates a significant milestone in the software’s lifecycle, often introducing extensive changes. +- Characteristics: Includes major architectural updates, substantial new features, or system overhauls. +- Impact: Typically not backward-compatible, requiring adjustments from users or developers. +- Examples: Major API redesigns, foundational architectural shifts, or the introduction of new core modules. + +## Minor release(2) +The minor version focuses on feature enhancements and minor improvements, aiming to refine the existing system. +- Characteristics: Adds new features, small updates, or interface improvements. +- Impact: While it strives for backward compatibility within the same major version, minor breaking changes might occasionally occur. +- Examples: Introducing optional functionality, updating user interfaces, or expanding configuration options with slight adjustments to existing behaviors. + +## Revision number(3) +The revision number is used for patches or minor refinements that address specific issues. +- Characteristics: Focuses on bug fixes, security updates, or performance optimizations. +- Impact: Does not introduce new features or change the overall behavior of the system. +- Examples: Fixing known bugs, addressing security vulnerabilities, or improving system stability. \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/command-lines/datanode.md b/versioned_docs/version-1.0/reference/command-lines/datanode.md new file mode 100644 index 0000000000..6907923f40 --- /dev/null +++ b/versioned_docs/version-1.0/reference/command-lines/datanode.md @@ -0,0 +1,86 @@ +--- +keywords: [GreptimeDB datanode, command-line interface, datanode configuration, datanode startup, datanode options, datanode examples] +description: Comprehensive guide to GreptimeDB datanode command-line interface, including configuration options, startup commands, and practical examples for deploying datanode instances. +--- + +# Datanode + +The `greptime datanode` command provides subcommands for managing and benchmarking datanode instances. + +## start + +Start the datanode service. + +### Options + +You can list all the options from the following command: + +``` +greptime datanode start --help +``` + +| Option | Description | +| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-c`/`--config-file` | The configuration file for datanode | +| `--data-home` | Database storage root directory | +| `--env-prefix ` | The prefix of environment variables, default is `GREPTIMEDB_DATANODE` | +| `--http-addr ` | HTTP server address | +| `--http-timeout ` | HTTP request timeout in seconds | +| `--metasrv-addrs ` | Metasrv address list | +| `--node-id ` | The datanode ID | +| `--rpc-bind-addr ` | The address to bind the gRPC server | +| `--rpc-server-addr ` | The address advertised to the metasrv, and used for connections from outside the host. If left empty or unset, the server will automatically use the IP address of the first network interface on the host, with the same port number as the one specified in `rpc_bind_addr` | +| `--wal-dir ` | The directory of WAL | + +All the `addr` options are in the form of `ip:port`. + +### Examples + +#### Start service with configurations + +Starts a datanode instance with customized configurations: + +```sh +greptime datanode start -c config/datanode.example.toml +``` + +Starts a datanode instance with command line arguments specifying the gRPC service address, the MySQL service address, the address of the metasrv, and the node id of the instance: + +```sh +greptime datanode start --rpc-bind-addr=0.0.0.0:4001 --mysql-addr=0.0.0.0:4002 --metasrv-addrs=0.0.0.0:3002 --node-id=1 +``` + +The `datanode.example.toml` configuration file comes from the `config` directory of the `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` repository. You can find more example configuration files there. The `-c` option specifies the configuration file, for more information check [Configuration](/user-guide/deployments-administration/configuration.md). + +## objbench + +The `objbench` subcommand is a benchmarking tool for measuring read/write performance of specific files on object storage. This is useful for diagnosing performance issues and testing storage layer performance. + +### Options + +| Option | Description | +| ------------------------------ | ------------------------------------------------------------------------------------------------ | +| `--config ` | Path to the datanode configuration file (TOML format) | +| `--source ` | Source SST file path in object storage (e.g., `data/greptime/public/1024/1024_0000000000/metadata/.parquet`) | +| `-v`/`--verbose` | Enable verbose output | +| `--pprof-file ` | Output file path for pprof flamegraph (enables profiling). Generates an SVG flamegraph file | + +### Examples + +#### Basic benchmark + +Measure the read/write performance of a specific file: + +```sh +greptime datanode objbench --config ./datanode.toml --source data/greptime/public/1024/1024_0000000000/metadata/8fb41bc7-a106-4b9e-879b-392da799f958.parquet +``` + +#### Benchmark with profiling + +Measure performance and generate a flamegraph for performance analysis: + +```sh +greptime datanode objbench --config ./datanode.toml --source data/greptime/public/1024/1024_0000000000/metadata/8fb41bc7-a106-4b9e-879b-392da799f958.parquet --pprof-file=./flamegraph.svg +``` + +This will generate a flamegraph in SVG format that can be opened in a web browser for performance analysis. \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/command-lines/flownode.md b/versioned_docs/version-1.0/reference/command-lines/flownode.md new file mode 100644 index 0000000000..b1214ea709 --- /dev/null +++ b/versioned_docs/version-1.0/reference/command-lines/flownode.md @@ -0,0 +1,40 @@ +--- +keywords: [GreptimeDB flownode, command-line interface, flownode configuration, flownode startup, flownode options, flownode examples] +description: Comprehensive guide to GreptimeDB flownode command-line interface, including configuration options, startup commands, and practical examples for deploying flownode instances. +--- + +# Flownode + +## Subcommand options + +You can list all the options from the following command: + +``` +greptime flownode start --help +``` +| Option | Description | +| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-c`/`--config-file` | The configuration file for flownode | +| `--env-prefix ` | The prefix of environment variables, default is `GREPTIMEDB_FLOWNODE` | +| `--metasrv-addrs ...` | Metasrv address list | +| `--node-id ` | Flownode's id | +| `--rpc-bind-addr ` | The address to bind the gRPC server | +| `--rpc-server-addr ` | The address advertised to the metasrv, and used for connections from outside the host. If left empty or unset, the server will automatically use the IP address of the first network interface on the host, with the same port number as the one specified in `rpc_bind_addr` | + +## Examples + +### Start service with configurations + +Starts a flownode instance with customized configurations: + +```sh +greptime flownode start -c config/flownode.example.toml +``` + +Starts a flownode instance with command line arguments specifying the address of the metasrv: + +```sh +greptime flownode start --node-id=0 --rpc-bind-addr=127.0.0.1:6800 --metasrv-addrs=127.0.0.1:3002 +``` + +The `flownode.example.toml` configuration file comes from the `config` directory of the `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` repository. You can find more example configuration files there. The `-c` option specifies the configuration file, for more information check [Configuration](/user-guide/deployments-administration/configuration.md). \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/command-lines/frontend.md b/versioned_docs/version-1.0/reference/command-lines/frontend.md new file mode 100644 index 0000000000..e27067487c --- /dev/null +++ b/versioned_docs/version-1.0/reference/command-lines/frontend.md @@ -0,0 +1,50 @@ +--- +keywords: [GreptimeDB frontend, command-line interface, frontend configuration, frontend startup, frontend options, frontend examples] +description: Comprehensive guide to GreptimeDB frontend command-line interface, including configuration options, startup commands, and practical examples for deploying frontend instances. +--- + +# Frontend + +## Subcommand options + + +You can list all the options from the following command: + +``` +greptime frontend start --help +``` + +| Option | Description | +| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-c`/`--config-file` | The configuration file for frontend | +| `--disable-dashboard` | Disable dashboard http service, default is `false` | +| `--env-prefix ` | The prefix of environment variables, default is `GREPTIMEDB_FRONTEND` | +| `--rpc-bind-addr ` | The address to bind the gRPC server | +| `--rpc-server-addr ` | The address advertised to the metasrv, and used for connections from outside the host. If left empty or unset, the server will automatically use the IP address of the first network interface on the host, with the same port number as the one specified in `rpc_bind_addr` | +| `--http-timeout ` | HTTP request timeout in seconds | +| `--influxdb-enable` | Whether to enable InfluxDB protocol in HTTP API | +| `--metasrv-addrs ` | Metasrv address list | +| `--mysql-addr ` | MySQL server address | +| `--postgres-addr ` | Postgres server address | +| `--tls-cert-path ` | The TLS public key file path | +| `--tls-key-path ` | The TLS private key file path | +| `--tls-mode ` | TLS Mode | +| `--user-provider ` | You can refer [authentication](/user-guide/deployments-administration/authentication/overview.md) | + +## Examples + +### Start service with configurations + +Starts a frontend instance with customized configurations: + +```sh +greptime frontend start -c config/frontend.example.toml +``` + +Starts a frontend instance with command line arguments specifying the address of the metasrv: + +```sh +greptime frontend start --metasrv-addrs=0.0.0.0:3002 +``` + +The `frontend.example.toml` configuration file comes from the `config` directory of the `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` repository. You can find more example configuration files there. The `-c` option specifies the configuration file, for more information check [Configuration](/user-guide/deployments-administration/configuration.md). \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/command-lines/metasrv.md b/versioned_docs/version-1.0/reference/command-lines/metasrv.md new file mode 100644 index 0000000000..bde57aa8ef --- /dev/null +++ b/versioned_docs/version-1.0/reference/command-lines/metasrv.md @@ -0,0 +1,39 @@ +--- +keywords: [GreptimeDB metasrv, command-line interface, metasrv configuration, metasrv startup, metasrv options, metasrv examples] +description: Comprehensive guide to GreptimeDB metasrv command-line interface, including configuration options, startup commands, and practical examples for deploying instances. +--- + +# Metasrv + +## Subcommand options + +You can list all the options from the following command: + +``` +greptime metasrv start --help +``` + +| Option | Description | +| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-c`/`--config-file` | The configuration file for metasrv | +| `--enable-region-failover` | Whether to enable region failover, default is `false`. Please refer to [Region Failover](/user-guide/deployments-administration/manage-data/region-failover.md) for the conditions to enable it. | +| `--env-prefix ` | The prefix of environment variables, default is `GREPTIMEDB_METASRV` | +| `--rpc-bind-addr ` | The address to bind the gRPC server | +| `--rpc-server-addr ` | The communication server address for the other components(frontend, datanode, flownode, etc.) If left empty or unset, the server will automatically use the IP address of the first network interface on the host, with the same port number as the one specified in `rpc_bind_addr` | +| `--http-addr ` | HTTP server address | +| `--http-timeout ` | HTTP request timeout in seconds | +| `--selector ` | You can refer [selector-type](/contributor-guide/metasrv/selector.md#selector-type) | +| `--store-addrs ` | Comma or space separated key-value storage server (default is etcd) address, used for storing metadata | +| `--use-memory-store` | Use memory store instead of etcd, for test purpose only | + +## Examples + +### Start service with configurations + +Starts a metasrv with customized configurations: + +```sh +greptime metasrv start -c config/metasrv.example.toml +``` + +The `metasrv.example.toml` configuration file comes from the `config` directory of the `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` repository. You can find more example configuration files there. The `-c` option specifies the configuration file, for more information check [Configuration](/user-guide/deployments-administration/configuration.md). \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/command-lines/overview.md b/versioned_docs/version-1.0/reference/command-lines/overview.md new file mode 100644 index 0000000000..76e8b750ce --- /dev/null +++ b/versioned_docs/version-1.0/reference/command-lines/overview.md @@ -0,0 +1,70 @@ +--- +keywords: [GreptimeDB CLI, command-line interface, installation, starting services, upgrading versions, command line tools, CLI reference] +description: Comprehensive overview of the GreptimeDB command-line interface, including installation instructions, available commands, global options, and practical examples for starting services and managing GreptimeDB instances. +--- + +# Overview + +The `greptime` command can start/stop GreptimeDB and pass configuration options. + +## Install the Greptime CLI + +The Greptime CLI is bundled with the GreptimeDB binary. + +If you start GreptimeDB using the binary file as described in the [installing GreptimeDB](/getting-started/installation/overview.md) documentation, +you can execute the `./greptime` command from within the GreptimeDB directory. +For convenience, if you prefer to run commands using `greptime` instead of `./greptime`, +consider moving the CLI binary to your system's `bin` directory or adding the binary's path to your `PATH` environment variable. + +If you deployed GreptimeDB in Kubernetes, you can access the greptime command line through the frontend pod. Use the following command to enter the pod: + +```sh +kubectl exec -it -n -- /bin/bash +``` + +Once inside the pod, you can run `greptime help` to see all available commands. + + +## CLI Options + +The `help` command lists all available commands and options of `greptime`. + +```sh +$ greptime help +Usage: greptime [OPTIONS] + +Commands: + datanode Start datanode service + flownode Start flownode 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 +``` + +### Global options + +| Option | Description | +| ------------------------- | ---------------------------------------------------------- | +| `-h`/`--help` | Print help information | +| `-V`/`--version` | Print version information | +| `--log-dir ` | The logging directory, default is `./greptimedb_data/logs` | +| `--log-level ` | The logging level, default is `info` | + +### Subcommands +- [Metasrv](/reference/command-lines/metasrv.md) +- [Datanode](/reference/command-lines/datanode.md) +- [Flownode](/reference/command-lines/flownode.md) +- [Frontend](/reference/command-lines/frontend.md) +- [Standalone](/reference/command-lines/standalone.md) + +### Upgrade GreptimeDB version + +Please refer to [the upgrade steps](/user-guide/deployments-administration/upgrade.md) diff --git a/versioned_docs/version-1.0/reference/command-lines/standalone.md b/versioned_docs/version-1.0/reference/command-lines/standalone.md new file mode 100644 index 0000000000..0c459eb194 --- /dev/null +++ b/versioned_docs/version-1.0/reference/command-lines/standalone.md @@ -0,0 +1,36 @@ +--- +keywords: [GreptimeDB standalone, command-line interface, standalone configuration, standalone startup, standalone options, standalone examples] +description: Comprehensive guide to GreptimeDB standalone command-line interface, including configuration options, startup commands, and practical examples for deploying standalone instances. +--- + +# Standalone + +## Subcommand options + +You can list all the options from the following command: + + +``` +greptime standalone start --help +``` +| Option | Description | +| --------------------------------- | ----------------------------------------------------------------------- | +| `-c`/`--config-file` | The configuration file for frontend | +| `--env-prefix ` | The prefix of environment variables, default is `GREPTIMEDB_STANDALONE` | +| `--http-addr ` | HTTP server address | +| `--influxdb-enable` | Whether to enable InfluxDB protocol in HTTP API | +| `--mysql-addr ` | MySQL server address | +| `--postgres-addr ` | Postgres server address | +| `--rpc-bind-addr ` | The address to bind the gRPC server | + +## Examples + +### Start standalone with configurations + +Starts GreptimeDB in standalone mode with customized configurations: + +```sh +greptime --log-dir=greptimedb_data/logs --log-level=info standalone start -c config/standalone.example.toml +``` + +The `standalone.example.toml` configuration file comes from the `config` directory of the `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` repository. You can find more example configuration files there. The `-c` option specifies the configuration file, for more information check [Configuration](/user-guide/deployments-administration/configuration.md). \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/command-lines/utilities/data.md b/versioned_docs/version-1.0/reference/command-lines/utilities/data.md new file mode 100644 index 0000000000..2a89f67d93 --- /dev/null +++ b/versioned_docs/version-1.0/reference/command-lines/utilities/data.md @@ -0,0 +1,72 @@ +--- +keywords: [GreptimeDB CLI, backup, restore, export tool, import tool, database backup, database restoration, command line tool, data export, data import] +description: Introduction to GreptimeDB's data export and import tools for backing up and restoring database data, including command syntax, options. +--- + +# Data Export & Import + +The Export and Import tools provide functionality for backing up and restoring GreptimeDB databases. These tools can handle both schema and data, allowing for complete or selective backup and restoration operations. + +## Export Tool + +### Command Syntax +```bash +greptime cli data export [OPTIONS] +``` + +### Options +| Option | Required | Default | Description | +| ------------------------- | -------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--addr` | Yes | - | Server address to connect | +| `--output-dir` | Yes | - | Directory to store exported data | +| `--database` | No | all databasses | Name of the database to export | +| `--export-jobs`, `-j` | No | 1 | Number of parallel export jobs(multiple databases can be exported in parallel) | +| `--max-retry` | No | 3 | Maximum retry attempts per job | +| `--target`, `-t` | No | all | Export target (schema/data/all) | +| `--start-time` | No | - | Start of time range for data export | +| `--end-time` | No | - | End of time range for data export | +| `--auth-basic` | No | - | Use the `:` format | +| `--timeout` | No | 0 | The timeout for a single call to the DB, default is 0 which means never timeout (e.g., `30s`, `10min 20s`) | +| `--proxy ` | No | - | The proxy server address to connect, if set, will override the system proxy. The default behavior will use the system proxy if neither `proxy` nor `no_proxy` is set. | +| `--no-proxy` | No | - | Disable proxy server, if set, will not use any proxy | +| `--s3` | No | - | If export data to s3 | +| `--ddl-local-dir` | No | - | If both `ddl_local_dir` and remote storage (s3/oss) are set, `ddl_local_dir` will be only used for exported SQL files, and the data will be exported to remote storage. Note that `ddl_local_dir` export sql files to **LOCAL** file system, this is useful if export client don't have direct access to remote storage. If remote storage is set but `ddl_local_dir` is not set, both SQL&data will be exported to remote storage. | +| `--s3-bucket` | Yes* | - | The s3 bucket name if s3 is set, this is required | +| `--s3-root` | Yes* | - | If s3 is set, this is required | +| `--s3-endpoint` | No* | - | The s3 endpoint if s3 is set, this is required | +| `--s3-access-key` | Yes* | - | The s3 access key if s3 is set, this is required | +| `--s3-secret-key` | Yes* | - | The s3 secret key if s3 is set, this is required | +| `--s3-region` | Yes* | - | The s3 region if s3 is set, this is required | +| `--oss` | No | - | If export data to oss | +| `--oss-bucket` | Yes* | - | The oss bucket name if oss is set, this is required | +| `--oss-endpoint` | No* | - | The oss endpoint if oss is set, this is required | +| `--oss-access-key-id` | Yes* | - | The oss access key id if oss is set, this is required | +| `--oss-access-key-secret` | Yes* | - | The oss access key secret if oss is set, this is required | + +### Export Targets +- `schema`: Exports table schemas only (`SHOW CREATE TABLE`) +- `data`: Exports table data only (`COPY DATABASE TO`) +- `all`: Exports both schemas and data (default) + +## Import Tool + +### Command Syntax +```bash +greptime cli data import [OPTIONS] +``` + +### Options +| Option | Required | Default | Description | +| ------------------- | -------- | ------------- | ------------------------------------------------------------------------------- | +| `--addr` | Yes | - | Server address to connect | +| `--input-dir` | Yes | - | Directory containing backup data | +| `--database` | No | all databases | Name of the database to import | +| `--import-jobs, -j` | No | 1 | Number of parallel import jobs (multiple databases can be imported in parallel) | +| `--max-retry` | No | 3 | Maximum retry attempts per job | +| `--target, -t` | No | all | Import target (schema/data/all) | +| `--auth-basic` | No | - | Use the `:` format | + +### Import Targets +- `schema`: Imports table schemas only +- `data`: Imports table data only +- `all`: Imports both schemas and data (default) diff --git a/versioned_docs/version-1.0/reference/command-lines/utilities/metadata-interaction.md b/versioned_docs/version-1.0/reference/command-lines/utilities/metadata-interaction.md new file mode 100644 index 0000000000..1673dec84d --- /dev/null +++ b/versioned_docs/version-1.0/reference/command-lines/utilities/metadata-interaction.md @@ -0,0 +1,255 @@ +--- +keywords: [GreptimeDB CLI, metadata interaction, key-value operations, table metadata, store backends] +description: Guide for interacting with GreptimeDB metadata using the CLI, including key-value, table metadata retrieval, and deletion. +--- + +# Metadata Interaction + +The `greptime cli meta` command can be used to interact with the metadata of GreptimeDB cluster. + + +## Common options + +| Option | Description | Default | Values | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------------------- | +| `--store-addrs ...` | The endpoint of store. One of etcd, postgres or mysql.
For postgres store, the format is: `"password=password dbname=postgres user=postgres host=localhost port=5432"`.
For etcd store, the format is: `"127.0.0.1:2379"`.
For mysql store, the format is: `"mysql://user:password@ip:port/dbname"` | - | - | +| `--max-txn-ops ` | The maximum number of operations in a transaction. Only used when using [etcd-store] | 128 | - | +| `--backend ` | The metadata store backend | etcd-store | etcd-store, memory-store, postgres-store, mysql-store | +| `--store-key-prefix ` | The key prefix of the metadata store | - | - | +| `--meta-table-name ` | The table name in RDS to store metadata. Only used when using [postgres-store] or [mysql-store] | greptime_metakv | - | + + + +## Get key-value pair + +### Command syntax + +```bash +greptime cli meta get key [OPTIONS] [KEY] +``` + +### Options + +| Option | Description | Default | +| ----------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--prefix` | Whether to perform a prefix query. If true, returns all key-value pairs where the key starts with the given prefix | false | +| `--limit ` | The maximum number of key-value pairs to return. If 0, returns all key-value pairs | 0 | + +## Get table metadata + +### Command syntax +```bash +greptime cli meta get table [OPTIONS] +``` + +### Options + +| Option | Description | Default | +| ------------------------------- | -------------------------------- | -------- | +| `--table-id ` | Get table metadata by table id | - | +| `--table-name ` | Get table metadata by table name | - | +| `--schema-name ` | The schema name of the table | public | +| `--catalog-name ` | The catalog name of the table | greptime | +| `--pretty` | Pretty print the output | - | + + +## Delete key-value pair + +### Command syntax + +```bash +greptime cli meta del key [OPTIONS] [KEY] +``` + +### Options + + +| Option | Description | Default | +| ---------- | --------------------------------------------- | ------- | +| `--prefix` | Delete key-value pairs with the given prefix. | false | + + +## Delete table metadata + +### Command syntax + +```bash +greptime cli meta del table [OPTIONS] +``` + +#### Options + +| Option | Description | Default | +| ------------------------------- | -------------------------------- | -------- | +| `--table-id ` | Get table metadata by table id | - | +| `--table-name ` | Get table metadata by table name | - | +| `--schema-name ` | The schema name of the table | public | +| `--catalog-name ` | The catalog name of the table | greptime | + + +## Examples + +### Get single key-value pair + +```bash +greptime cli meta get key --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + __table_name/greptime/public/metric_table_2 +``` + +Output: + +```json +__table_name/greptime/public/metric_table_2 +{"table_id":1059} +``` + +### Get all key-value pairs with the prefix + +Output: +```bash +greptime cli meta get key --prefix \ + --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + __table_name/greptime/public +``` + +```json +__table_name/greptime/public/greptime_physical_table +{"table_id":1057} +__table_name/greptime/public/metric_table_1 +{"table_id":1058} +__table_name/greptime/public/metric_table_2 +{"table_id":1059} +``` + +### Get table metadata by table id + +```bash +greptime cli meta get table --table-id=1059 \ + --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + --pretty +``` + +Output: + +```json +__table_info/1059 +{ + "table_info": { + "ident": { + "table_id": 1059, + "version": 0 + }, + "name": "metric_table_2", + "desc": null, + "catalog_name": "greptime", + "schema_name": "public", + "meta": { + "schema": { + "column_schemas": [ + { + "name": "app", + "data_type": { + "String": null + }, + "is_nullable": true, + "is_time_index": false, + "default_constraint": null, + "metadata": {} + }, + ... + ], + "timestamp_index": 2, + "version": 0 + }, + "primary_key_indices": [ + 0, + ... + ], + "value_indices": [ + 3 + ], + "engine": "metric", + "next_column_id": 8, + "region_numbers": [ + 0, + ... + ], + "options": { + "write_buffer_size": null, + "ttl": null, + "skip_wal": false, + "extra_options": { + "on_physical_table": "greptime_physical_table" + } + }, + "created_on": "2025-06-17T14:53:14.639207075Z", + "partition_key_indices": [] + }, + "table_type": "Base" + }, + "version": 0 +} +__table_route/1059 +{ + "type": "logical", + "physical_table_id": 1057, + "region_ids": [ + 4548370366464, + 4548370366465, + ... + ] +} +``` + +### Get table metadata by table name + +```bash +greptime cli meta get table --table-name=metric_table_2 \ + --schema-name=public \ + --store-addrs=$ENDPOINT \ + --backend=postgres-store +``` + +Output: same as the output of the command above. + +## Delete non-existent key-value pair + +```bash +greptime cli meta del key --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + non_existent_key +``` + +Output(Return deleted key-value pairs count): +```bash +0 +``` + +## Delete a key-value pair + +```bash +greptime cli meta del key --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + __table_name/greptime/public/metric_table_3 +``` + +Output(Return deleted key-value pairs count): +```bash +1 +``` + +## Delete a table metadata + +```bash +greptime cli meta del table --table-id=1059 \ + --store-addrs=$ENDPOINT \ + --backend=postgres-store +``` + +Output: +```bash +Table(1059) deleted +``` diff --git a/versioned_docs/version-1.0/reference/command-lines/utilities/metadata.md b/versioned_docs/version-1.0/reference/command-lines/utilities/metadata.md new file mode 100644 index 0000000000..1d35d0abd2 --- /dev/null +++ b/versioned_docs/version-1.0/reference/command-lines/utilities/metadata.md @@ -0,0 +1,242 @@ +--- +keywords: [metadata backup, metadata restore, export tool, import tool, database metadata backup, metadata recovery, command line tool, GreptimeDB CLI, disaster recovery] +description: Comprehensive guide to GreptimeDB's metadata export and import tools for backing up and restoring database metadata, including command syntax, options. +--- + +# Metadata Export & Import + +The Export and Import tools provide functionality for backing up and restoring GreptimeDB metadata. These tools allow for metadata backup and restoration operations. + +## Export Tool + +### Command Syntax + +```bash +greptime cli meta snapshot save [OPTIONS] +``` + +### Options + +#### Storage Backend Options + +| Option | Required | Default | Description | +| ------------------ | -------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| --store-addrs | Yes | - | Metadata storage service addresses to connect to (only supports etcd MySQL PostgreSQL) format consistent with store-addrs in metasrv configuration | +| --backend | Yes | - | Type of metadata storage backend, one of `etcd-store`, `postgres-store`, `mysql-store` | +| --store-key-prefix | No | "" | Unified prefix for data in metasrv, refer to metasrv configuration | +| --meta-table-name | No | greptime_metakv | When backend is one of `postgres-store`, `mysql-store`, the table name storing metadata | +| --max-txn-ops | No | 128 | Maximum number of txn operations | + +#### File Options + +| Option | Required | Default | Description | +| ------------ | -------- | ----------------- | --------------------------------------------------------------------------- | +| --file-name | No | metadata_snapshot | File name for metadata export, will automatically add `.metadata.fb` suffix | +| --dir | No | "" | Directory to store exported data | + +#### Object Storage Options + +To use object storage for storing exported metadata, enable one of the following providers and configure its connection parameters: + +##### S3 + +| Option | Required | Default | Description | +| ---------------------------- | -------- | ------- | ---------------------------------------------------------------- | +| --enable-s3 | No | false | Whether to use S3 as storage medium for exported data | +| --s3-bucket | No | - | S3 bucket name | +| --s3-root | No | - | Root path in S3 bucket | +| --s3-access-key-id | No | - | S3 access key ID | +| --s3-secret-access-key | No | - | S3 secret access key | +| --s3-region | No | - | S3 region name | +| --s3-endpoint | No | - | S3 endpoint URL (optional, defaults based on bucket region) | +| --s3-enable-virtual-host-style | No | false | Enable virtual host style for S3 API requests | + +##### OSS (Alibaba Cloud) + +| Option | Required | Default | Description | +| ----------------------- | -------- | ------- | -------------------------------------- | +| --enable-oss | No | false | Whether to use OSS for exported data | +| --oss-bucket | No | - | OSS bucket name | +| --oss-root | No | - | Root path in OSS bucket | +| --oss-access-key-id | No | - | OSS access key ID | +| --oss-access-key-secret | No | - | OSS access key secret | +| --oss-endpoint | No | - | OSS endpoint URL | + +##### GCS (Google Cloud Storage) + +| Option | Required | Default | Description | +| --------------------- | -------- | ------- | ------------------------------------- | +| --enable-gcs | No | false | Whether to use GCS for exported data | +| --gcs-bucket | No | - | GCS bucket name | +| --gcs-root | No | - | Root path in GCS bucket | +| --gcs-scope | No | - | GCS service scope | +| --gcs-credential-path | No | - | Path to GCS credential file | +| --gcs-credential | No | - | GCS credential content | +| --gcs-endpoint | No | - | GCS endpoint URL | + +##### Azure Blob Storage + +| Option | Required | Default | Description | +| --------------------- | -------- | ------- | ------------------------------------------- | +| --enable-azblob | No | false | Whether to use Azure Blob for exported data | +| --azblob-container | No | - | Azure Blob container name | +| --azblob-root | No | - | Root path in container | +| --azblob-account-name | No | - | Azure Blob account name | +| --azblob-account-key | No | - | Azure Blob account key | +| --azblob-endpoint | No | - | Azure Blob endpoint URL | +| --azblob-sas-token | No | - | Azure Blob SAS token | + + + +## Import Tool + +### Command Syntax + +```bash +greptime cli meta snapshot restore [OPTIONS] +``` + +### Options + +#### Storage Backend Options + +| Option | Required | Default | Description | +| ------------------ | -------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| --store-addrs | Yes | - | Metadata storage service addresses to connect to (only supports etcd MySQL PostgreSQL) format consistent with store-addrs in metasrv configuration | +| --backend | Yes | - | Type of metadata storage backend, one of `etcd-store`, `postgres-store`, `mysql-store` | +| --store-key-prefix | No | "" | Unified prefix for data in metasrv, refer to metasrv configuration | +| --meta-table-name | No | greptime_metakv | When backend is `postgres-store`, `mysql-store`, the table name storing metadata | +| --max-txn-ops | No | 128 | Maximum number of txn operations | + +#### File Options + +| Option | Required | Default | Description | +| ----------- | -------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| --file-name | No | metadata_snapshot.metadata.fb | File name of metadata export to import | +| --dir | No | "." | Directory storing exported data | +| --force | No | false | Whether to force import, when target backend is detected to not be in a clean state, import is disabled by default, enable this flag to force import | + +#### Object Storage Options + +To use object storage for importing metadata, enable one of the following providers and configure its connection parameters: + +##### S3 + +| Option | Required | Default | Description | +| ---------------------------- | -------- | ------- | ---------------------------------------------------------------- | +| --enable-s3 | No | false | Whether to use S3 as storage medium for exported data | +| --s3-bucket | No | - | S3 bucket name | +| --s3-root | No | - | Root path in S3 bucket | +| --s3-access-key-id | No | - | S3 access key ID | +| --s3-secret-access-key | No | - | S3 secret access key | +| --s3-region | No | - | S3 region name | +| --s3-endpoint | No | - | S3 endpoint URL (optional, defaults based on bucket region) | +| --s3-enable-virtual-host-style | No | false | Enable virtual host style for S3 API requests | + +##### OSS (Alibaba Cloud) + +| Option | Required | Default | Description | +| ----------------------- | -------- | ------- | -------------------------------------- | +| --enable-oss | No | false | Whether to use OSS for exported data | +| --oss-bucket | No | - | OSS bucket name | +| --oss-root | No | - | Root path in OSS bucket | +| --oss-access-key-id | No | - | OSS access key ID | +| --oss-access-key-secret | No | - | OSS access key secret | +| --oss-endpoint | No | - | OSS endpoint URL | + +##### GCS (Google Cloud Storage) + +| Option | Required | Default | Description | +| --------------------- | -------- | ------- | ------------------------------------- | +| --enable-gcs | No | false | Whether to use GCS for exported data | +| --gcs-bucket | No | - | GCS bucket name | +| --gcs-root | No | - | Root path in GCS bucket | +| --gcs-scope | No | - | GCS service scope | +| --gcs-credential-path | No | - | Path to GCS credential file | +| --gcs-credential | No | - | GCS credential content | +| --gcs-endpoint | No | - | GCS endpoint URL | + +##### Azure Blob Storage + +| Option | Required | Default | Description | +| --------------------- | -------- | ------- | ------------------------------------------- | +| --enable-azblob | No | false | Whether to use Azure Blob for exported data | +| --azblob-container | No | - | Azure Blob container name | +| --azblob-root | No | - | Root path in container | +| --azblob-account-name | No | - | Azure Blob account name | +| --azblob-account-key | No | - | Azure Blob account key | +| --azblob-endpoint | No | - | Azure Blob endpoint URL | +| --azblob-sas-token | No | - | Azure Blob SAS token | + +## Info Tool + +The Info tool allows you to view the contents of a metadata snapshot without restoring it. + +### Command Syntax + +```bash +greptime cli meta snapshot info [OPTIONS] +``` + +### Options + +#### File Options + +| Option | Required | Default | Description | +| ------------ | -------- | ----------------- | ------------------------------------------- | +| --file-name | No | metadata_snapshot | File name of the metadata snapshot to view | +| --dir | No | "." | Directory where the snapshot file is stored | +| --inspect-key| No | "*" | Query pattern to filter metadata keys | +| --limit | No | - | Maximum number of entries to display | + +#### Object Storage Options + +To inspect snapshots stored in object storage, enable one of the following providers and configure its connection parameters: + +##### S3 + +| Option | Required | Default | Description | +| ---------------------------- | -------- | ------- | ---------------------------------------------------------------- | +| --enable-s3 | No | false | Whether to use S3 as storage medium for the snapshot | +| --s3-bucket | No | - | S3 bucket name | +| --s3-root | No | - | Root path in S3 bucket | +| --s3-access-key-id | No | - | S3 access key ID | +| --s3-secret-access-key | No | - | S3 secret access key | +| --s3-region | No | - | S3 region name | +| --s3-endpoint | No | - | S3 endpoint URL (optional, defaults based on bucket region) | +| --s3-enable-virtual-host-style | No | false | Enable virtual host style for S3 API requests | + +##### OSS (Alibaba Cloud) + +| Option | Required | Default | Description | +| ----------------------- | -------- | ------- | -------------------------------------- | +| --enable-oss | No | false | Whether to use OSS for the snapshot | +| --oss-bucket | No | - | OSS bucket name | +| --oss-root | No | - | Root path in OSS bucket | +| --oss-access-key-id | No | - | OSS access key ID | +| --oss-access-key-secret | No | - | OSS access key secret | +| --oss-endpoint | No | - | OSS endpoint URL | + +##### GCS (Google Cloud Storage) + +| Option | Required | Default | Description | +| --------------------- | -------- | ------- | ------------------------------------- | +| --enable-gcs | No | false | Whether to use GCS for the snapshot | +| --gcs-bucket | No | - | GCS bucket name | +| --gcs-root | No | - | Root path in GCS bucket | +| --gcs-scope | No | - | GCS service scope | +| --gcs-credential-path | No | - | Path to GCS credential file | +| --gcs-credential | No | - | GCS credential content | +| --gcs-endpoint | No | - | GCS endpoint URL | + +##### Azure Blob Storage + +| Option | Required | Default | Description | +| --------------------- | -------- | ------- | ------------------------------------------- | +| --enable-azblob | No | false | Whether to use Azure Blob for the snapshot | +| --azblob-container | No | - | Azure Blob container name | +| --azblob-root | No | - | Root path in container | +| --azblob-account-name | No | - | Azure Blob account name | +| --azblob-account-key | No | - | Azure Blob account key | +| --azblob-endpoint | No | - | Azure Blob endpoint URL | +| --azblob-sas-token | No | - | Azure Blob SAS token | diff --git a/versioned_docs/version-1.0/reference/command-lines/utilities/repair-logical-tables.md b/versioned_docs/version-1.0/reference/command-lines/utilities/repair-logical-tables.md new file mode 100644 index 0000000000..7a6efdf5a8 --- /dev/null +++ b/versioned_docs/version-1.0/reference/command-lines/utilities/repair-logical-tables.md @@ -0,0 +1,55 @@ +--- +keywords: [GreptimeDB CLI, logical table repair, metadata repair, table metadata, storage backend] +description: Guide for using CLI to repair logical tables in GreptimeDB cluster, including metadata consistency repair. +--- + +# Repair logical tables + +The `greptime cli meta repair-logical-tables` command can be used to repair logical tables for GreptimeDB cluster. In some cases, the logical tables metadata may be inconsistent with metadata stored in the metadata store. This command can be used to repair the logical tables metadata. + +:::tip +The tool needs to connect to both the metadata store and datanode. Ensure that the cluster is running and the tool can communicate with the datanode. +::: + +## Command syntax + +```bash +greptime cli meta repair-logical-tables [OPTIONS] +``` + +## Options + +| Option | Description | Default | Values | +| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------------------- | +| `--store-addrs ...` | The endpoint of store. One of etcd, postgres or mysql.
For postgres store, the format is: `"password=password dbname=postgres user=postgres host=localhost port=5432"`.
For etcd store, the format is: `"127.0.0.1:2379"`.
For mysql store, the format is: `"mysql://user:password@ip:port/dbname"` | - | - | +| `--max-txn-ops ` | The maximum number of operations in a transaction. Only used when using [etcd-store] | 128 | - | +| `--backend ` | The metadata store backend | etcd-store | etcd-store, memory-store, postgres-store, mysql-store | +| `--store-key-prefix ` | The key prefix of the metadata store | - | - | +| `--meta-table-name ` | The table name in RDS to store metadata. Only used when using [postgres-store] or [mysql-store] | greptime_metakv | - | +| `--table-names ` | The names of the tables to repair, separated by comma | - | +| `--table-ids ` | The id of the table to repair, separated by comma | - | +| `--schema-name ` | The schema of the tables to repair | public | +| `--catalog-name ` | The catalog of the tables to repair | greptime | +| `--fail-fast` | Whether to fail fast if any repair operation fails | - | +| `--client-timeout-secs ` | The timeout for the client to operate the datanode | 30 | +| `--client-connect-timeout-secs ` | The timeout for the client to connect to the datanode | 3 | + + +## Examples + +### Repair logical tables by table names + +```bash +greptime cli meta repair-logical-tables --store-addrs=$ENDPOINT \ + --backend=postgres-store \ + --table-names=metric_table_1,metric_table_2 \ + --schema-name=public \ + --catalog-name=greptime +``` + +Output: +```bash +2025-06-20T08:31:43.904497Z INFO cli::metadata::repair: All alter table requests sent successfully for table: greptime.public.metric_table_1 +2025-06-20T08:31:43.904499Z INFO cli::metadata::repair: All alter table requests sent successfully for table: greptime.public.metric_table_2 +2025-06-20T08:31:43.904539Z INFO cli::metadata::repair: Repair logical tables result: 2 tables repaired, 0 tables skipped +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/glossary.md b/versioned_docs/version-1.0/reference/glossary.md new file mode 100644 index 0000000000..d7079e2339 --- /dev/null +++ b/versioned_docs/version-1.0/reference/glossary.md @@ -0,0 +1,240 @@ +--- +keywords: [cloud-native, observability, open-source, time-series database, connected vehicles, IoT, log, metrics, events, rust] +description: The GreptimeDB Glossary provides clear definitions and explanations of core terms and concepts related to GreptimeDB, the cloud-native open source temporal database, covering the areas of metrics, logging, and events processing. Explore the Glossary to gain insight into the innovative features and technical architecture that underpin GreptimeDB. +--- + +# GreptimeDB Glossary + +Welcome to the GreptimeDB Glossary! This resource provides clear definitions and explanations of key terms and concepts associated with GreptimeDB, a cloud-native, open-source time-series database designed for metrics, logs, and events. Explore the glossary to better understand the innovative features and technologies behind GreptimeDB. + +--- + +## A + +### Anomaly Detection +The process of identifying data points, events, or observations that deviate significantly from the norm. In time-series data, anomaly detection helps in spotting unusual patterns that may indicate critical incidents. + +### Append Only Table +A table type in GreptimeDB optimized for write-heavy workloads where data is only inserted, never updated or deleted. This design significantly improves write and query performance, especially for log analytics and time-series data scenarios. + +--- + +## C + +### Cardinality +A measure of the uniqueness of data elements in a database, such as the number of unique values in a column. High cardinality can increase the complexity and storage requirements of a database, especially in time-series data. + +### Cloud-Native Design +An architectural approach that utilizes cloud computing frameworks and services to build scalable and resilient applications. GreptimeDB's cloud-native design allows it to scale effortlessly from edge deployments to distributed clusters in the cloud. + +### Columnar Storage +A data storage format that stores data tables by columns rather than rows. This format enhances performance for read-heavy operations and is optimized for analytical queries, contributing to GreptimeDB's cost efficiency. + +--- + +## D + +### Decoupled Compute and Storage Architecture +An architectural design where computing resources and storage are managed separately. This separation enables independent scaling and resource optimization, leading to improved performance and flexibility in managing workloads. + +--- + +## E + +### Edge Database +A database deployed at the edge of a network, close to the data source or user, to minimize latency and optimize data processing in real-time. + +### Edge Deployment +The practice of deploying applications or services closer to the data source or end-user to reduce latency and bandwidth usage. GreptimeDB supports edge deployment, allowing for real-time data processing in resource-limited environments. + +### Event Management +The practice of collecting, organizing, and analyzing events—including metrics, logs, and traces—to monitor and optimize systems. Event management is a critical aspect of maintaining real-time systems and applications. + +--- + +## D + +### Datanode +A core component in GreptimeDB's distributed architecture responsible for data storage and processing. Datanodes handle data ingestion, storage management, query execution on local data, and maintain regions containing actual table data. Multiple datanodes can be deployed across a cluster to provide horizontal scalability, fault tolerance, and distributed data processing capabilities. + +--- + +## F + +### Field +A column type in GreptimeDB's data model that contains the actual measurement data or log contents being collected. Fields store the numerical values, text content, or other data indicators that represent the core information in time-series data, complementing Tag and Time Index columns to form the complete data model. + +### Frontend +The query processing layer in GreptimeDB's distributed architecture that serves as the entry point for client connections. Frontend nodes handle SQL parsing, query planning, distributed query coordination, and result aggregation. They route queries to appropriate datanodes, manage client sessions, and provide protocol compatibility for various database interfaces including MySQL, PostgreSQL, and GreptimeDB's native protocols. + + + +### Flow Engine +GreptimeDB's real-time stream processing system that enables continuous, incremental computation on streaming data. Flow Engine works like an intelligent materialized view that automatically updates result tables as new data arrives in source tables. It processes data at configurable intervals (default: one second) with minimal computational overhead, making it ideal for ETL processes, downsampling, real-time analytics, and continuous aggregation scenarios. + +--- + +## G + +### GreptimeCloud +The fully managed cloud service offering of GreptimeDB that provides serverless, auto-scaling database-as-a-service (DBaaS) capabilities. GreptimeCloud eliminates operational overhead with features like automatic scaling, pay-as-you-go pricing, enterprise-grade security, and seamless cloud-to-edge deployment, making it ideal for organizations seeking a hassle-free observability database solution. + +--- + +## I + +### IoT Cloud +A cloud computing platform specifically designed to support Internet of Things (IoT) applications by providing the necessary storage, processing power, and connectivity to manage IoT data at scale. + +### IoT Database +A database optimized for handling Internet of Things (IoT) data, which often involves time-series metrics from sensors and devices. GreptimeDB is suitable for IoT use cases, providing scalable and efficient storage and querying for high-frequency data generated by IoT devices. + +### IoT Observability +The ability to monitor, analyze, and gain insights into IoT devices and systems through metrics, logs, and events. IoT observability ensures that devices and applications perform reliably and efficiently. + +### Interoperability +The ability of different systems, applications, or products to connect and communicate in a coordinated way without effort from the end-user. GreptimeDB supports widely adopted database protocols and APIs, including SQL, InfluxDB, OpenTelemetry, Prometheus, Elasticsearch, and Loki, ensuring seamless integration. + +--- + +## L + +### Log Aggregation +Perform calculations on a set of logs to generate a single summary statistic for analysis and troubleshooting. For example, SUM, COUNT, etc. + +### Log Management +The overall process of handling log data, including collection, storage, analysis, and visualization, to ensure system performance and security. + +--- + +## M + +### Memory Leak +A type of software bug where a program fails to release unused memory, causing a gradual decrease in available memory and potential system instability over time. + +### Metric Engine +A specialized storage engine in GreptimeDB designed for efficient processing of metrics data, particularly scenarios with thousands of small tables common in observability workloads. The Metric Engine uses synthetic wide physical tables to store data from numerous logical tables, enabling efficient column and metadata reuse, reducing storage overhead, and enhancing columnar compression. Built on top of the Mito Engine for robust storage capabilities. + +### Mito Engine +The default storage engine in GreptimeDB based on Log-Structured Merge Tree (LSM-Tree) architecture, optimized for time-series workloads. Mito features Write-Ahead Logging (WAL), memory tables, and Time Window Compaction Strategy (TWCS) to handle high-throughput writes while maintaining excellent query performance. It integrates natively with object storage solutions (S3, GCS, Azure Blob) and implements tiered caching for optimal storage costs and access speeds. + +--- + +## L + +### LSM-Tree (Log-Structured Merge Tree) +A data structure used by GreptimeDB's storage engine that optimizes write performance by initially writing data to a log and periodically merging these logs into sorted structures. This design is particularly effective for time-series workloads with high write throughput. + +--- + +## M + +### Metasrv +The metadata management service in GreptimeDB's distributed architecture that maintains cluster state, table schemas, and region distribution information. Metasrv coordinates cluster operations, manages table creation and modifications, handles region assignments and migrations, and ensures metadata consistency across the cluster. It acts as the central control plane for cluster management and serves as the source of truth for all metadata operations. + +--- + +## O + +### Observability +A measure of how well the internal states of a system can be inferred based on its external outputs. Observability tools, such as GreptimeDB, help engineers monitor, debug, and gain insights into system performance by analyzing metrics, logs, and events. + +### OpenTelemetry +An open-source observability framework for cloud-native software. OpenTelemetry provides APIs and SDKs for collecting, processing, and exporting telemetry data such as traces, metrics, and logs. GreptimeDB integrates with OpenTelemetry to enhance data observability. + +--- + +## P + +### PromQL (Prometheus Query Language) +A powerful and flexible query language used to retrieve and manipulate time-series data stored in Prometheus. GreptimeDB supports PromQL with near 100% compatibility, enabling users to perform complex queries on their time-series data and use existing Prometheus dashboards and alerting rules. + +--- + +## P + +### Pipeline +A powerful data parsing and transformation mechanism in GreptimeDB designed for processing incoming data in real-time. Pipeline consists of configurable processors that pre-process raw data, dispatchers that route data to different pipelines, and transform rules that convert data types and define table structures. It supports multiple input formats and data sources (including logs, Prometheus metrics, and other observability data) and provides extensive processing capabilities including timestamp parsing, regex matching, field extraction, and data type conversion, enabling structured storage and efficient querying of observability data. + +--- + +## R + +### Read Replica +An enterprise feature in GreptimeDB that creates additional read-only instances of data to enhance query performance and scalability. Read replicas distribute read workloads across multiple instances, reducing load on primary databases while providing faster query responses. This feature supports geographic distribution of data access points, improves high availability for read operations, and enables efficient scaling of read-intensive workloads in enterprise environments. + +### Region +A fundamental unit of data distribution in GreptimeDB's architecture. Regions contain a subset of table data and can be distributed across different nodes in a cluster. Each region manages its own storage, indexing, and query processing, enabling horizontal scalability and fault tolerance. + +### Rust +A modern programming language known for its performance and safety features, particularly in system-level programming. GreptimeDB is built with Rust, contributing to its superior performance and reliability. + +--- + +## S + +### Scalability +The capability of a database system to handle growing volumes of data and increasing query loads efficiently by scaling resources either vertically (adding more power to a single server) or horizontally (adding more servers to a cluster). Scalability ensures that the system can accommodate future growth without sacrificing performance or reliability, making it crucial for modern data-intensive applications. + +### SQL (Structured Query Language) +A standardized programming language used for managing and manipulating relational databases. GreptimeDB supports SQL, allowing users to query metrics, logs, and events efficiently. + +### Stream Processing +The continuous, real-time processing of data streams as they arrive. In GreptimeDB, stream processing is implemented through the Flow Engine, which performs incremental computation on streaming time-series data. This enables instant filtering, computing, and aggregation of metrics, logs, and events, providing actionable insights with minimal latency. + +--- + +## T + +### Tag +A column type in GreptimeDB's data model that uniquely identifies time-series data. Rows with the same Tag values belong to the same time-series, making Tags essential for organizing and querying observability data. Tags are typically used to store metadata like host names, service names, or device IDs, and are specified as PRIMARY KEY columns in table schemas. + +### Time Index +A special timestamp column in GreptimeDB tables that serves as the primary time dimension for time-series data. Every GreptimeDB table requires exactly one Time Index column to organize data chronologically, enable time-based queries, and support efficient time-series operations like downsampling and time-window aggregations. + +### Time Series Database +A specialized database designed to handle time-series data, which consists of sequences of data points indexed by timestamps. GreptimeDB is a cloud-native time-series database optimized for analyzing and querying metrics, logs, and events. + +--- + +## T + +### Trigger +An enterprise-grade monitoring and alerting feature in GreptimeDB that enables automated evaluation of time-series data conditions. Triggers continuously monitor data in tables at specified intervals, execute SQL-based rules to check for predefined thresholds or conditions, and send notifications via webhooks when criteria are met. This feature integrates with alerting systems like Alertmanager and supports custom labels and annotations, making it ideal for real-time system monitoring, performance alerting, and automated incident response. + +--- + +## U + +### Unified Analysis +The integration of various data types and sources into a single platform for analysis. GreptimeDB provides unified analysis by allowing users to query metrics, logs, and events using SQL and PromQL, simplifying data analytics workflows. + +### Unified Observability +A database architecture approach that consolidates metrics, logs, and traces into a single system, eliminating data silos and reducing operational complexity. GreptimeDB implements unified observability by treating all telemetry data types as wide events with timestamps, enabling cross-signal correlation, simplified data pipelines, and cost-effective observability infrastructure. + +--- + +## W + +### WAL (Write-Ahead Log) +A logging mechanism used by GreptimeDB to ensure data durability and consistency. WAL records all data changes before they are applied to the main storage, enabling recovery in case of system failures. GreptimeDB supports flexible WAL options including local disk storage or distributed services like Kafka. + +### Wide Events +A foundational concept in Observability 2.0 that represents context-rich, high-dimensional telemetry data combining metrics, logs, and traces into single comprehensive events. Wide Events capture extensive contextual information per service interaction, including high-cardinality fields (user IDs, session IDs), business logic data, infrastructure details, and request metadata. GreptimeDB natively supports Wide Events as timestamped observability data, enabling complex multi-dimensional querying and solving "unknown unknowns" in system behavior analysis. + +--- + +## V + +### Vector Processing +A high-performance data processing technique used by GreptimeDB's query engine that operates on data in batches (vectors) rather than individual values. Leverages SIMD instructions for acceleration, significantly improving query performance on large-scale time-series datasets. + +### Vehicle Data Collection +The process of gathering data generated by vehicles, such as sensor readings, GPS locations, and diagnostics, for analysis and insights. Vehicle data collection is a key component of modern IoT ecosystems. + +### Vehicle-Cloud Integrated TSDB +A time-series database designed to work seamlessly with vehicle data and cloud-based systems, enabling efficient data storage, querying, and real-time analysis for connected vehicle applications. + +--- + +*Note: This glossary is a work in progress and will be updated as new features and concepts emerge within the GreptimeDB ecosystem.* \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/gtctl.md b/versioned_docs/version-1.0/reference/gtctl.md new file mode 100644 index 0000000000..1b69102874 --- /dev/null +++ b/versioned_docs/version-1.0/reference/gtctl.md @@ -0,0 +1,246 @@ +--- +keywords: [gtctl, command-line tool, cluster management, installation, Kubernetes, bare-metal, deployment, autocompletion] +description: Instructions for installing and using gtctl, a command-line tool for managing GreptimeDB clusters, including installation methods, autocompletion setup, and deployment modes. +--- + +# gtctl + +[gtctl][1], g-t-control, is a command-line tool for managing the GreptimeDB clusters. gtctl is the **All-in-One** binary that integrates with multiple operations of GreptimeDB clusters. + +## Installation + +### One-line Installation + +Download the binary using the following command: + +```bash +curl -fsSL https://raw.githubusercontent.com/greptimeteam/gtctl/develop/hack/install.sh | sh +``` + +After downloading, the gtctl will be in the current directory. + +You also can install gtctl from the AWS-CN S3 bucket: + +```bash +curl -fsSL https://downloads.greptime.cn/releases/scripts/gtctl/install.sh | sh -s -- -s aws +``` + +### Homebrew + +On macOS, gtctl is available via Homebrew: + +```bash +brew tap greptimeteam/greptime +brew install gtctl +``` + +### From Source + +If you already have the [Go][2] installed, you can run the `make` command under this project to build gtctl: + +```bash +make gtctl +``` + +After building, the gtctl will be generated in `./bin/`. If you want to install gtctl, you can run the `install` command: + +```bash +# The built gtctl will be installed in /usr/local/bin. +make install + +# The built gtctl will be installed in your customed path. +make install INSTALL_DIR= +``` + +## Enable gtctl Autocompletion (Optional) + +The gtctl supports autocompletion of several different shells. + +### Bash + +The gtctl completion script for Bash can be generated with the command `gtctl completion bash`. Sourcing the completion script in your shell enables gtctl autocompletion. + +```bash +echo 'source <(gtctl completion bash)' >> ~/.bashrc +``` + +### Zsh + +The gtctl completion script for Zsh can be generated with the command `gtctl completion zsh`. Sourcing the completion script in your shell enables gtctl autocompletion. + +```bash +mkdir -p $ZSH/completions && gtctl completion zsh > $ZSH/completions/_gtctl +``` + +### Fish + +The gtctl completion script for Fish can be generated with the command `gtctl completion fish`. Sourcing the completion script in your shell enables gtctl autocompletion. + +```bash +gtctl completion fish | source +``` + +## Quick Start + +The **fastest** way to experience the GreptimeDB cluster is to use the playground: + +```bash +gtctl playground +``` + +The `playground` will deploy the minimal GreptimeDB cluster on your environment in **bare-metal** mode. + +## Deployments + +The gtctl supports two deployment mode: Kubernetes and Bare-Metal. + +### Kubernetes + +#### Prerequisites + +* Kubernetes 1.18 or higher version is required. + + You can use the [kind][3] to create your own Kubernetes cluster: + + ```bash + kind create cluster + ``` + +#### Create + +Create your own GreptimeDB cluster and etcd cluster: + +```bash +gtctl cluster create mycluster -n default +``` + +If you want to use artifacts(charts and images) that are stored in the CN region, you can enable `--use-greptime-cn-artifacts`: + +```bash +gtctl cluster create mycluster -n default --use-greptime-cn-artifacts +``` + +After creating, the whole GreptimeDB cluster will start in the default namespace: + +```bash +# Get the cluster. +gtctl cluster get mycluster -n default + +# List all clusters. +gtctl cluster list +``` + +All the values used for cluster, etcd and operator which provided in [charts][4] are configurable, you can use `--set` to configure them. The gtctl also surface some commonly used configurations, you can use `gtctl cluster create --help` to browse them. + +```bash +# Configure cluster datanode replicas to 5 +gtctl cluster create mycluster --set cluster.datanode.replicas=5 + +# Two same ways to configure etcd storage size to 15Gi +gtctl cluster create mycluster --set etcd.storage.volumeSize=15Gi +gtctl cluster create mycluster --etcd-storage-size 15Gi +``` + +#### Dry Run + +gtctl provides `--dry-run` option in cluster creation. If a user executes the command with `--dry-run`, gtctl will output the manifests content without applying them: + +```bash +gtctl cluster create mycluster -n default --dry-run +``` + +#### Connect + +You can use the kubectl `port-forward` command to forward frontend requests: + +```bash +kubectl port-forward svc/mycluster-frontend 4002:4002 > connections.out & +``` + +Use gtctl `connect` command or your `mysql` client to connect to your cluster: + +```bash +gtctl cluster connect mycluster -p mysql + +mysql -h 127.0.0.1 -P 4002 +``` + +#### Scale (Experimental) + +You can use the following commands to scale (or down-scale) your cluster: + +```bash +# Scale datanode to 3 replicas. +gtctl cluster scale -n -c datanode --replicas 3 + +# Scale frontend to 5 replicas. +gtctl cluster scale -n -c frontend --replicas 5 +``` + +#### Delete + +If you want to delete the cluster, you can: + +```bash +# Delete the cluster. +gtctl cluster delete mycluster -n default + +# Delete the cluster, including etcd cluster. +gtctl cluster delete mycluster -n default --tear-down-etcd +``` + +### Bare-Metal + +#### Create + +You can deploy the GreptimeDB cluster on a bare-metal environment by the following simple command: + +```bash +gtctl cluster create mycluster --bare-metal +``` + +It will create all the necessary meta information on `${HOME}/.gtctl`. + +If you want to do more configurations, you can use the yaml format config file: + +```bash +gtctl cluster create mycluster --bare-metal --config +``` + +You can refer to the example config `cluster.yaml` and `cluster-with-local-artifacts.yaml` provided in [`examples/bare-metal`][5]. + +#### Delete + +Since the cluster in bare-metal mode runs in the foreground, any `SIGINT` and `SIGTERM` will delete the cluster. For example, the cluster will be deleted after pressing `Ctrl+C` on keyboard. + +The deletion will also delete the meta information of one cluster which located in `${HOME}/.gtctl`. The logs of cluster will remain if `--retain-logs` is enabled (enabled by default). + +## Development + +There are many useful tools provided through Makefile, you can simply run make help to get more information: + +* Compile the project + + ```bash + make + ``` + + Then the gtctl will be generated in `./bin/`. + +* Run the unit test + + ```bash + make test + ``` + +* Run the e2e test + + ```bash + make e2e + ``` + +[1]: +[2]: +[3]: +[4]: +[5]: diff --git a/versioned_docs/version-1.0/reference/http-endpoints.md b/versioned_docs/version-1.0/reference/http-endpoints.md new file mode 100644 index 0000000000..2ce4678bd5 --- /dev/null +++ b/versioned_docs/version-1.0/reference/http-endpoints.md @@ -0,0 +1,236 @@ +--- +keywords: [HTTP API, endpoints, health check, status, metrics, configuration, query APIs, PromQL, InfluxDB, OpenTelemetry] +description: Provides a full list of HTTP paths and their usage in GreptimeDB, including admin APIs, query endpoints, and protocol endpoints. +--- + +# HTTP API Endpoint List + +Here is the full list for the various HTTP paths and their usage in GreptimeDB: + +## Admin APIs + +Endpoints that is not versioned (under `/v1`). For admin usage like health check, status, metrics, etc. + +### Health Check + +- **Path**: `/health` +- **Methods**: `GET`, `POST` +- **Description**: Provides a health check endpoint to verify that the server is running. +- **Usage**: Access this endpoint to check the health status of the server. + +Please refer to the [check GreptimeDB health documentation](/enterprise/deployments-administration/monitoring/check-db-status.md#check-if-greptimedb-is-running-normally) for an example. + +### Status + +- **Path**: `/status` +- **Methods**: `GET` +- **Description**: Retrieves the current status of the server. +- **Usage**: Use this endpoint to obtain server status information. + +Please refer to the [Check GreptimeDB status documentation](/enterprise/deployments-administration/monitoring/check-db-status.md#check-greptimedb-status) for an example. + +### Metrics + +- **Path**: `/metrics` +- **Methods**: `GET` +- **Description**: Exposes Prometheus metrics for monitoring purposes. +- **Usage**: Prometheus can scrape this endpoint to collect metrics data. + +Example: + +```bash +curl -X GET http://127.0.0.1:4000/metrics + +# HELP greptime_app_version app version +# TYPE greptime_app_version gauge +greptime_app_version{app="greptime-edge",short_version="main-b4bd34c5",version="0.12.0"} 1 +# HELP greptime_catalog_catalog_count catalog catalog count +# TYPE greptime_catalog_catalog_count gauge +greptime_catalog_catalog_count 1 +# HELP greptime_catalog_schema_count catalog schema count +# TYPE greptime_catalog_schema_count gauge +greptime_catalog_schema_count 3 +# HELP greptime_flow_run_interval_ms flow run interval in ms +# TYPE greptime_flow_run_interval_ms gauge +greptime_flow_run_interval_ms 1000 +# HELP greptime_meta_create_catalog meta create catalog +# TYPE greptime_meta_create_catalog histogram +greptime_meta_create_catalog_bucket{le="0.005"} 1 +greptime_meta_create_catalog_bucket{le="0.01"} 1 +greptime_meta_create_catalog_bucket{le="0.025"} 1 +greptime_meta_create_catalog_bucket{le="0.05"} 1 +greptime_meta_create_catalog_bucket{le="0.1"} 1 +... +``` + +### Configuration + +- **Path**: `/config` +- **Methods**: `GET` +- **Description**: Retrieves the server's configuration options. +- **Usage**: Access this endpoint to get configuration details. + +For example: + +```shell +curl http://localhost:4000/config +``` + +The output contains the configuration information of the GreptimeDB server. + +```toml +enable_telemetry = true +user_provider = "static_user_provider:file:user" +init_regions_in_background = false +init_regions_parallelism = 16 + +[http] +addr = "127.0.0.1:4000" +timeout = "30s" +body_limit = "64MiB" +is_strict_mode = false + +# ... +``` + +### Dashboard + +- **Paths**: `/dashboard` +- **Methods**: `GET`, `POST` +- **Description**: Provides access to the server's dashboard interface. +- **Usage**: Access these endpoints to interact with the web-based dashboard. + +This dashboard is packaged with the GreptimeDB server and provides a user-friendly interface for interacting with the server. It requires corresponding compile flags to be enabled when building GreptimeDB. The original source code for the dashboard can be found at https://github.com/GreptimeTeam/dashboard + +### Log Level + +- **Path**: `/debug/log_level` +- **Methods**: `POST` +- **Description**: Adjusts the server's log level dynamically. +- **Usage**: Send a log level change request to this endpoint. + +For more information, refer to the [how-to documentation](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-change-log-level-on-the-fly.md). + +### Profiling Tools + +- **Base Path**: `/debug/prof/` +- **Endpoints**: + - `cpu` + - `mem` +- **Methods**: `POST` for profiling the database node. +- **Description**: Runtime profiling for CPU or Memory usage. +- **Usage**: + - Refer to [Profiling CPU](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-profile-cpu.md) for detailed guide for CPU profiling. + - Refer to [Profiling Memory](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-profile-memory.md) for detailed guide for Memory profiling. + +## Query Endpoints + +Various query APIs for sending query to GreptimeDB. + +### SQL API + +- **Path**: `/v1/sql` +- **Methods**: `GET`, `POST` +- **Description**: Executes SQL queries against the server. +- **Usage**: Send SQL queries in the request body. + +For more information on the SQL API, refer to the [HTTP API documentation](/user-guide/protocols/http.md#post-sql-statements) in the user guide. + +### PromQL API + +- **Path**: `/v1/promql` +- **Methods**: `GET`, `POST` +- **Description**: Executes PromQL queries for Prometheus-compatible metrics, and returns data in GreptimeDB's JSON format. +- **Usage**: Send PromQL queries in the request body. + +For more information on the PromQL API, refer to the [PromQL documentation](/user-guide/query-data/promql.md). + +## Protocol Endpoints + +Endpoints for various protocols that are compatible with GreptimeDB. Like InfluxDB, Prometheus, OpenTelemetry, etc. + +### InfluxDB Compatibility + +- **Paths**: + - `/v1/influxdb/write` + - `/v1/influxdb/api/v2/write` + - `/v1/influxdb/ping` + - `/v1/influxdb/health` +- **Methods**: + - `POST` for write endpoints. + - `GET` for ping and health endpoints. +- **Description**: Provides endpoints compatible with InfluxDB for data ingestion and health checks. +- **Usage**: + - Ingest data using InfluxDB line protocol. + - Use ping and health endpoints to check server status. + +The detailed documentation for InfluxDB protocol can be found at [here](/user-guide/protocols/influxdb-line-protocol.md). + +### Prometheus Remote Write/Read + +- **Paths**: + - `/v1/prometheus/write` + - `/v1/prometheus/read` +- **Methods**: `POST` +- **Description**: Supports Prometheus remote write and read APIs. +- **Usage**: + - Send metric data using Prometheus remote write protocol. + - Read metric data using Prometheus remote read protocol. + +### Prometheus HTTP API + +- **Base Path**: `/v1/prometheus/api/v1` +- **Endpoints**: + - `/format_query` + - `/status/buildinfo` + - `/query` + - `/query_range` + - `/labels` + - `/series` + - `/parse_query` + - `/label/{label_name}/values` +- **Methods**: `GET`, `POST` +- **Description**: Provides Prometheus HTTP API endpoints for querying and retrieving metric data. +- **Usage**: Use these endpoints to interact with metrics using standard Prometheus HTTP API. + +Refer to the original Prometheus documentation for more information on the [Prometheus HTTP API](https://prometheus.io/docs/prometheus/latest/querying/api/). + +### OpenTelemetry Protocol (OTLP) + +- **Paths**: + - `/v1/otlp/v1/metrics` + - `/v1/otlp/v1/traces` + - `/v1/otlp/v1/logs` +- **Methods**: `POST` +- **Description**: Supports OpenTelemetry protocol for ingesting metrics, traces, and logs. +- **Usage**: Send OpenTelemetry formatted data to these endpoints. + +### Loki Compatibility + +- **Path**: `/v1/loki/api/v1/push` +- **Methods**: `POST` +- **Description**: Compatible with Loki's API for log ingestion. +- **Usage**: Send log data in Loki's format to this endpoint. + +### OpenTSDB Protocol + +- **Path**: `/v1/opentsdb/api/put` +- **Methods**: `POST` +- **Description**: Supports data ingestion using the OpenTSDB protocol. +- **Usage**: Ingest time series data using OpenTSDB's JSON format. + +## Log Ingestion Endpoints + +- **Paths**: + - `/v1/ingest` + - `/v1/pipelines/{pipeline_name}` + - `/v1/pipelines/dryrun` +- **Methods**: + - `POST` for ingesting logs and adding pipelines. + - `DELETE` for deleting pipelines. +- **Description**: Provides endpoints for log ingestion and pipeline management. +- **Usage**: + - Ingest logs via the `/logs` endpoint. + - Manage log pipelines using the `/pipelines` endpoints. + +For more information on log ingestion and pipeline management, refer to the [log overview](/user-guide/logs/overview.md). diff --git a/versioned_docs/version-1.0/reference/pipeline/built-in-pipelines.md b/versioned_docs/version-1.0/reference/pipeline/built-in-pipelines.md new file mode 100644 index 0000000000..ad168a124c --- /dev/null +++ b/versioned_docs/version-1.0/reference/pipeline/built-in-pipelines.md @@ -0,0 +1,187 @@ +--- +keywords: [built-in pipelines, greptime_identity, JSON logs, log processing, time index, pipeline, GreptimeDB] +description: Learn about GreptimeDB's built-in pipelines, including the greptime_identity pipeline for processing JSON logs with automatic schema creation, type conversion, and time index configuration. +--- + +# Built-in Pipelines + +GreptimeDB offers built-in pipelines for common log formats, allowing you to use them directly without creating new pipelines. + +Note that the built-in pipelines are not editable. +Additionally, the "greptime_" prefix of the pipeline name is reserved. + +## `greptime_identity` + +The `greptime_identity` pipeline is designed for writing JSON logs and automatically creates columns for each field in the JSON log. Nested JSON objects are automatically flattened into separate columns using dot notation. + +- Nested objects are automatically flattened (e.g., `{"a": {"b": 1}}` becomes column `a.b`) +- Arrays are converted to JSON strings +- An error is returned if the same field has different types +- Fields with `null` values are ignored +- If time index is not specified, an additional column, `greptime_timestamp`, is added to the table as the time index to indicate when the log was written + +### Type conversion rules + +- `string` -> `string` +- `number` -> `int64` or `float64` +- `boolean` -> `bool` +- `null` -> ignore +- `array` -> `string` (JSON-stringified) +- `object` -> automatically flattened into separate columns (see [Flatten JSON objects](#flatten-json-objects)) + + +For example, if we have the following json data: + +```json +[ + {"name": "Alice", "age": 20, "is_student": true, "score": 90.5,"object": {"a":1,"b":2}}, + {"age": 21, "is_student": false, "score": 85.5, "company": "A" ,"whatever": null}, + {"name": "Charlie", "age": 22, "is_student": true, "score": 95.5,"array":[1,2,3]} +] +``` + +We'll merge the schema for each row of this batch to get the final schema. Note that nested objects are automatically flattened into separate columns (e.g., `object.a`, `object.b`), and arrays are converted to JSON strings. The table schema will be: + +```sql +mysql> desc pipeline_logs; ++--------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+---------------------+------+------+---------+---------------+ +| age | Int64 | | YES | | FIELD | +| is_student | Boolean | | YES | | FIELD | +| name | String | | YES | | FIELD | +| object.a | Int64 | | YES | | FIELD | +| object.b | Int64 | | YES | | FIELD | +| score | Float64 | | YES | | FIELD | +| company | String | | YES | | FIELD | +| array | String | | YES | | FIELD | +| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | ++--------------------+---------------------+------+------+---------+---------------+ +9 rows in set (0.00 sec) +``` + +The data will be stored in the table as follows: + +```sql +mysql> select * from pipeline_logs; ++------+------------+---------+----------+----------+-------+---------+-----------+----------------------------+ +| age | is_student | name | object.a | object.b | score | company | array | greptime_timestamp | ++------+------------+---------+----------+----------+-------+---------+-----------+----------------------------+ +| 22 | 1 | Charlie | NULL | NULL | 95.5 | NULL | [1,2,3] | 2024-10-18 09:35:48.333020 | +| 21 | 0 | NULL | NULL | NULL | 85.5 | A | NULL | 2024-10-18 09:35:48.333020 | +| 20 | 1 | Alice | 1 | 2 | 90.5 | NULL | NULL | 2024-10-18 09:35:48.333020 | ++------+------------+---------+----------+----------+-------+---------+-----------+----------------------------+ +3 rows in set (0.01 sec) +``` + +### Specify time index + +A time index is necessary in GreptimeDB. Since the `greptime_identity` pipeline does not require a YAML configuration, you must set the time index in the query parameters if you want to use the timestamp from the log data instead of the automatically generated timestamp when the data arrives. + +Example of Incoming Log Data: +```JSON +[ + {"action": "login", "ts": 1742814853} +] +``` + +To instruct the server to use ts as the time index, set the following query parameter in the HTTP header: +```shell +curl -X "POST" "http://localhost:4000/v1/ingest?db=public&table=pipeline_logs&pipeline_name=greptime_identity&custom_time_index=ts;epoch;s" \ + -H "Content-Type: application/json" \ + -H "Authorization: Basic {{authentication}}" \ + -d $'[{"action": "login", "ts": 1742814853}]' +``` + +The `custom_time_index` parameter accepts two formats, depending on the input data format: +- Epoch number format: `;epoch;` + - The field can be an integer or a string. + - The resolution must be one of: `s`, `ms`, `us`, or `ns`. +- Date string format: `;datestr;` + - For example, if the input data contains a timestamp like `2025-03-24 19:31:37+08:00`, the corresponding format should be `%Y-%m-%d %H:%M:%S%:z`. + +With the configuration above, the resulting table will correctly use the specified log data field as the time index. +```sql +DESC pipeline_logs; +``` +```sql ++--------+-----------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------+-----------------+------+------+---------+---------------+ +| ts | TimestampSecond | PRI | NO | | TIMESTAMP | +| action | String | | YES | | FIELD | ++--------+-----------------+------+------+---------+---------------+ +2 rows in set (0.02 sec) +``` + +Here are some example of using `custom_time_index` assuming the time variable is named `input_ts`: +- 1742814853: `custom_time_index=input_ts;epoch;s` +- 1752749137000: `custom_time_index=input_ts;epoch;ms` +- "2025-07-17T10:00:00+0800": `custom_time_index=input_ts;datestr;%Y-%m-%dT%H:%M:%S%z` +- "2025-06-27T15:02:23.082253908Z": `custom_time_index=input_ts;datestr;%Y-%m-%dT%H:%M:%S%.9f%#z` + + +### Flatten JSON objects + +The `greptime_identity` pipeline **automatically flattens** nested JSON objects into a single-level structure. This behavior is always enabled and creates separate columns for each nested field using dot notation (e.g., `a.b.c`). + +#### Controlling flattening depth + +You can control how deeply nested objects are flattened using the `max_nested_levels` parameter in the `x-greptime-pipeline-params` header. The default value is 10 levels. + +Here is a sample request: + +```shell +curl -X "POST" "http://localhost:4000/v1/ingest?db=&table=&pipeline_name=greptime_identity&version=" \ + -H "Content-Type: application/x-ndjson" \ + -H "Authorization: Basic {{authentication}}" \ + -H "x-greptime-pipeline-params: max_nested_levels=5" \ + -d "$" +``` + +When the maximum nesting level is reached, any remaining nested structure is converted to a JSON string and stored in a single column. For example, with `max_nested_levels=3`: + +```JSON +{ + "a": { + "b": { + "c": { + "d": [1, 2, 3] + } + } + }, + "e": [ + "foo", + "bar" + ], + "f": { + "g": { + "h": 123, + "i": "hello", + "j": { + "k": true + } + } + } +} +``` + +Will be flattened to: + +```json +{ + "a.b.c": "{\"d\":[1,2,3]}", + "e": "[\"foo\",\"bar\"]", + "f.g.h": 123, + "f.g.i": "hello", + "f.g.j": "{\"k\":true}" +} +``` + +Note that: +- Arrays at any level are always converted to JSON strings (e.g., `"e"` becomes `"[\"foo\",\"bar\"]"`) +- When the nesting level limit is reached (level 3 in this example), the remaining nested objects are converted to JSON strings (e.g., `"a.b.c"` and `"f.g.j"`) +- Regular scalar values within the depth limit are stored as their native types (e.g., `"f.g.h"` as integer, `"f.g.i"` as string) + + + diff --git a/versioned_docs/version-1.0/reference/pipeline/pipeline-config.md b/versioned_docs/version-1.0/reference/pipeline/pipeline-config.md new file mode 100644 index 0000000000..522b8f1b12 --- /dev/null +++ b/versioned_docs/version-1.0/reference/pipeline/pipeline-config.md @@ -0,0 +1,1164 @@ +--- +keywords: [pipeline configuration, log parsing, log transformation, processors, transform rules] +description: Explains the configuration of pipelines in GreptimeDB for parsing and transforming log data, including processors and transform rules. +--- + +# Pipeline Configuration + +Pipeline is a mechanism in GreptimeDB for parsing and transforming log data. It consists of a unique name and a set of configuration rules that define how log data is formatted, split, and transformed. Currently, we support JSON (`application/json` or `application/x-ndjson`, the latter is preferred) and plain text (`text/plain`) formats as input for log data. + +These configurations are provided in YAML format, allowing the Pipeline to process data during the log writing process according to the defined rules and store the processed data in the database for subsequent structured queries. + +## Input Formats + +In general, a pipeline receives a set of key-value pairs in the form of a map as its input. The following three formats can all be used as pipeline input: + +### JSON Format + +When the request's Content-Type is `application/json`, the data format should be standard JSON. + +```json +[ + {"message": "hello world", "time": "2024-07-12T16:18:53.048"}, + {"message": "hello greptime", "time": "2024-07-12T16:18:53.048"} +] +``` + +### NDJSON Format + +When the request's Content-Type is `application/x-ndjson`, each line is treated as a separate standard JSON object. + +```json +{"message": "hello world", "time": "2024-07-12T16:18:53.048"} +{"message": "hello greptime", "time": "2024-07-12T16:18:53.048"} +``` + +### Plain Text Format + +When the request's Content-Type is `text/plain`, each line is treated as a separate object. The entire line is treated as a string and stored in a map object containing only the `message` field. + +``` +hello world 2024-07-12T16:18:53.048 +hello greptime 2024-07-12T16:18:53.048 +``` + +The above plain text data will be converted to the following equivalent form: + +```json +{"message": "hello world 2024-07-12T16:18:53.048"} +{"message": "hello greptime 2024-07-12T16:18:53.048"} +``` + +In other words, when the input is in plain text format, you need to use `message` to refer to the content of each line when writing `Processor` and `Transform` configurations. + +## Pipeline Configuration Structure + +Pipeline consists of four parts: Processors, Dispatcher, Transform, and Table suffix. +Processors pre-process input log data. +Dispatcher forwards pipeline execution context onto different subsequent pipeline. +Transform decides the final datatype and table structure in the database. +Table suffix allows storing the data into different tables. + +- Version is used to state the pipeline configuration format. Although it's optional, it's high recommended to start with version 2. See [here](#transform-in-version-2) for more details. +- Processors are used for preprocessing log data, such as parsing time fields and replacing fields. +- Dispatcher(optional) is used for forwarding the context into another pipeline, so that the same batch of input data can be divided and processed by different pipeline based on certain fields. +- Transform(optional) is used for converting data formats, such as converting string types to numeric types, and specifying indexes. +- Table suffix(optional) is used for storing data into different table for later convenience. + +Here is an example of a simple configuration that includes Processors and Transform: + +```yaml +version: 2 +processors: + - urlencoding: + fields: + - string_field_a + - string_field_b + method: decode + ignore_missing: true +dispatcher: + field: type + rules: + - value: http + table_suffix: http + pipeline: http + - value: db + table_suffix: db +transform: + - fields: + - string_field_a + - string_field_b + type: string + # The written data must include the timestamp field + - fields: + - reqTimeSec, req_time_sec + # epoch is a special field type and must specify precision + type: epoch, ms + index: timestamp +table_suffix: _${string_field_a} +``` + +Starting from `v0.15`, the GreptimeDB introduce a version `2` format. +The main change is the transform process. +Refer to [the following documentation](#transform-in-version-2) for detailed changes. + +## Processor + +The Processor is used for preprocessing log data, and its configuration is located under the `processors` section in the YAML file. The Pipeline processes data by applying multiple Processors in sequential order, where each Processor depends on the result of the previous Processor. A Processor consists of a name and multiple configurations, and different types of Processors have different fields in their configuration. + +We currently provide the following built-in Processors: + +- `date`: parses formatted time string fields, such as `2024-07-12T16:18:53.048`. +- `epoch`: parses numeric timestamp fields, such as `1720772378893`. +- `dissect`: splits log data fields. +- `gsub`: replaces log data fields. +- `join`: merges array-type fields in logs. +- `letter`: converts log data fields to letters. +- `regex`: performs regular expression matching on log data fields. +- `urlencoding`: performs URL encoding/decoding on log data fields. +- `csv`: parses CSV data fields in logs. +- `json_path`: extracts fields from JSON data. (**deprecated**, please use `vrl` instead) +- `json_parse`: parse a field into JSON object. +- `simple_extract`: extracts fields from JSON data using simple key. +- `digest`: extracts the template from a log message by removing variable content. +- `select`: retain(include) or exclude fields from the pipeline context. +- `vrl`: runs the [vrl](https://vector.dev/docs/reference/vrl/) script against the pipeline context. +- `filter`: filter out lines if the condition check is meet. + +### Input and output of Processors + +Most processors accept a `field` or `fields` parameter, which is a list of fields processed sequentially, as input data. +Processors produce one or more output based on the input. +For processors that produce a single output, the result will overwrite the original input key in the context. + +In the following example, after the `letter` processor, an upper-case version of the original string is saved back to the `message` field. +```yaml +processors: + - letter: + fields: + - message + method: upper +``` + +We can save the output data to another field, leaving the original field unchanged. +In the following example, we still use the `message` field as the input of the `letter` processor, but saving the output to a new field named `upper_message`. +```yaml +processors: + - letter: + fields: + - key: message + rename_to: upper_message + method: upper +``` + +This renaming syntax also has a shortcut form: simply separate the two field names with a `,`. +Here is an example of this shortcut: +```yaml +processors: + - letter: + fields: + - message, upper_message + method: upper +``` + +There are mainly two reasons why renaming is needed: +1. Leaving the original field unchanged, so it can be reused in more than one processors, or be saved into the database as well. +2. Unifying naming. For example rename camel-case names to snake-case names for consistency. + +### `date` + +The `date` processor is used to parse time fields. Here's an example configuration: + +```yaml +processors: + - date: + fields: + - time + formats: + - '%Y-%m-%d %H:%M:%S%.3f' + ignore_missing: true + timezone: 'Asia/Shanghai' +``` + +In the above example, the configuration of the `date` processor includes the following fields: + +- `fields`: A list of time field names to be parsed. +- `formats`: Time format strings, supporting multiple format strings. Parsing is attempted in the order provided until successful. You can find reference [here](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) for formatting syntax. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. +- `timezone`: Time zone. Use the time zone identifiers from the [tz_database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) to specify the time zone. Defaults to `UTC`. + +### `epoch` + +The `epoch` processor is used to parse timestamp fields. Here's an example configuration: + +```yaml +processors: + - epoch: + fields: + - reqTimeSec + resolution: millisecond + ignore_missing: true +``` + +In the above example, the configuration of the `epoch` processor includes the following fields: + +- `fields`: A list of timestamp field names to be parsed. +- `resolution`: Timestamp precision, supports `s`, `sec`, `second`, `ms`, `millisecond`, `milli`, `us`, `microsecond`, `micro`, `ns`, `nanosecond`, `nano`. Defaults to `ms`. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. + +### `dissect` + +The `dissect` processor is used to split log data fields. Here's an example configuration: + +```yaml +processors: + - dissect: + fields: + - message + patterns: + - '%{key1} %{key2}' + ignore_missing: true + append_separator: '-' +``` + +In the above example, the configuration of the `dissect` processor includes the following fields: + +- `fields`: A list of field names to be split, does not support field renaming. +- `patterns`: The dissect pattern for splitting. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. +- `append_separator`: Specifies the separator for concatenating multiple fields with same field name together. Defaults to an empty string. See `+` modifier below. + +#### Dissect pattern + +Similar to Logstash's dissect pattern, the dissect pattern consists of `%{key}`, where `%{key}` is a field name. For example: + +``` +"%{key1} %{key2} %{+key3} %{+key4/2} %{key5->} %{?key6}" +``` + +#### Dissect modifiers + +The dissect pattern supports the following modifiers: + +| Modifier | Description | Example | +| ------------ | ------------------------------------------------------ | --------------------- | +| `+` | Concatenates two or more fields together | `%{+key} %{+key}` | +| `+` and `/n` | Concatenates two or more fields in the specified order | `%{+key/2} %{+key/1}` | +| `->` | Ignores any repeating characters on the right side | `%{key1->} %{key2->}` | +| `?` | Ignores matching values | `%{?key}` | + +#### `dissect` examples + +For example, given the following log data: + +``` +"key1 key2 key3 key4 key5 key6" +``` + +Using the following Dissect pattern: + +``` +"%{key1} %{key2} %{+key3} %{+key3/2} %{key5->} %{?key6}" +``` + +The result will be: + +``` +{ + "key1": "key1", + "key2": "key2", + "key3": "key3 key4", + "key5": "key5" +} +``` + +### `gsub` + +The `gsub` processor is used to replace values in log data fields. Here's an example configuration: + +```yaml +processors: + - gsub: + fields: + - message + pattern: 'old' + replacement: 'new' + ignore_missing: true +``` + +In the above example, the configuration of the `gsub` processor includes the following fields: + +- `fields`: A list of field names to be replaced. +- `pattern`: The string to be replaced. Supports regular expressions. +- `replacement`: The string to replace with. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. + +### `join` + +The `join` processor is used to merge Array-type fields in log data. Here's an example configuration: + +```yaml +processors: + - join: + fields: + - message + separator: ',' + ignore_missing: true +``` + +In the above example, the configuration of the `join` processor includes the following fields: + +- `fields`: A list of field names to be merged. Note that all the fields mentioned are already of array type. Each field will have its own array merged separately. The content of multiple fields will not be combined. +- `separator`: The separator for the merged result. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. + +#### `join` example + +For example, given the following log data: + +```json +{ + "message": ["a", "b", "c"] +} +``` + +Using the following configuration: + +```yaml +processors: + - join: + fields: + - message + separator: ',' +``` + +The result will be: + +```json +{ + "message": "a,b,c" +} +``` + +### `letter` + +The `letter` processor is used to convert the case of characters in log data fields. Here's an example configuration: + +```yaml +processors: + - letter: + fields: + - message + method: upper + ignore_missing: true +``` + +In the above example, the configuration of the `letter` processor includes the following fields: + +- `fields`: A list of field names to be transformed. +- `method`: The transformation method, supports `upper`, `lower`, `capital`. Defaults to `lower`. Note the `capital` only changes the first letter to uppercase. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. + +### `regex` + +The `regex` processor is used to perform regular expression matching on log data fields. Here's an example configuration: + +```yaml +processors: + - regex: + fields: + - message + patterns: + - ':(?[0-9])' + ignore_missing: true +``` + +In the above example, the configuration of the `regex` processor includes the following fields: + +- `fields`: A list of field names to be matched. If you rename the field, the renamed fields will be combined with the capture groups in `patterns` to generate the result name. +- `pattern`: The regular expression pattern to match. Named capture groups are required to extract corresponding data from the respective field. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. + +#### Rules for named capture groups in regex + +The `regex` processor supports the syntax `(?...)` to define named capture groups. The data will be processed into the following format: + +```json +{ + "_": "" +} +``` + +For example, if the field name specified in the `regex` processor is `message`, and the corresponding content is `"[ERROR] error message"`, you can set the pattern as `\[(?[A-Z]+)\] (?.+)`, and the data will be processed as: + +```json +{ + "message_level": "ERROR", + "message_content": "error message" +} +``` + +### `urlencoding` + +The `urlencoding` processor is used to perform URL encoding on log data fields. Here's an example configuration: + +```yaml +processors: + - urlencoding: + fields: + - string_field_a + - string_field_b + method: decode + ignore_missing: true +``` + +In the above example, the configuration of the `urlencoding` processor includes the following fields: + +- `fields`: A list of field names to be encoded. +- `method`: The encoding method, supports `encode`, `decode`. Defaults to `encode`. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. + +### `csv` + +The `csv` processor is used to parse CSV-type fields in log data that do not have a header. Here's an example configuration: + +```yaml +processors: + - csv: + fields: + - message + separator: ',' + quote: '"' + trim: true + ignore_missing: true +``` + +In the above example, the configuration of the `csv` processor includes the following fields: + +- `fields`: A list of field names to be parsed. +- `separator`: The separator. +- `quote`: The quotation mark. +- `trim`: Whether to trim whitespace. Defaults to `false`. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. + +### `json_path` (deprecated) + +:::danger Deprecated Feature +With the addition of the vrl processor, the use cases for the `json_path` processor have been greatly reduced. +If you need to extract fields from JSON data, it is recommended to use the `vrl` processor for more flexible processing. +We plan to deprecate the `json_path` processor in future versions. +::: + +The `json_path` processor is used to extract fields from JSON data. Here's an example configuration: + +```yaml +processors: + - json_path: + fields: + - complex_object + json_path: "$.shop.orders[?(@.active)].id" + ignore_missing: true + result_index: 1 +``` + +In the above example, the configuration of the `json_path` processor includes the following fields: + +- `fields`: A list of field names to be extracted. +- `json_path`: The JSON path to extract. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. +- `result_index`: Specifies the index of the value in the extracted array to be used as the result value. By default, all values are included. The extracted value of the processor is an array containing all the values of the path. If an index is specified, the corresponding value in the extracted array will be used as the final result. + +#### JSON path syntax + +The JSON path syntax is based on the [jsonpath-rust](https://github.com/besok/jsonpath-rust) library. + +At this stage we only recommend using some simple field extraction operations to facilitate the extraction of nested fields to the top level. + +#### `json_path` example + +For example, given the following log data: + +```json +{ + "product_object": { + "hello": "world" + }, + "product_array": [ + "hello", + "world" + ], + "complex_object": { + "shop": { + "orders": [ + { + "id": 1, + "active": true + }, + { + "id": 2 + }, + { + "id": 3 + }, + { + "id": 4, + "active": true + } + ] + } + } +} +``` + +Using the following configuration: + +```yaml +processors: + - json_path: + fields: + - product_object, object_target + json_path: "$.hello" + result_index: 0 + - json_path: + fields: + - product_array, array_target + json_path: "$.[1]" + result_index: 0 + - json_path: + fields: + - complex_object, complex_target_1 + json_path: "$.shop.orders[?(@.active)].id" + - json_path: + fields: + - complex_target_1, complex_target_2 + json_path: "$.[1]" + result_index: 0 + - json_path: + fields: + - complex_object, complex_target_3 + json_path: "$.shop.orders[?(@.active)].id" + result_index: 1 +transform: + - fields: + - object_target + - array_target + type: string + - fields: + - complex_target_3 + - complex_target_2 + type: uint32 + - fields: + - complex_target_1 + type: json +``` + +The result will be: + +```json +{ + "object_target": "world", + "array_target": "world", + "complex_target_3": 4, + "complex_target_2": 4, + "complex_target_1": [1, 4] +} +``` + +### `json_parse` + +`json_parse`, as its name suggests, parses a string field into a JSON object. Here's an example configuration: + +```yaml +processors: + - json_parse: + fields: + - complex_object, target_field + ignore_missing: true +``` + +In the above example, the configuration of the `json_parse` processor includes the following fields: + +- `fields`: For each field, the first key represents the entry string in the context, the second key represents the output key name. If the second key is not present, it uses the first key as the output key name too, which means in-place replacement of the original value. The example above means parsing `complex_object` and put the output into `target_field`. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. + +#### `json_parse` example + +For example, given the following log data: + +```json +{ + "product_object": "{\"hello\":\"world\"}", +} +``` + +Using the following configuration: + +```yaml +processors: + - json_parse: + fields: + - product_object +``` + +The result will be: + +```json +{ + "product_object": { + "hello": "world" + } +} +``` + +### `simple_extract` + +While `json_path` processor is capable of extracting fields from JSON objects using complex expressions, it's relatively slow and costly. The `simple_extract` processor offers a simple way to extract fields by using just key names. Here's an example configuration: + +```yaml +processors: + - simple_extract: + fields: + - complex_object, target_field + key: "shop.name" + ignore_missing: true +``` + +In the above example, the configuration of the `simple_extract` processor includes the following fields: + +- `fields`: For each field, the first key represents the entry JSON object in the context, the second key represents the output key name. The example above means extracting from `complex_object` and put the output into `target_field`. +- `key`: The extracting key, using `x.x` format, each `.` represents a new nested layer. +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. + +#### `simple_extract` example + +For example, given the following log data: + +```json +{ + "product_object": { + "hello": "world" + }, + "product_array": [ + "hello", + "world" + ], + "complex_object": { + "shop": { + "name": "some_shop_name" + } + } +} +``` + +Using the following configuration: + +```yaml +processors: + - simple_extract: + fields: + - complex_object, shop_name + key: "shop.name" +transform: + - fields: + - shop_name + type: string +``` + +The result will be: + +```json +{ + "shop_name": "some_shop_name" +} +``` + +### `digest` + +The `digest` processor is used to extract the template from a log message by removing variable content, such as numbers, UUIDs, IP addresses, quoted strings, and bracketed text. The digested result can be useful for log template grouping and analysis. Here's an example configuration: + +```yaml +processors: + - digest: + fields: + - message + presets: + - numbers + - uuid + - ip + - quoted + - bracketed + regex: + - "foobar" + ignore_missing: true +``` + +In the above example, the configuration of the `digest` processor includes the following fields: + +- `fields`: A list of field names to be digested. The digested result will be stored in a new field with suffix `_digest`. +- `presets`: A list of preset patterns to remove. The following patterns are supported: + - `numbers`: Matches numeric sequences + - `uuid`: Matches UUID strings like `123e4567-e89b-12d3-a456-426614174000` + - `ip`: Matches IPv4/IPv6 addresses with optional port numbers + - `quoted`: Matches text within single/double quotes (including various Unicode quotes) + - `bracketed`: Matches text within various types of brackets (including various Unicode brackets) +- `regex`: A list of custom regex patterns to remove +- `ignore_missing`: Ignores the case when the field is missing. Defaults to `false`. If the field is missing and this configuration is set to `false`, an exception will be thrown. + +#### `digest` example + +For example, given the following log data: + +```json +{ + "message": "User 'john.doe' from [192.168.1.1] accessed resource 12345 with UUID 123e4567-e89b-12d3-a456-426614174000" +} +``` + +Using the following configuration: + +```yaml +processors: + - digest: + fields: + - message + presets: + - numbers + - uuid + - ip + - quoted + - bracketed +``` + +The result will be: + +```json +{ + "message": "User 'john.doe' from [192.168.1.1] accessed resource 12345 with UUID 123e4567-e89b-12d3-a456-426614174000", + "message_digest": "User from accessed resource with UUID " +} +``` + +The digested template can be used to group similar log messages together or analyze log patterns, even when the variable content differs. For example, all these log messages would generate the same template: + +- `User 'alice' from [10.0.0.1] accessed resource 54321 with UUID 987fbc97-4bed-5078-9141-2791ba07c9f3` +- `User 'bob' from [2001:0db8::1] accessed resource 98765 with UUID 550e8400-e29b-41d4-a716-446655440000` + +### `select` + +The `select` processor is used to retain or exclude fields from the pipeline execution context. + +Starting from `v0.15` release, we are introducing [`auto-transform`](#auto-transform) for simplicity. +The `auto-transform` mode will try to preserve all fields from the pipeline execution context. +The `select` processor can be used here to select fields to include or exclude, which will reflects the final table schema if `auto-transform` is used. + +The configuration options for `select` is simple: +- `type`(optional) + - `include`(default): only keeps the selected fields + - `exclude`: removes the selected fields from the current context +- `fields`: fields selected from the pipeline execution context + +Here is an example: +```YAML +processors: + - dissect: + fields: + - message + patterns: + - "%{+ts} %{+ts} %{http_status_code} %{content}" + - date: + fields: + - ts + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + - select: + fields: + - http_status_code + - ts +``` + +With `dissect` and `date` processor, there are four fields in the context: `ts`, `http_status_code`, `content` and the original `message`. +Without the `select` processor, all four fields are preserved. +The `select` processor here selects `http_status_code` and `ts` fields to include (by default), which effectively removes `content` and `message` in the pipeline execution context, resulting the `http_status_code` and `ts` to be preserved into the database. + +The above example can also be done in the following `select` processor's configuration: +```YAML + - select: + type: exclude + fields: + - content + - message +``` + +### `vrl` + +:::warning Experimental Feature +This experimental feature may contain unexpected behavior, have its functionality change in the future. +::: + +The `vrl` processor run the vrl programming script against the pipeline context. +It's more powerful than simple processors, for it allows you to write actual programming codes to manipulate the context; however, it also costs more resource to execute. +Refer to the [official website](https://vector.dev/docs/reference/vrl/) for more language introduction and usage. + +The `vrl` processor only takes one configuration, that is the `source` field. Here's an example: +```YAML +processors: + - date: + field: time + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + ignore_missing: true + - vrl: + source: | + .from_source = "channel_2" + cond, err = .id1 > .id2 + if (cond) { + .from_source = "channel_1" + } + del(.id1) + del(.id2) + . +``` + +The configuration uses a `|` to start a multi-line content in the YAML file. +The whole script is then written below. + +Some notes regarding the `vrl` processor: +1. The script have to end with a newline of `.`, indicating returning the whole context as the returning value of the script. +2. The returning value of the vrl script should not contain any regex-type variables. They can be used in the script, but have to be `del`ed before returning. +3. Due to type conversion between pipeline's value type and vrl's, the value type that comes out of the vrl script will be the ones with max capacity, meaning `i64`, `f64`, and `Timestamp::nanoseconds`. + +You can use `vrl` processor to set [table options](./write-log-api.md#set-table-options) while writing logs. + +### `filter` + +The `filter` processor can filter out unneeded lines when the condition is meet. + +Here is a simple example of the `filter` processor: +```YAML +processors: + - date: + field: time + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + - filter: + field: name + mode: simple + match_op: in + case_insensitive: true + targets: + - John + - Wick +transform: + - field: name + type: string + - field: time + type: time + index: timestamp +``` +The `filter` processor is configured to check the `name` variable's value from the pipeline context. +If the value of `name` is found within the target list `['John', 'Wick']`, the input line is considered a match and will be discarded, preventing it from being written to the database. + +The `filter` processor takes the following options: +1. `field`(or `fields`): the variable that is used for checking; it can be a list of variables, any match will do the filter. +2. `mode`(optional): default to `simple`, which means simple string matching. This field is here for future extension. +3. `match_op`(optional): if the mode is `simple`, this option can be `in` or `not_in`, which means if the target list contains the input value. Default to `in`. +4. `case_insensitive`(optional): default to `true`. +5. `targets`: the target string lists that are compared against the variable. + +## Transform + +Transform is used to convert data formats and specify indexes upon columns. It is located under the `transform` section in the YAML file. + +Starting from `v0.15`, GreptimeDB is introducing version 2 format and auto-transform to largely simplify the configuration. See below for details. + +A Transform consists of one or more configurations, and each configuration contains the following fields: + +- `fields`: A list of field names to be transformed. +- `type`: The target transformation type in the database. +- `index`(optional): The index type. +- `tag`(optional): Specify the field to be a tag field. +- `on_failure`(optional): Handling method for transformation failures. +- `default`(optional): Default value. + +### Transform in version 2 + +Originally, you have to manually specify all the fields in the transform section for them to be persisted in the database. +If a field is not specify in the transform, it will be discards. +With the number of field growing, this can make the configuration both tedious and error-prone. + +Starting from `v0.15`, GreptimeDB introduces a new transform mode which make it easier to write pipeline configuration. +You only set necessary fields in the transform section, specifying particular datatype and index for them; the rest of the fields from the pipeline context are set automatically by the pipeline engine. +With the `select` processor, you can decide what field is wanted and what isn't in the final table. + +However, this is a breaking change to the existing pipeline configuration files. +If you has already used pipeline with `dissect` or `regex` processors, after upgrading the database, the original message string, which is still in the pipeline context, gets immediately inserted into the database and there's no way to stop this behavior. + +Therefore, GreptimeDB introduces the concept of version to decide which transform mode you want to use, just like the version in a Docker Compose file. Here is an example: +```YAML +version: 2 +processors: + - date: + field: input_str + formats: + - "%Y-%m-%dT%H:%M:%S%.3fZ" + +transform: + - field: input_str, ts + type: time, ms + index: timestamp +``` + +Simply add a `version: 2` line at the top of the config file, and the pipeline engine will run the transform in combined mode: +1. Process all written transform rules sequentially. +2. Write all fields of the pipeline context to the final table. + +Note: +- The transform section **must contains one timestamp index field**. +- The transform process in the version 2 will consume the original field in the pipeline context, so you can't transform the same field twice. + +### Auto-transform + +The transform configuration in version 2 format is already a large simplification over the original transform. +However, there are times when you might want to combine the power of processors with the ease of using `greptime_identity`, writing no transform code, letting the pipeline engine auto infer and persist the data. + +Now it is possible in custom pipelines. +If no transform section is specified, the pipeline engine will attempt to infer the datatype of the fields from the pipeline context and preserve them into the database, much like what the `identity_pipeline` does. + +To create a table in GreptimeDB, a timestamp index column must be specified. +In this case, the pipeline engine will try to find a field of type `timestamp` in the context and set it as the time index column. +A `timestamp` field is produced by a `date` or `epoch` processor, so at least one `date` or `epoch` processor must be defined in the processor's section. +Additionally, only one `timestamp` field is allowed, multiple `timestamp` fields would lead to an error due to ambiguity. + +For example, the following pipeline configuration is now valid. +```YAML +version: 2 +processors: + - dissect: + fields: + - message + patterns: + - '%{ip_address} - %{username} [%{timestamp}] "%{http_method} %{request_line} %{protocol}" %{status_code} %{response_size}' + ignore_missing: true + - date: + fields: + - timestamp + formats: + - "%d/%b/%Y:%H:%M:%S %z" +``` + +And it result to the following table schema: +``` +mysql> desc auto_trans; ++---------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++---------------+---------------------+------+------+---------+---------------+ +| timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| host | String | | YES | | FIELD | +| http_method | String | | YES | | FIELD | +| ip_address | String | | YES | | FIELD | +| message | String | | YES | | FIELD | +| protocol | String | | YES | | FIELD | +| request_line | String | | YES | | FIELD | +| response_size | String | | YES | | FIELD | +| service | String | | YES | | FIELD | +| source_type | String | | YES | | FIELD | +| status_code | String | | YES | | FIELD | +| username | String | | YES | | FIELD | ++---------------+---------------------+------+------+---------+---------------+ +12 rows in set (0.03 sec) +``` + +We can see that all fields are preserved, including the original `message` field. +Note that all fields are saved as `String` type, and the `timestamp` field is automatically set as the time index. + +### The `fields` field + +Each field name is a string. +`fields` in transform can also use renaming, refer to the docs [here](#input-and-output-of-processors). +The final name of the field will be used as the column name in the database table. + +### The `type` field + +GreptimeDB currently provides the following built-in transformation types: + +- `int8`, `int16`, `int32`, `int64`: Integer types. +- `uint8`, `uint16`, `uint32`, `uint64`: Unsigned integer types. +- `float32`, `float64`: Floating-point types. +- `string`: String type. +- `time`: Time type, which will be converted to GreptimeDB `timestamp(9)` type. +- `epoch`: Timestamp type, which will be converted to GreptimeDB `timestamp(n)` type. The value of `n` depends on the precision of the epoch. When the precision is `s`, `n` is 0; when the precision is `ms`, `n` is 3; when the precision is `us`, `n` is 6; when the precision is `ns`, `n` is 9. + +If a field obtains an illegal value during the transformation process, the Pipeline will throw an exception. For example, when converting a string `abc` to an integer, an exception will be thrown because the string is not a valid integer. + +### The `index` field + +The `Pipeline` will write the processed data to the automatically created table in GreptimeDB. To improve query efficiency, GreptimeDB creates indexes for certain columns in the table. The `index` field is used to specify which fields need to be indexed. For information about GreptimeDB index types, please refer to the [Data Index](/user-guide/manage-data/data-index.md) documentation. + +GreptimeDB supports the following four types of index for fields: + +- `timestamp`: Specifies a column as a timestamp index column. +- `inverted`: Specifies a column to use the inverted index type. +- `fulltext`: Specifies a column to use the fulltext index type. The column must be of string type. +- `skipping`: Specifies a column to use the skipping index type. The column must be of string type. + +When `index` field is not provided, GreptimeDB doesn't create index on the column. + +In GreptimeDB, a table must include exact one column of type `timestamp` as the time index column. Therefore, a Pipeline can have only one time index column. + +#### The Timestamp column + +Specify which field is the timestamp index column using `index: timestamp`. Refer to the [Transform Example](#transform-example) below for syntax. + +#### The Inverted Index + +Specify which field uses the inverted index. Refer to the [Transform Example](#transform-example) below for syntax. + +#### The Fulltext Index + +Specify which field will be used for full-text search using `index: fulltext`. This index greatly improves the performance of [log search](/user-guide/logs/fulltext-search.md). Refer to the [Transform Example](#transform-example) below for syntax. + +#### The Skipping Index + +Specify which field uses the skipping index. This index speeds up the query on high cardinality fields but consumes far less storage for building index files. Refer to the [Transform Example](#transform-example) below for syntax. + +### The `tag` field + +The `Pipeline` can also specify a tag field manually. For information about tag field, please refer to the [Data Model](/user-guide/concepts/data-model.md) documentation. Refer to the [Transform Example](#transform-example) below for syntax. + +### The `on_failure` field + +The `on_failure` field is used to specify the handling method when a transformation fails. It supports the following methods: + +- `ignore`: Ignore the failed field and do not write it to the database. +- `default`: Write the default value. The default value is specified by the `default` field. + +### The `default` field + +The `default` field is used to specify the default value when a transformation fails. + +### Transform Example + +For example, with the following log data: + +```json +{ + "num_field_a": "3", + "string_field_a": "john", + "string_field_b": "It was snowing when he was born.", + "time_field_a": 1625760000 +} +``` + +Using the following configuration: + +```yaml +transform: + - fields: + - string_field_a, name + type: string + index: skipping + tag: true + - fields: + - num_field_a, age + type: int32 + index: inverted + - fields: + - string_field_b, description + type: string + index: fulltext + - fields: + - time_field_a, born_time + type: epoch, s + index: timestamp +``` + +The result will be: + +``` +{ + "name": "john", + "age": 3, + "description": "It was snowing when he was born.", + "born_time": 2021-07-08 16:00:00 +} +``` + +## Dispatcher + +The pipeline dispatcher routes requests to other pipelines based on configured +field values. It is useful when multiple log types share a single source and +need to be stored in separate tables with different structures. + +A sample configuration is like: + +```yaml +dispatcher: + field: type + rules: + - value: http + table_suffix: http + pipeline: http + - value: db + table_suffix: db + +``` + +The dispatcher runs after processors and before transformations. It routes data +to the next pipeline, where the defined processors will execute. + +You can specify a `field` and `rules` for routing. If the field value matches a +rule's `value`, the data is routed to the specified `pipeline`. If no pipeline +is defined, the current data structure is used as the table structure. In the +example configuration above, if the `type` of input data is `http`, we will call +`http` as next pipeline. And if `type` is `db`, we use current data structure to +store the data. + +The target table name is determined by `table_suffix`, appended to the current +`table` and an underscore `_`. For example, if the table is `applogs` and it +matches the `http` rule, data is stored in `applogs_http`. + +If no rules match, data is transformed by the current pipeline's +transformations. + +## Table suffix + +:::warning Experimental Feature +This experimental feature may contain unexpected behavior, have its functionality change in the future. +::: + +There are cases where you want to split and insert log data into different target table +based on some certain values of input data. For example, if you want to divide and store the log data +based on the application where the log is produced, thus adding an app name suffix to the target table. + +A sample configuration is like: +```yaml +table_suffix: _${app_name} +``` + +The syntax is simple: use `${}` to include the variable in the pipeline execution context. +The variable can be directly from the input data or a product of former process. +After the table suffix is formatted, the whole string will be added to the input table name. + +Note: +1. The variable must be an integer number or a string type of data. +2. If any error occurs in runtime(e.g: the variable is missing or not a valid type), the input table +name will be used. + +Here is an example of how it works. The input data is like following: +```JSON +[ + {"type": "db"}, + {"type": "http"}, + {"t": "test"} +] +``` + +The input table name is `persist_app`, and the pipeline config is like +```YAML +table_suffix: _${type} +``` + +These three lines of input log will be inserted into three tables: +1. `persist_app_db` +2. `persist_app_http` +3. `persist_app`, for it doesn't have a `type` field, thus the default table name will be used. diff --git a/versioned_docs/version-1.0/reference/pipeline/write-log-api.md b/versioned_docs/version-1.0/reference/pipeline/write-log-api.md new file mode 100644 index 0000000000..04f22faadc --- /dev/null +++ b/versioned_docs/version-1.0/reference/pipeline/write-log-api.md @@ -0,0 +1,160 @@ +--- +keywords: [write logs, HTTP interface, log formats, request parameters, JSON logs] +description: Describes how to write logs to GreptimeDB using a pipeline via the HTTP interface, including supported formats and request parameters. +--- + +# APIs for Writing Logs + +Before writing logs, please read the [Pipeline Configuration](/user-guide/logs/use-custom-pipelines.md#upload-pipeline) to complete the configuration setup and upload. + +## HTTP API + +You can use the following command to write logs via the HTTP interface: + +```shell +curl -X "POST" "http://localhost:4000/v1/ingest?db=&table=&pipeline_name=&version=&skip_error=" \ + -H "Content-Type: application/x-ndjson" \ + -H "Authorization: Basic {{authentication}}" \ + -d "$" +``` + +### Request parameters + +This interface accepts the following parameters: + +- `db`: The name of the database. +- `table`: The name of the table. +- `pipeline_name`: The name of the [pipeline](./pipeline-config.md). +- `version`: The version of the pipeline. Optional, default use the latest one. +- `skip_error`: Whether to skip errors when writing logs. Optional, defaults to `false`. When set to `true`, GreptimeDB will skip individual log entries that encounter errors and continue processing the remaining logs. This prevents the entire request from failing due to a single problematic log entry. + +### `Content-Type` and body format + +GreptimeDB uses `Content-Type` header to decide how to decode the payload body. Currently the following two format is supported: +- `application/json`: this includes normal JSON format and NDJSON format. +- `application/x-ndjson`: specifically uses NDJSON format, which will try to split lines and parse for more accurate error checking. +- `text/plain`: multiple log lines separated by line breaks. + +#### `application/json` and `application/x-ndjson` format + +Here is an example of JSON format body payload + +```JSON +[ + {"message":"127.0.0.1 - - [25/May/2024:20:16:37 +0000] \"GET /index.html HTTP/1.1\" 200 612 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\""}, + {"message":"192.168.1.1 - - [25/May/2024:20:17:37 +0000] \"POST /api/login HTTP/1.1\" 200 1784 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36\""}, + {"message":"10.0.0.1 - - [25/May/2024:20:18:37 +0000] \"GET /images/logo.png HTTP/1.1\" 304 0 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0\""}, + {"message":"172.16.0.1 - - [25/May/2024:20:19:37 +0000] \"GET /contact HTTP/1.1\" 404 162 \"-\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1\""} +] +``` + +Note the whole JSON is an array (log lines). Each JSON object represents one line to be processed by Pipeline engine. + +The name of the key in JSON objects, which is `message` here, is used as field name in Pipeline processors. For example: + +```yaml +processors: + - dissect: + fields: + # `message` is the key in JSON object + - message + patterns: + - '%{ip_address} - - [%{timestamp}] "%{http_method} %{request_line}" %{status_code} %{response_size} "-" "%{user_agent}"' + ignore_missing: true + +# rest of the file is ignored +``` + +We can also rewrite the payload into NDJSON format like following: + +```JSON +{"message":"127.0.0.1 - - [25/May/2024:20:16:37 +0000] \"GET /index.html HTTP/1.1\" 200 612 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\""} +{"message":"192.168.1.1 - - [25/May/2024:20:17:37 +0000] \"POST /api/login HTTP/1.1\" 200 1784 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36\""} +{"message":"10.0.0.1 - - [25/May/2024:20:18:37 +0000] \"GET /images/logo.png HTTP/1.1\" 304 0 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0\""} +{"message":"172.16.0.1 - - [25/May/2024:20:19:37 +0000] \"GET /contact HTTP/1.1\" 404 162 \"-\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1\""} +``` + +Note the outer array is eliminated, and lines are separated by line breaks instead of `,`. + +#### `text/plain` format + +Log in plain text format is widely used throughout the ecosystem. GreptimeDB also supports `text/plain` format as log data input, enabling ingesting logs first hand from log producers. + +The equivalent body payload of previous example is like following: + +```plain +127.0.0.1 - - [25/May/2024:20:16:37 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" +192.168.1.1 - - [25/May/2024:20:17:37 +0000] "POST /api/login HTTP/1.1" 200 1784 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36" +10.0.0.1 - - [25/May/2024:20:18:37 +0000] "GET /images/logo.png HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0" +172.16.0.1 - - [25/May/2024:20:19:37 +0000] "GET /contact HTTP/1.1" 404 162 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1" +``` + +Sending log ingestion request to GreptimeDB requires only modifying the `Content-Type` header to be `text/plain`, and you are good to go! + +Please note that, unlike JSON format, where the input data already have key names as field names to be used in Pipeline processors, `text/plain` format just gives the whole line as input to the Pipeline engine. In this case we use `message` as the field name to refer to the input line, for example: + +```yaml +processors: + - dissect: + fields: + # use `message` as the field name + - message + patterns: + - '%{ip_address} - - [%{timestamp}] "%{http_method} %{request_line}" %{status_code} %{response_size} "-" "%{user_agent}"' + ignore_missing: true + +# rest of the file is ignored +``` + +It is recommended to use `dissect` or `regex` processor to split the input line into fields first and then process the fields accordingly. + +## Set Table Options + +The table options need to be set in the pipeline configurations. +Starting from `v0.15`, the pipeline engine recognizes certain variables, and can set corresponding table options based on the value of the variables. +Combined with the `vrl` processor, it's now easy to create and set table options during the pipeline execution based on input data. + +Here is a list of supported common table option variables: +- `greptime_auto_create_table` +- `greptime_ttl` +- `greptime_append_mode` +- `greptime_merge_mode` +- `greptime_physical_table` +- `greptime_skip_wal` + +Please refer to [table options](/reference/sql/create.md#table-options) for the detailed explanation of each option. + +Here are some pipeline specific variables: +- `greptime_table_suffix`: add suffix to the destined table name. + +Let's use the following pipeline file to demonstrate: +```YAML +processors: + - date: + field: time + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + ignore_missing: true + - vrl: + source: | + .greptime_table_suffix, err = "_" + .id + .greptime_table_ttl = "1d" + . +``` + +In the vrl script, we set the table suffix variable with the input field `.id`(leading with an underscore), and set the ttl to `1d`. +Then we run the ingestion using the following JSON data. + +```JSON +{ + "id": "2436", + "time": "2024-05-25 20:16:37.217" +} +``` + +Assuming the given table name being `d_table`, the final table name would be `d_table_2436` as we would expected. +The table is also set with a ttl of 1 day. + +## Examples + +Please refer to the "Writing Logs" section in the [Quick Start](/user-guide/logs/quick-start.md#direct-http-ingestion) and [Using Custom Pipelines](/user-guide/logs/use-custom-pipelines.md#write-logs) guide for examples. diff --git a/versioned_docs/version-1.0/reference/sql-tools.md b/versioned_docs/version-1.0/reference/sql-tools.md new file mode 100644 index 0000000000..c66a8fa647 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql-tools.md @@ -0,0 +1,290 @@ +--- +keywords: [SQL tools, JDBC, GORM, database connection, Java, Go, SQL queries, installation] +description: Guide on using SQL tools with GreptimeDB, including recommended libraries, installation, connection setup, and usage examples for Java and Go. +--- + +# SQL Tools + +GreptimeDB uses SQL as its main query language and supports many popular SQL tools. +This document guides you on how to use SQL tools with GreptimeDB. + +## Language drivers + +It is recommended to use mature SQL drivers to query data. + +### Recommended libraries + + + + Java Database Connectivity (JDBC) is the JavaSoft specification of a standard application programming interface (API) that allows Java programs to access database management systems. + + Many databases, such as MySQL or PostgreSQL, have implemented their own drivers based on the JDBC API. + Since GreptimeDB supports [multiple protocols](/user-guide/protocols/overview.md), we use MySQL as an example to demonstrate how to use JDBC. + If you want to use other protocols, just replace the MySQL driver with the corresponding driver. + + + It is recommended to use the [GORM](https://gorm.io/) library, which is popular and developer-friendly. + + + +### Installation + + + + If you are using [Maven](https://maven.apache.org/), add the following to your `pom.xml` dependencies list: + + ```xml + + mysql + mysql-connector-java + 8.0.33 + + ``` + + + + Use the following command to install the GORM library: + + ```shell + go get -u gorm.io/gorm + ``` + + Then install the MySQL driver: + + ```shell + go get -u gorm.io/driver/mysql + ``` + + Import the libraries in your code: + + ```go + import ( + "gorm.io/gorm" + "gorm.io/driver/mysql" + ) + ``` + + + +### Connect to database + +The following use MySQL as an example to demonstrate how to connect to 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!"); + } + ``` + + You need a properties file to store the DB connection information. Place it in the resources directory and name it `db-connection.properties`. The file content is as follows: + + ```txt + # DataSource + db.database-driver=com.mysql.cj.jdbc.Driver + db.url=jdbc:mysql://localhost:4002/public + db.username= + db.password= + ``` + + Or you can get the file from [here](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 + ``` + + + +#### Time zone + + + + Set the JDBC time zone by setting URL parameters: + + ```txt + jdbc:mysql://127.0.0.1:4002?connectionTimeZone=Asia/Shanghai&forceConnectionTimeZoneToSession=true + ``` + + * `connectionTimeZone={LOCAL|SERVER|user-defined-time-zone}` specifies the connection time zone. + * `forceConnectionTimeZoneToSession=true` sets the session `time_zone` variable to the value specified in `connectionTimeZone`. + + + Set the time zone in the DSN. For example, set the time zone to `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) + ``` + + For more information, see the [MySQL Driver Documentation](https://github.com/go-sql-driver/mysql?tab=readme-ov-file#system-variables). + + + +### Raw SQL + +It is recommended to use raw SQL to experience the full features of GreptimeDB. +The following example shows how to use raw SQL to query data. + + + + ```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")); + } + } + ``` + + For the complete code of the demo, please refer to [here](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"` + } + ``` + + If you are using the [High-level API](/user-guide/ingest-data/for-iot/grpc-sdks/go.md#high-level-api) to insert data, you can declare the model with both GORM and GreptimeDB tags. + + ```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"` + } + ``` + + Declare the table name as follows: + + ```go + func (CpuMetric) TableName() string { + return "cpu_metric" + } + ``` + + Use raw SQL to query data: + + ```go + var cpuMetric CpuMetric + db.Raw("SELECT * FROM cpu_metric LIMIT 10").Scan(&result) + ``` + + + +### Query library reference + +For more information about how to use the query library, please see the documentation of the corresponding library: + + + + - [JDBC Online Tutorials](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) + + + - [GORM](https://gorm.io/docs/index.html) + + + +## Command line tools + +### MySQL + +You can use the `mysql` command line tool to connect to the GreptimeDB. +Please refer to the [MySQL protocol](/user-guide/protocols/mysql.md) document for connection information. + +After you connect to the server, you can use all [GreptimeDB SQL commands](/reference/sql/overview.md) to interact with the database. + +### PostgreSQL + +You can use the `psql` command line tool to connect to the GreptimeDB. +Please refer to the [PostgreSQL protocol](/user-guide/protocols/postgresql.md) document for connection information. + +After you connect to the server, you can use all [GreptimeDB SQL commands](/reference/sql/overview.md) to interact with the database. + +## GreptimeDB Dashboard + +You can run SQL and visualize data in the [GreptimeDB Dashboard](/getting-started/installation/greptimedb-dashboard.md). + +## GUI tools + +### DBeaver + +Please refer to the [DBeaver Integration Guide](/user-guide/integrations/dbeaver.md). + + + +## HTTP API + +You can POST SQL queries to the GreptimeDB HTTP API to query data. +Please refer to the [HTTP API](/user-guide/protocols/http.md) document for more information. diff --git a/versioned_docs/version-1.0/reference/sql/admin.md b/versioned_docs/version-1.0/reference/sql/admin.md new file mode 100644 index 0000000000..9342a49231 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/admin.md @@ -0,0 +1,46 @@ +--- +keywords: [ADMIN statement, SQL, administration functions, flush table, compact table, migrate region] +description: Describes the `ADMIN` statement used to run administration functions, including examples for flushing tables, scheduling compactions, migrating regions, and querying procedure states. +--- + +# ADMIN + +`ADMIN` is used to run administration functions. + +```sql +ADMIN function(arg1, arg2, ...) +``` + + +## Admin Functions + +GreptimeDB provides some administration functions to manage the database and data: + +* `flush_table(table_name)` to flush a table's memtables into SST file by table name. +* `flush_region(region_id)` to flush a region's memtables into SST file by region id. Find the region id through [PARTITIONS](./information-schema/partitions.md) table. +* `compact_table(table_name, [type], [options])` to schedule a compaction task for a table by table name, read [compaction](/user-guide/deployments-administration/manage-data/compaction.md#strict-window-compaction-strategy-swcs-and-manual-compaction) for more details. +* `compact_region(region_id)` to schedule a compaction task for a region by region id. +* `migrate_region(region_id, from_peer, to_peer, [timeout])` to migrate regions between datanodes, please read the [Region Migration](/user-guide/deployments-administration/manage-data/region-migration.md). +* `procedure_state(procedure_id)` to query a procedure state by its id. +* `flush_flow(flow_name)` to flush a flow's output into the sink table. +* `reconcile_table(table_name)` to reconcile the metadata inconsistency of a table, read [table reconciliation](/user-guide/deployments-administration/maintenance/table-reconciliation.md) for more details. +* `reconcile_database(database_name)` to reconcile the metadata inconsistency of all tables in a database, read [table reconciliation](/user-guide/deployments-administration/maintenance/table-reconciliation.md) for more details. +* `reconcile_catalog()` to reconcile the metadata inconsistency of all tables in the entire cluster, read [table reconciliation](/user-guide/deployments-administration/maintenance/table-reconciliation.md) for more details. + +For example: +```sql +-- Flush the table test -- +admin flush_table("test"); + +-- Schedule a compaction for table test with default parallelism (1) -- +admin compact_table("test"); + +-- Schedule a regular compaction with parallelism set to 2 -- +admin compact_table("test", "regular", "parallelism=2"); + +-- Schedule an SWCS compaction with default time window and parallelism set to 2 -- +admin compact_table("test", "swcs", "parallelism=2"); + +-- Schedule an SWCS compaction with custom time window and parallelism -- +admin compact_table("test", "swcs", "window=1800,parallelism=2"); +``` diff --git a/versioned_docs/version-1.0/reference/sql/alter.md b/versioned_docs/version-1.0/reference/sql/alter.md new file mode 100644 index 0000000000..5b1676682e --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/alter.md @@ -0,0 +1,246 @@ +--- +keywords: [ALTER statement, SQL, modify database, modify table, alter column, table options] +description: Describes the `ALTER` statement used to modify database options, table options, or metadata, including syntax and examples for altering databases and tables. +--- + +# ALTER + +`ALTER` can be used to modify any database options, table options or metadata of the table, including: + +* Modify database options +* Add/Drop/Modify a column +* Set/Drop column default values +* Drop column default values +* Rename a table +* Modify table options + +## ALTER DATABASE + +`ALTER DATABASE` statements can be used to modify the options of databases. + +### Syntax + +```sql +ALTER DATABASE db + [SET = [, ...] + | UNSET [, ...] + ] +``` + +Currently following options are supported: +- `ttl`: Specifies the default retention time for data in the database. Data exceeding this retention period will be deleted asynchronously. + - If `ttl` was not previously set, defining a new `ttl` using `ALTER` will result in the deletion of data that exceeds the specified retention time. + - If `ttl` was already set, modifying it via `ALTER` will enforce the updated retention time immediately, removing data that exceeds the new retention threshold. + - If `ttl` was previously set and is unset using `ALTER`, new data will no longer be deleted. However, data that was previously deleted due to the retention policy cannot be restored. + +### Examples + +#### Modify default retention time of data in database + +Change the default retention time of data in the database to 1 day: + +```sql +ALTER DATABASE db SET 'ttl'='1d'; +``` + +Remove the default retention time of data in the database: + +```sql +ALTER DATABASE db UNSET 'ttl'; +``` + +## ALTER TABLE + +### Syntax + +```sql +ALTER TABLE [db.]table + [ADD COLUMN name1 type1 [options], ADD COLUMN name2 type2 [options], ... + | DROP COLUMN name + | MODIFY COLUMN name type + | MODIFY COLUMN name SET DEFAULT value + | MODIFY COLUMN name DROP DEFAULT + | MODIFY COLUMN name SET FULLTEXT INDEX [WITH ] + | MODIFY COLUMN name UNSET FULLTEXT INDEX + | RENAME name + | SET = [, ...] + | UNSET [, ...] + ] +``` + + +### Add column + +Adds a new column to the table: + +```sql +ALTER TABLE monitor ADD COLUMN load_15 double; +``` + +Definition of column is the same as in [CREATE](./create.md). + +Also, we can add multiple columns to the table at the same time: + +```sql +ALTER TABLE monitor ADD COLUMN disk_usage double, ADD COLUMN disk_free double; +``` + +We can set the new column's location. In first position for example: + +```sql +ALTER TABLE monitor ADD COLUMN load_15 double FIRST; +``` + +After an existing column: + +```sql +ALTER TABLE monitor ADD COLUMN load_15 double AFTER memory; +``` + +Adds a new column as a tag(primary key) with a default value: +```sql +ALTER TABLE monitor ADD COLUMN app STRING DEFAULT 'shop' PRIMARY KEY; +``` + +### Remove column + +Removes a column from the table: + +```sql +ALTER TABLE monitor DROP COLUMN load_15; +``` + +The removed column can't be retrieved immediately by all subsequent queries. + +### Modify column type + +Modify the date type of a column + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 STRING; +``` + +The modified column cannot be a tag (primary key) or time index, and it must be nullable to ensure that the data can be safely converted (returns `NULL` on cast failures). + +### Set column default value + +Set a default value for an existing column: + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 SET DEFAULT 0.0; +``` + +Set a string default value: + +```sql +ALTER TABLE monitor MODIFY COLUMN `status` SET DEFAULT 'active'; +``` + +The default value will be used for new rows when no explicit value is provided for the column during insertion. + +Remove the default value from a column: + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 DROP DEFAULT; +``` + +After dropping the default value, the column will use `NULL` as the default. The database only allow dropping defaults for nullable columns. + +### Alter table options + +`ALTER TABLE` statements can also be used to change the options of tables. + +Currently following options are supported: +- `ttl`: the retention time of data in table. +- `compaction.twcs.time_window`: the time window parameter of TWCS compaction strategy. The value should be a [time duration string](/reference/time-durations.md). +- `compaction.twcs.max_output_file_size`: the maximum allowed output file size of TWCS compaction strategy. +- `compaction.twcs.trigger_file_num`: the number of files in a specific time window to trigger a 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.trigger_file_num'='8'; +``` + +### Unset table options + +```sql +ALTER TABLE monitor UNSET 'ttl'; +``` + +### Create an index for a column + +Enable inverted index on a column: + +```sql +ALTER TABLE monitor MODIFY COLUMN host SET INVERTED INDEX; +``` + +Enable fulltext index on a column: + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 SET FULLTEXT INDEX WITH (analyzer = 'Chinese', case_sensitive = 'false', backend = 'bloom', granularity = 1024, false_positive_rate = 0.01); +``` + +You can specify the following options using `FULLTEXT INDEX WITH` when enabling fulltext options: + +- `analyzer`: Sets the language analyzer for the full-text index. Supported values are `English` and `Chinese`. Default is `English`. +- `case_sensitive`: Determines whether the full-text index is case-sensitive. Supported values are `true` and `false`. Default is `false`. +- `backend`: Sets the backend for the full-text index. Supported values are `bloom` and `tantivy`. Default is `bloom`. +- `granularity`: (For `bloom` backend) The size of data chunks covered by each filter. A smaller granularity improves filtering but increases index size. Default is `10240`. +- `false_positive_rate`: (For `bloom` backend) The probability of misidentifying a block. A lower rate improves accuracy (better filtering) but increases index size. Value is a float between `0` and `1`. Default is `0.01`. + +For more information on full-text index configuration and performance comparison, refer to the [Full-Text Index Configuration Guide](/user-guide/manage-data/data-index.md#fulltext-index). + +If `WITH ` is not specified, `FULLTEXT INDEX` will use the default values. + +Enable skipping index on a column: + +```sql +ALTER TABLE monitor MODIFY COLUMN host SET SKIPPING INDEX WITH(granularity = 1024, type = 'BLOOM', false_positive_rate = 0.01); +``` + +The valid options for the skipping index include: +* `type`: The index type, only supports `BLOOM` type right now. +* `granularity`: (For `BLOOM` type) The size of data chunks covered by each filter. A smaller granularity improves filtering but increases index size. Default is `10240`. +* `false_positive_rate`: (For `BLOOM` type) The probability of misidentifying a block. A lower rate improves accuracy (better filtering) but increases index size. Value is a float between `0` and `1`. Default is `0.01`. + +### Remove index on a column + +The syntax is: +```sql +ALTER TABLE [table] MODIFY COLUMN [column] UNSET [INVERTED | SKIPPING | FULLTEXT] INDEX; +``` + +For example, remove the inverted index: +```sql +ALTER TABLE monitor_pk MODIFY COLUMN host UNSET INVERTED INDEX; +``` + +Remove the skipping index: +```sql +ALTER TABLE monitor_pk MODIFY COLUMN host UNSET SKIPPING INDEX; +``` + +Remove the fulltext index: +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 UNSET FULLTEXT INDEX; +``` + +The column must be a string type to alter the fulltext index. + +If the fulltext index has never been enabled, you can enable it and specify the `analyzer` and `case_sensitive` options. When the fulltext index is already enabled on a column, you can disable it but **cannot modify the options, and so does the skipping index**. + +### Rename table + +Renames the table: + +```sql +ALTER TABLE monitor RENAME monitor_new; +``` + +This command only renames the table; it doesn't modify the data within the table. diff --git a/versioned_docs/version-1.0/reference/sql/case.md b/versioned_docs/version-1.0/reference/sql/case.md new file mode 100644 index 0000000000..0a2abe80d0 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/case.md @@ -0,0 +1,96 @@ +--- +keywords: [CASE statement, SQL, conditional logic, query, syntax, examples] +description: Describes the `CASE` statement used for conditional logic within queries, including syntax and examples for usage in `SELECT`, `WHERE`, `GROUP BY`, and `ORDER BY` clauses. +--- + +# CASE + +The `CASE` statement allows you to perform conditional logic within your queries, +similar to an IF-THEN-ELSE structure in programming languages. +It enables you to return specific values based on evaluated conditions, +making data retrieval and manipulation more dynamic. + +## Syntax + +```sql +CASE + WHEN condition1 THEN result1 + WHEN condition2 THEN result2 + ... + ELSE result +END +``` + +- `condition1`, `condition2`, ...: The conditions to evaluate against the expression. +- `result1`, `result2`, ...: The values to return when the corresponding condition is met. +- `result`: The value to return when none of the conditions are met (optional). + + +## Examples + +The `CASE` statement can be used in various clauses, such as `SELECT`, `WHERE`, `ORDER BY` and `GROUP BY`. + +### Use `CASE` in `SELECT` + +In the `SELECT` clause, you can use the `CASE` statement to create new columns based on conditions. +please see [the example](/user-guide/query-data/sql.md#case) in the query data guide. + +You can also use `CASE` with functions like `SUM` to conditionally aggregate data. +for example, you can calculate the total number of logs with status 200 and 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; +``` + +### Use `CASE` in `WHERE` + +In the `WHERE` clause, you can filter rows based on conditions. +For example, the following query retrieves data from the `monitor` table based on the `ts` condition: + +```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; +``` + +### Use `CASE` in `GROUP BY` + +The `CASE` statement can be utilized in the `GROUP BY` clause to categorize data based on specific conditions. For instance, the following query groups data by the `host` column and classifies the `cpu` column into three categories: 'high', 'medium', and '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; +``` + +### Use `CASE` in `ORDER BY` + +According to GreptimeDB's [data model](/user-guide/concepts/data-model.md), +the `Tag` columns are indexed and can be used in the `ORDER BY` clause to enhance query performance. +For instance, if the `status_code` and `http_method` columns in the `nginx_logs` table are `Tag` columns storing string values, +you can utilize the `CASE` statement to sort the data based on these columns as follows: + +```sql +SELECT * +FROM nginx_logs +ORDER BY + CASE + WHEN status_code IS NOT NULL THEN status_code + ELSE http_method + END; +``` + diff --git a/versioned_docs/version-1.0/reference/sql/cast.md b/versioned_docs/version-1.0/reference/sql/cast.md new file mode 100644 index 0000000000..0f3dbf7d5e --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/cast.md @@ -0,0 +1,35 @@ +--- +keywords: [CAST function, SQL, data type conversion, syntax, examples] +description: Describes the `CAST` function used to convert an expression of one data type to another, including syntax and examples. +--- + +# CAST + +`CAST` is used to convert an expression of one data type to another. + +## Syntax + +```sql +CAST (expression AS data_type) +``` + +## Parameters + +- expression: the expression to be converted. +- data_type: the data type to convert the expression to. + +# Examples + + Convert a string to an integer: + +```sql + SELECT CAST('123' AS INT) ; +``` + +```sql ++-------------+ +| Utf8("123") | ++-------------+ +| 123 | ++-------------+ +``` diff --git a/versioned_docs/version-1.0/reference/sql/compatibility.md b/versioned_docs/version-1.0/reference/sql/compatibility.md new file mode 100644 index 0000000000..9e7d19dfcf --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/compatibility.md @@ -0,0 +1,25 @@ +--- +keywords: [ANSI SQL, SQL compatibility, SQL extensions, table creation, data insertion] +description: Describes the subset of ANSI SQL supported by GreptimeDB and its unique extensions, including major incompatibilities and extensions for table creation, data insertion, updates, queries, and deletions. +--- + +# ANSI Compatibility + +GreptimeDB supports a subset of ANSI SQL and has some unique extensions. Some major incompatibilities and extensions are described below: + +1. Create a table: + * Supports the unique `TIME INDEX` constraint. Please refer to the [Data Model](/user-guide/concepts/data-model.md) and the [CREATE](./create.md) table creation syntax for details. + * Currently only supports `PRIMARY KEY` constraints and does not support other types of constraints or foreign keys. + * GreptimeDB is a native distributed database, so the table creation syntax for distributed tables supports partitioning rules. Please also refer to the [CREATE](./create.md). +2. Insert data: Consistent with ANSI SQL syntax, but requires the `TIME INDEX` column value (or default value) to be provided. +3. Update data: Does not support `UPDATE` syntax, but if the primary key and `TIME INDEX` corresponding column values are the same during `INSERT`, subsequent inserted rows will overwrite previously written rows, effectively achieving an update. + * Since 0.8, GreptimeDB supports [append mode](/reference/sql/create.md#create-an-append-only-table) that creates an append-only table with `append_mode="true"` option which keeps duplicate rows. + * GreptimeDB supports [merge mode](/reference/sql/create.md#create-an-append-only-table) that creates a table with `merge_mode="last_non_null"` option which allow updating a field partially. +4. Query data: Query syntax is compatible with ANSI SQL, with some functional differences and omissions. + * Since v0.9.0, begins to support [VIEW](/user-guide/query-data/view.md). + * TQL syntax extension: Supports executing PromQL in SQL via TQL subcommands. Please refer to the [TQL](./tql.md) section for details. + * [Range Query](/reference/sql/range.md#range-query) to query and aggregate data within a range of time. +5. Delete data: Deletion syntax is basically consistent with ANSI SQL. +6. Others: + * Identifiers such as table names and column names have constraints similar to ANSI SQL, are case sensitive, and require double quotes when encountering special characters or uppercase letters. + * GreptimeDB has optimized identifier rules for different dialects. For example, when you connect with a MySQL or PostgreSQL client, you can use identifier rules specific to that SQL dialect, such as using backticks `` ` `` for MySQL and standard double quotes `"` for PostgreSQL. diff --git a/versioned_docs/version-1.0/reference/sql/copy.md b/versioned_docs/version-1.0/reference/sql/copy.md new file mode 100644 index 0000000000..d0cdfa6f69 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/copy.md @@ -0,0 +1,233 @@ +--- +keywords: [copy statement, SQL, export data, import data, file format, cloud storage] +description: Describes the `COPY` statement used to export and import table or database data to and from files, including options for file format, time range, and cloud storage connections. +--- + +# COPY + +## COPY TABLE +### COPY TO + +`COPY TO` is used to export the contents of a table to a file. + +The syntax for using `COPY TO` is as follows: + +```sql +COPY tbl TO '/xxx/xxx/output.parquet' WITH (FORMAT = 'parquet'); +``` + +The command starts with the keyword `COPY`, followed by the name of the table you want to export data from (`tbl` in this case). + +`TO` specifies the file path and name to save the exported +data (`/xxx/xxx/output.parquet` in this case). + +For example, to export data to CSV with custom timestamp and date formats: + +```sql +COPY tbl TO '/path/to/file.csv' WITH ( + FORMAT = 'csv', + TIMESTAMP_FORMAT = '%Y/%m/%d %H:%M:%S', + DATE_FORMAT = '%Y-%m-%d' +); +``` + +#### `WITH` Option + +`WITH` adds options such as the file `FORMAT` which specifies the format of the exported file. In this example, the format is Parquet; it is a columnar storage format used for big data processing. Parquet efficiently compresses and encodes columnar data for big data analytics. + +| Option | Description | Required | +|---|---|---| +| `FORMAT` | Target file(s) format, e.g., JSON, CSV, Parquet | **Required** | +| `START_TIME`/`END_TIME`| The time range within which data should be exported. `START_TIME` is inclusive and `END_TIME` is exclusive. | Optional | +| `TIMESTAMP_FORMAT` | Custom format for timestamp columns when exporting to CSV format. Uses [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) format specifiers (e.g., `'%Y-%m-%d %H:%M:%S'`). Only supported for CSV format. | Optional | +| `DATE_FORMAT` | Custom format for date columns when exporting to CSV format. Uses [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) format specifiers (e.g., `'%Y-%m-%d'`). Only supported for CSV format. | Optional | +| `TIME_FORMAT` | Custom format for time columns when exporting to CSV format. Uses [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) format specifiers (e.g., `'%H:%M:%S'`). Only supported for CSV format. | Optional | + +#### `CONNECTION` Option + +`COPY TO` supports exporting data to cloud storage services like S3. See [connect-to-s3](#connect-to-s3) for more detail. + +### COPY FROM + +`COPY FROM` is used to import data from a file into a table. + +The syntax for using `COPY FROM` is as follows: + +```sql +COPY [.] +FROM { '/[]' } +[ [ WITH ] + ( + [ FORMAT = { 'CSV' | 'JSON' | 'PARQUET' | 'ORC' } ] + [ PATTERN = '' ] + ) +] +[LIMIT NUM] +``` + +The command starts with the keyword `COPY`, followed by the name of the table you want to import data into. + +#### `WITH` Option + +`FORMAT` specifies the file format of the imported file. In this example, the format is Parquet. + +The option `PATTERN` allows the usage of wildcard characters like * to specify multiple input files that +match a certain pattern. For example, you can use the following syntax to import all files in the +directory(which must be an absolute path) "/path/to/folder" with the filename that contains `parquet`: + +```sql +COPY tbl FROM '/path/to/folder/' WITH (FORMAT = 'parquet', PATTERN = '.*parquet.*'); +``` + +Specifically, if you only have one file to import, you can use the following syntax: + +```sql +COPY tbl FROM '/path/to/folder/xxx.parquet' WITH (FORMAT = 'parquet'); +``` + +| Option | Description | Required | +|---|---|---| +| `FORMAT` | Target file(s) format, e.g., JSON, CSV, Parquet, ORC | **Required** | +| `PATTERN` | Use regex to match files. e.g., `*_today.parquet` | Optional | + +:::tip NOTE +The CSV file must have a header row to be imported correctly. The header row should contain the column names of the table. +::: + +#### `CONNECTION` Option + +`COPY FROM` also supports importing data from cloud storage services like S3. See [connect-to-s3](#connect-to-s3) for more detail. + +### Connect to S3 + +You can copy data from/to S3 + +```sql +-- COPY FROM +COPY tbl FROM '' WITH (FORMAT = 'parquet') CONNECTION(REGION = 'us-west-2'); + +-- COPY TO +COPY tbl TO '' WITH (FORMAT = 'parquet') CONNECTION(REGION = 'us-west-2'); +``` + +#### URL + +Notes: You should specify a file using `S3://bucket/key-name`. The following example shows the correct format. + +``` +s3://my-bucket/data.parquet +``` + +Another way is using Virtual-hosted–style(`ENABLE_VIRTUAL_HOST_STYLE` must be set to `true` to enable this). The following example shows the correct format. + +``` +s3://bucket-name.s3.region-code.amazonaws.com/key-name +``` + +:::tip NOTE +You can use `Copy S3 URI` or `COPY URL` on S3 console to get S3 URI/HTTP URL prefix or full path. +::: + +#### Options + +You can set the following **CONNECTION** options: + +| Option | Description | Required | +|---|---|---| +| `REGION` | AWS region name. e.g., `us-west-2` | **Required** | +| `ENDPOINT` | The bucket endpoint. e.g., `s3.us-west-2.amazonaws.com` | Optional | +| `ACCESS_KEY_ID` | ACCESS_KEY_ID Your access key ID for connecting the AWS S3 compatible object storage. | Optional | +| `SECRET_ACCESS_KEY` | Your secret access key for connecting the AWS S3 compatible object storage. | Optional | +| `ENABLE_VIRTUAL_HOST_STYLE` | If you use virtual hosting to address the bucket, set it to "true".| Optional | +| `SESSION_TOKEN` | Your temporary credential for connecting the AWS S3 service. | Optional | + +#### LIMIT + +You can use `LIMIT` to restrict maximum number of rows inserted at once. + +## COPY Query Results + +You can use the `COPY` statement to export the results of a query to a file. The syntax is as follows: + +```sql +COPY () TO '' WITH (FORMAT = { 'CSV' | 'JSON' | 'PARQUET' }); +``` + +| Option | Description | Required | +|---|---|---| +| `QUERY` | The SQL SELECT statement to execute | **Required** | +| `PATH` | The file path where the output will be written | **Required** | +| `FORMAT` | The output file format: 'CSV', 'JSON', or 'PARQUET' | **Required** | +| `TIMESTAMP_FORMAT` | Custom format for timestamp columns when exporting to CSV format. Uses [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) format specifiers. Only supported for CSV format. | Optional | +| `DATE_FORMAT` | Custom format for date columns when exporting to CSV format. Uses [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) format specifiers. Only supported for CSV format. | Optional | +| `TIME_FORMAT` | Custom format for time columns when exporting to CSV format. Uses [strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) format specifiers. Only supported for CSV format. | Optional | + +For example, the following statement exports query results to a CSV file: + +```sql +COPY (SELECT * FROM tbl WHERE host = 'host1') TO '/path/to/file.csv' WITH (FORMAT = 'csv'); +``` + +You can also specify custom date and time formats when exporting to CSV: + +```sql +COPY (SELECT * FROM tbl WHERE host = 'host1') TO '/path/to/file.csv' WITH ( + FORMAT = 'csv', + TIMESTAMP_FORMAT = '%m-%d-%Y %H:%M:%S', + DATE_FORMAT = '%Y/%m/%d' +); +``` + +## COPY DATABASE + +Beside copying specific table to/from some path, `COPY` statement can also be used to copy whole database to/from some path. The syntax for copying databases is: + +```sql +COPY DATABASE + [TO | FROM] '' + WITH ( + FORMAT = { 'CSV' | 'JSON' | 'PARQUET' }, + START_TIME = "", + END_TIME = "" + ) + [CONNECTION( + REGION = "", + ENDPOINT = "", + ACCESS_KEY_ID = "", + SECRET_ACCESS_KEY = "", + ENABLE_VIRTUAL_HOST_STYLE = "[true | false]", + )] +``` + +| Option | Description | Required | +|---|---|---| +| `FORMAT` | Export file format, available options: JSON, CSV, Parquet | **Required** | +| `START_TIME`/`END_TIME`| The time range within which data should be exported. `START_TIME` is inclusive and `END_TIME` is exclusive. | Optional | + +> - When copying databases, `` must end with `/`. +> - `CONNECTION` parameters can also be used to copying databases to/from object storage services like AWS S3. + +### Examples + +```sql +-- Export all tables' data to /tmp/export/ +COPY DATABASE public TO '/tmp/export/' WITH (FORMAT='parquet'); + +-- Export all tables' data within time range 2022-04-11 08:00:00~2022-04-11 09:00:00 to /tmp/export/ +COPY DATABASE public TO '/tmp/export/' WITH (FORMAT='parquet', START_TIME='2022-04-11 08:00:00', END_TIME='2022-04-11 09:00:00'); + +-- Import files under /tmp/export/ directory to database named public. +COPY DATABASE public FROM '/tmp/export/' WITH (FORMAT='parquet'); +``` + +## Special reminder for Windows platforms + +Please notice that when executing `COPY`/`COPY DATABASE` statements on Windows platforms, backslashes (`\`) in paths should be replaced with `/` for compatibility. + +```sql +-- Won't work +COPY tbl TO 'C:\xxx\xxx\output.parquet' WITH (FORMAT = 'parquet'); + +-- Correct path: +COPY tbl TO 'C:/xxx/xxx/output.parquet' WITH (FORMAT = 'parquet'); +``` diff --git a/versioned_docs/version-1.0/reference/sql/create.md b/versioned_docs/version-1.0/reference/sql/create.md new file mode 100644 index 0000000000..2d811111ca --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/create.md @@ -0,0 +1,483 @@ +--- +keywords: [create statement, SQL, create database, create table, create view, create flow] +description: Explains the SQL CREATE statement for creating databases, tables, external tables, flows, and views in GreptimeDB, including syntax, table constraints, options, and examples. +--- + +# CREATE + +`CREATE` is used to create new databases or tables. + +## CREATE DATABASE + +### Syntax + +Creates a new database: + +```sql +CREATE DATABASE [IF NOT EXISTS] db_name [WITH ] +``` + +If the `db_name` database already exists, then GreptimeDB has the following behaviors: + +- Doesn't create a new database. +- Doesn't return an error when the clause `IF NOT EXISTS` is presented. +- Otherwise, returns an error. + +The database can also carry options similar to the `CREATE TABLE` statement by using the `WITH` keyword. The following options are available for databases: + +- `ttl` - Time-To-Live for data in all tables within the database (cannot be set to `instant`) +- `memtable.type` - Type of memtable (`time_series`, `partition_tree`) +- `append_mode` - Whether tables in the database should be append-only (`true`/`false`) +- `merge_mode` - Strategy for merging duplicate rows (`last_row`, `last_non_null`) +- `skip_wal` - Whether to disable Write-Ahead-Log for tables in the database (`'true'`/`'false'`) +- `compaction.*` - Compaction-related settings (e.g., `compaction.type`, `compaction.twcs.time_window`) + +Read more about [table options](#table-options). + +:::note Important Behavior Differences +Database options behave differently: + +- **TTL**: This option has ongoing effect. Tables without a specified TTL will continuously inherit this database-level value. Changing the database TTL will immediately impact all tables that don't have their own TTL setting. + +- **Other options** (`memtable.type`, `append_mode`, `merge_mode`, `skip_wal`, `compaction.*`): These act as template variables that are only applied when creating new tables. Changing these database-level options will NOT affect existing tables - they only serve as defaults for newly created tables. +::: + +When creating a table, if the corresponding table options are not provided, the options configured at the database level will be applied. + +### Examples + +Creates a `test` database: + +```sql +CREATE DATABASE test; +``` + +```sql +Query OK, 1 row affected (0.05 sec) +``` + +Creates it again with `IF NOT EXISTS`: + +```sql +CREATE DATABASE IF NOT EXISTS test; +``` + +Create a database with a `TTL` (Time-To-Live) of seven days, which means all the tables in this database will inherit this option if they don't have their own `TTL` setting: + +```sql +CREATE DATABASE test WITH (ttl='7d'); +``` + +Create a database with multiple options, including append mode and custom memtable type: + +```sql +CREATE DATABASE test WITH ( + ttl='30d', + 'memtable.type'='partition_tree', + 'append_mode'='true' +); +``` + +Create a database with Write-Ahead-Log disabled and custom merge mode: + +```sql +CREATE DATABASE test WITH ( + 'skip_wal'='true', + 'merge_mode'='last_non_null' +); +``` + +## CREATE TABLE + +### Syntax + +Creates a new table in the `db` database or the current database in use: + +```sql +CREATE TABLE [IF NOT EXISTS] [db.]table_name +( + column1 type1 [NULL | NOT NULL] [DEFAULT expr1] [TIME INDEX] [PRIMARY KEY] [indexes] [COMMENT comment1], + column2 type2 [NULL | NOT NULL] [DEFAULT expr2] [TIME INDEX] [PRIMARY KEY] [indexes] [COMMENT comment2], + ... + [TIME INDEX (column)], + [PRIMARY KEY(column1, column2, ...)], +) +[ + PARTITION ON COLUMNS(column1, column2, ...) ( + , + ... + ) +] +ENGINE = engine WITH([TTL | storage | ...] = expr, ...) +``` + +The table schema is specified by the brackets before the `ENGINE`. The table schema is a list of column definitions and table constraints. + +For information on the `engine` option and table engine selection, please refer to the [Table Engines](/reference/about-greptimedb-engines.md) guide. + +A column definition includes the column `column_name`, `type`, and options such as nullable or default values, etc. Please see below. + +### Table constraints + +The table constraints contain the following: + +- `TIME INDEX` specifies the time index column, which always has one and only one column. It indicates the `Timestamp` type in the [data model](/user-guide/concepts/data-model.md) of GreptimeDB. +- `PRIMARY KEY` specifies the table's primary key column, which indicates the `Tag` type in the [data model](/user-guide/concepts/data-model.md) of GreptimeDB. It cannot include the time index column, but it always implicitly adds the time index column to the end of keys. +- The Other columns are `Field` columns in the [data model](/user-guide/concepts/data-model.md) of GreptimeDB. + +:::tip NOTE +The `PRIMARY KEY` specified in the `CREATE` statement is **not** the primary key in traditional relational databases. +Actually, The `PRIMARY KEY` in traditional relational databases is equivalent to the combination of `PRIMARY KEY` and `TIME INDEX` in GreptimeDB. In other words, the `PRIMARY KEY` and `TIME INDEX` together constitute the unique identifier of a row in GreptimeDB. +::: + +The statement won't do anything if the table already exists and `IF NOT EXISTS` is presented; otherwise returns an error. + +#### Indexes + +GreptimeDB provides various type of indexes to accelerate query. Please refer to [Data Index](/user-guide/manage-data/data-index.md) for more details. + +### Table options + +Users can add table options by using `WITH`. The valid options contain the following: + +| Option | Description | Value | +| ------------------------------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ttl` | The storage time of the table data | A time duration string such as `'60m'`, `'1h'` for one hour, `'14d'` for 14 days etc. Supported time units are: `s` / `m` / `h` / `d`. | +| `storage` | The name of the table storage engine provider | String value, such as `S3`, `Gcs`, etc. It must be configured in `[[storage.providers]]`, see [configuration](/user-guide/deployments-administration/configuration.md#storage-engine-provider). | +| `compaction.type` | Compaction strategy of the table | String value. Only `twcs` is allowed. | +| `compaction.twcs.trigger_file_num` | Number of files in a specific time window to trigger a compaction | String value, such as '8'. Only available when `compaction.type` is `twcs`. You can refer to this [document](https://cassandra.apache.org/doc/latest/cassandra/managing/operating/compaction/twcs.html) to learn more about the `twcs` compaction strategy. | +| `compaction.twcs.time_window` | Compaction time window | String value, such as '1d' for 1 day. The table usually partitions rows into different time windows by their timestamps. Only available when `compaction.type` is `twcs`. | +| `compaction.twcs.max_output_file_size` | Maximum allowed output file size for TWCS compaction | String value, such as '1GB', '512MB'. Sets the maximum size for files produced by TWCS compaction. Only available when `compaction.type` is `twcs`. | +| `memtable.type` | Type of the memtable. | String value, supports `time_series`, `partition_tree`. | +| `append_mode` | Whether the table is append-only | String value. Default is 'false', which removes duplicate rows by primary keys and timestamps according to the `merge_mode`. Setting it to 'true' to enable append mode and create an append-only table which keeps duplicate rows. | +| `merge_mode` | The strategy to merge duplicate rows | String value. Only available when `append_mode` is 'false'. Default is `last_row`, which keeps the last row for the same primary key and timestamp. Setting it to `last_non_null` to keep the last non-null field for the same primary key and timestamp. | +| `comment` | Table level comment | String value. | +| `skip_wal` | Whether to disable Write-Ahead-Log for this table | String type. When set to `'true'`, the data written to the table will not be persisted to the write-ahead log, which can avoid storage wear and improve write throughput. However, when the process restarts, any unflushed data will be lost. Please use this feature only when the data source itself can ensure reliability. | +| `index.type` | Index type | **Only for metric engine** String value, supports `none`, `skipping`. | + +#### Create a table with TTL +For example, to create a table with the storage data TTL(Time-To-Live) is seven days: + +```sql +CREATE TABLE IF NOT EXISTS temperatures( + ts TIMESTAMP TIME INDEX, + temperature DOUBLE DEFAULT 10, +) with(ttl='7d'); +``` + +The `ttl` value can be one of the following: + +- A [duration](/reference/time-durations.md) like `1hour 12min 5s`. +- `forever`, `NULL`, an empty string `''` and `0s` (or any zero length duration, like `0d`), means the data will never be deleted. +- `instant`, note that database's TTL can't be set to `instant`. `instant` means the data will be deleted instantly when inserted, useful if you want to send input to a flow task without saving it, see more details in [flow management documents](/user-guide/flow-computation/manage-flow.md#manage-flows). +- Unset, `ttl` can be unset by using `ALTER TABLE UNSET 'ttl'`, which means the table will inherit the database's ttl policy (if any). + +If a table has its own TTL policy, it will take precedence over the database TTL policy. +Otherwise, the database TTL policy will be applied to the table. + +So if table's TTL is set to `forever`, no matter what the database's TTL is, the data will never be deleted. But if you unset table TTL using: +```sql +ALTER TABLE UNSET 'ttl'; +``` +Then the database's TTL will be applied to the table. + +Note that the default TTL setting for table and database is unset, which also means the data will never be deleted. + +#### Create a table with custom storage +Create a table that stores the data in Google Cloud Storage: + +```sql +CREATE TABLE IF NOT EXISTS temperatures( + ts TIMESTAMP TIME INDEX, + temperature DOUBLE DEFAULT 10, +) with(ttl='7d', storage="Gcs"); +``` + +#### Create a table with custom compaction options +Create a table with custom compaction options. The table will attempt to partition data into 1-day time window based on the timestamps of the data and merges files within each time window if they exceed 8 files. + +```sql +CREATE TABLE IF NOT EXISTS temperatures( + ts TIMESTAMP TIME INDEX, + temperature DOUBLE DEFAULT 10, +) +with( + 'compaction.type'='twcs', + 'compaction.twcs.time_window'='1d', + 'compaction.twcs.trigger_file_num'='8', + 'compaction.twcs.max_output_file_size'='1GB' +); +``` + +#### Create an append-only table +Create an append-only table which disables deduplication. +```sql +CREATE TABLE IF NOT EXISTS temperatures( + ts TIMESTAMP TIME INDEX, + temperature DOUBLE DEFAULT 10, +) with('append_mode'='true'); +``` + +#### Create a table with merge mode +Create a table with `last_row` merge mode, which is the default merge mode. +```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'); +``` + +Under `last_row` mode, the table merges rows with the same primary key and timestamp by only keeping the latest 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 | | ++-------+-------------------------+------+--------+ +``` + + +Create a table with `last_non_null` merge mode. +```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'); +``` + +Under `last_non_null` mode, the table merges rows with the same primary key and timestamp by keeping the latest non-null value of each field. +```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 | ++-------+-------------------------+------+--------+ +``` + +#### Create a physical table with metric engine + +The metric engine use synthetic physical wide tables to store a large amount of small table data, achieving effects such as reuse of the same column and metadata. For details, please refer to the [metric engine document](/contributor-guide/datanode/metric-engine) and [Table Engines](/reference/about-greptimedb-engines.md) introduction. + +Create a physical table with the metric engine. +```sql +CREATE TABLE greptime_physical_table ( + greptime_timestamp TIMESTAMP(3) NOT NULL, + greptime_value DOUBLE NULL, + TIME INDEX (greptime_timestamp), +) +engine = metric +with ( + "physical_metric_table" = "", +); +``` + +#### Create a physical table with enable skipping index for columns + +By default, the metric engine won't create indexes for columns. You can enable it by setting the `index.type` to `skipping`. + +Create a physical table with a skipping index; all automatically added columns will have this index applied. + +```sql +CREATE TABLE greptime_physical_table ( + greptime_timestamp TIMESTAMP(3) NOT NULL, + greptime_value DOUBLE NULL, + TIME INDEX (greptime_timestamp), +) +engine = metric +with ( + "physical_metric_table" = "", + "index.type" = "skipping", +); +``` + + + +### Column options + +GreptimeDB supports the following column options: + +| Option | Description | +| ----------------- | ---------------------------------------------------------------------------------------------------------- | +| NULL | The column value can be `null`. | +| NOT NULL | The column value can't be `null`. | +| DEFAULT `expr` | The column's default value is `expr`, which its result type must be the column's type | +| COMMENT `comment` | The column comment. It must be a string value | +| FULLTEXT INDEX | Creates a full-text index to speed up full-text search operations. Applicable only to string-type columns. | +| SKIPPING INDEX | Creates a skipping index to speed up query on sparse data. | +| INVERTED INDEX | Creates an inverted index to speed up query on dense data. | + +The table constraints `TIME INDEX` and `PRIMARY KEY` can also be set by column option, but they can only be specified once in column definitions. So you can't specify `PRIMARY KEY` for more than one column except by the table constraint `PRIMARY KEY` : + +```sql +CREATE TABLE system_metrics ( + host STRING PRIMARY KEY, + idc STRING PRIMARY KEY, + cpu_util DOUBLE, + memory_util DOUBLE, + disk_util DOUBLE, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP(), + TIME INDEX(ts) +); +``` + +Goes wrong: + +```sql + Illegal primary keys definition: not allowed to inline multiple primary keys in columns options +``` + +```sql +CREATE TABLE system_metrics ( + host STRING, + idc STRING, + cpu_util DOUBLE, + memory_util DOUBLE, + disk_util DOUBLE, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + PRIMARY KEY(host, idc), +); +``` + +```sql +Query OK, 0 rows affected (0.01 sec) +``` + +#### `INDEX` Column Option + +For more information on the `INDEX` column option, please refer to the [Data Index](/user-guide/manage-data/data-index.md) document. + +### Region partition rules + +Please refer to [Partition](/contributor-guide/frontend/table-sharding.md#partition) for more details. + +## CREATE EXTERNAL TABLE + +### Syntax + +Creates a new file external table in the `db` database or the current database in use: + +```sql +CREATE EXTERNAL 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], + ... + [TIME INDEX (column)], + [PRIMARY KEY(column1, column2, ...)] + ) +] WITH ( + LOCATION = url, + FORMAT = { 'CSV' | 'JSON' | 'PARQUET' | 'ORC' } + [,PATTERN = regex_pattern ] + [,REGION = region ] + [,ENDPOINT = uri ] + [,ACCESS_KEY_ID = key_id ] + [,SECRET_ACCESS_KEY = access_key ] + [,ENABLE_VIRTUAL_HOST_STYLE = { TRUE | FALSE }] + [,SESSION_TOKEN = token ] + ... +) +``` + +### Table options + +| Option | Description | Required | +| ---------- | ------------------------------------------------------------------------------- | ------------ | +| `LOCATION` | External files locations, e.g., `s3://[]`, `//[]` | **Required** | +| `FORMAT` | Target file(s) format, e.g., JSON, CSV, Parquet, ORC | **Required** | +| `PATTERN` | Use regex to match files. e.g., `*_today.parquet` | Optional | + +#### S3 + +| Option | Description | Required | +| --------------------------- | ------------------------------------------------------------------------------------- | ------------ | +| `REGION` | AWS region name. e.g., us-east-1. | **Required** | +| `ENDPOINT` | The bucket endpoint | Optional | +| `ACCESS_KEY_ID` | ACCESS_KEY_ID Your access key ID for connecting the AWS S3 compatible object storage. | Optional | +| `SECRET_ACCESS_KEY` | Your secret access key for connecting the AWS S3 compatible object storage. | Optional | +| `ENABLE_VIRTUAL_HOST_STYLE` | If you use virtual hosting to address the bucket, set it to "true". | Optional | +| `SESSION_TOKEN` | Your temporary credential for connecting the AWS S3 service. | Optional | + +### Time Index Column + +When creating an external table using the `CREATE EXTERNAL TABLE` statement, you are required to use the `TIME INDEX` constraint to specify a Time Index column. + +### Examples + +You can create an external table without columns definitions, the column definitions will be automatically inferred: + +```sql +CREATE EXTERNAL TABLE IF NOT EXISTS city WITH (location='/var/data/city.csv',format='csv'); +``` + +In this example, we did not explicitly define the columns of the table. To satisfy the requirement that the external table must specify a **Time Index** column, the `CREATE EXTERNAL TABLE` statement will infer the Time Index column according to the following rules: + +1. If the Time Index column can be inferred from the file metadata, then that column will be used as the Time Index column. +2. If there is a column named `greptime_timestamp` (the type of this column must be `TIMESTAMP`, otherwise, an error will be thrown), then this column will be used as the Time Index column. +3. Otherwise, a column named `greptime_timestamp` will be automatically created as the Time Index column, and a `DEFAULT '1970-01-01 00:00:00+0000'` constraint will be added. + +Or + +```sql +CREATE EXTERNAL TABLE city ( + host string, + ts timestamp, + cpu float64 default 0, + memory float64, + TIME INDEX (ts), + PRIMARY KEY(host) +) WITH (location='/var/data/city.csv', format='csv'); +``` + +In this example, we explicitly defined the `ts` column as the Time Index column. If there is no suitable Time Index column in the file, you can also create a placeholder column and add a `DEFAULT expr` constraint. + + +## CREATE FLOW + +```sql +CREATE [OR REPLACE] FLOW [ IF NOT EXISTS ] +SINK TO +[ EXPIRE AFTER ] +[ COMMENT '' ] +AS +; +``` + +For the statement to create or update a flow, please read the [flow management documents](/user-guide/flow-computation/manage-flow.md#create-a-flow). + +## CREATE VIEW + +```sql +CREATE [OR REPLACE] VIEW [ IF NOT EXISTS ] +AS select_statement +``` + +For the statement to create or update a view, please read the [view user guide](/user-guide/query-data/view.md#view). + +## CREATE TRIGGER + +Please refer to the [CREATE TRIGGER](/reference/sql/trigger-syntax.md#create-trigger) documentation. + diff --git a/versioned_docs/version-1.0/reference/sql/data-types.md b/versioned_docs/version-1.0/reference/sql/data-types.md new file mode 100644 index 0000000000..55e0066ed9 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/data-types.md @@ -0,0 +1,406 @@ +--- +keywords: [SQL data types, SQL column types, SQL syntax, SQL examples, SQL type compatibility] +description: Provides an overview of SQL data types supported by GreptimeDB, including string, binary, numeric, decimal, date and time, interval, JSON, and boolean types, with examples and compatibility with MySQL and PostgreSQL. +--- + +# Data Types + +SQL data types define the type of data that a column can store. When you run the `DESC TABLE` command, you can see the data type of each column. + +## String and Binary Data Types + +| Type Name | Description | Size | +| --------- | ---------------------------------------------------------------------- | -------------------------------- | +| `String` | UTF-8 encoded strings. Holds up to 2,147,483,647 bytes of data | The length of the strings | +| `Binary` | Variable-length binary values. Holds up to 2,147,483,647 bytes of data | The length of the data + 2 bytes | + +The maximum capacities of `String` and `Binary` are determined by their encodings and how the storage engine handles them. For example, `String` values are encoded into UTF-8. If all characters are 3 bytes in length, this field can store up to 715,827,882 characters. As for `Binary` types, they can store a maximum of 2,147,483,647 bytes. + +## Numeric Data Types + +| Type Name | Description | Size | +| --------- | ----------------------------------------------- | ------- | +| `Int8` | -128 ~ 127 | 1 Byte | +| `Int16` | -32768 ~ 32767 | 2 Bytes | +| `Int32` | -2147483648 ~ 2147483647 | 4 Bytes | +| `Int64` | -9223372036854775808 ~ 9223372036854775807 | 8 Bytes | +| `UInt8` | 0 ~ 255 | 1 Byte | +| `UInt16` | 0 ~ 65535 | 2 Bytes | +| `UInt32` | 0 ~ 4294967295 | 4 Bytes | +| `UInt64` | 0 ~ 18446744073709551615 | 8 Bytes | +| `Float32` | 32-bit IEEE754 floating point values | 4 Bytes | +| `Float64` | Double precision IEEE 754 floating point values | 8 Bytes | + +## Decimal Type + +GreptimeDB supports the `decimal` type, a fixed-point type represented as `decimal(precision, scale)`, where `precision` is the total number of digits, and `scale` is the number of digits in the fractional part. For example, `123.45` has a precision of 5 and a scale of 2. + +- `precision` can range from [1, 38]. +- `scale` can range from [0, precision]. + +The default decimal is `decimal(38, 10)` if the precision and scale are not specified. + +```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; +``` + +Output: +```sql ++------+---------------------+ +| d | ts | ++------+---------------------+ +| 0.10 | 1970-01-01T00:00:01 | +| 0.20 | 1970-01-01T00:00:02 | ++------+---------------------+ +``` + +## Date and Time Types + +| Type Name | Description | Size | +| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | +| `TimestampSecond` | 64-bit timestamp values with seconds precision, range: `[-262144-01-01 00:00:00, +262143-12-31 23:59:59]` | 8 Bytes | +| `TimestampMillisecond` | 64-bit timestamp values with milliseconds precision, range: `[-262144-01-01 00:00:00.000, +262143-12-31 23:59:59.999]` | 8 Bytes | +| `TimestampMicroSecond` | 64-bit timestamp values with microseconds precision, range: `[-262144-01-01 00:00:00.000000, +262143-12-31 23:59:59.999999]` | 8 Bytes | +| `TimestampNanosecond` | 64-bit timestamp values with nanoseconds precision, range: `[1677-09-21 00:12:43.145225, 2262-04-11 23:47:16.854775807]` | 8 Bytes | +| `Interval` | Time interval | 4 Bytes for `YearMonth`, 8 Bytes for `DayTime` and 16 Bytes for `MonthDayNano` | + +:::tip NOTE +When inserting Timestamp string literals to GreptimeDB using MySQL/PostgreSQL protocol, the value range is limited to '0001-01-01 00:00:00' to '9999-12-31 23:59:59'. +::: + +### Interval Type + +`Interval` type is used in scenarios where you need to track and manipulate time durations. It can be written using the following verbose syntax: + +``` +QUANTITY UNIT [QUANTITY UNIT...] +``` + +* `QUANTITY`: is a number (possibly signed), +* `UNIT`: is `microsecond`, `millisecond`, `second`, `minute`, `hour`, `day`, `week`, `month`, `year`, `decade`, `century`, or abbreviations or plurals of these units; + +The amounts of the different units are combined, with each unit's sign determining if it adds or subtracts from the total interval. For example, '1 year -2 months' results in a net interval of ten months. Unfortunately, GreptimeDB doesn't support writing the interval in the format of [ISO 8601 time intervals](https://en.wikipedia.org/wiki/ISO_8601#Time_intervals) such as `P3Y3M700DT133H17M36.789S` etc. But it's output supports it. + +Let's take some examples: + +```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 minutes ago: + +```sql +SELECT '-1 hour 5 minute'::INTERVAL; +``` + +```sql ++--------------------------+ +| Utf8("-1 hour 5 minute") | ++--------------------------+ +| P0Y0M0DT0H-55M0S | ++--------------------------+ +``` + +1 hour and 5 minutes ago: + +```sql +SELECT '-1 hour -5 minute'::INTERVAL; +``` + +```sql ++---------------------------+ +| Utf8("-1 hour -5 minute") | ++---------------------------+ +| P0Y0M0DT-1H-5M0S | ++---------------------------+ +``` + +And of course, you can manipulate time with intervals by arithmetics. +Get the time of 5 minutes go: + +```sql +SELECT now() - '5 minute'::INTERVAL; +``` + +```sql ++----------------------------------------------+ +| now() - IntervalMonthDayNano("300000000000") | ++----------------------------------------------+ +| 2024-06-24 21:24:05.012306 | ++----------------------------------------------+ +``` + +GreptimeDB also supports shorthand forms without spaces, such as `3y2mon4h`: + +```sql +SELECT '3y2mon4h'::INTERVAL; +``` + +``` ++---------------------------------------------------------+ +| IntervalMonthDayNano("3010670175542044842954670112768") | ++---------------------------------------------------------+ +| P3Y2M0DT4H0M0S | ++---------------------------------------------------------+ +``` + +It also supports signed numbers: + +```sql +SELECT '-1h5m'::INTERVAL; +``` + +``` ++----------------------------------------------+ +| IntervalMonthDayNano("18446740773709551616") | ++----------------------------------------------+ +| P0Y0M0DT0H-55M0S | ++----------------------------------------------+ +``` + +Supported abbreviations include: + +| Abbreviation | Full name | +| ------------ | ------------ | +| y | years | +| mon | months | +| w | weeks | +| d | days | +| h | hours | +| m | minutes | +| s | seconds | +| millis | milliseconds | +| ms | milliseconds | +| us | microseconds | +| ns | nanoseconds | + +#### INTERVAL keyword + +In the examples above, we used the cast operation `'{quantity unit}'::INTERVAL` to demonstrate the interval type. In fact, the interval type can also be used with the syntax supported by the `INTERVAL` keyword, though the behavior varies between database dialects: + +1. In MySQL, the syntax is `INTERVAL {quantity} {unit}`, where `quantity` can be a number or a string depending on the context. For example: +```sql +mysql> SELECT INTERVAL 1 YEAR; ++--------------------------------------------------------------------------------------+ +| IntervalMonthDayNano("IntervalMonthDayNano { months: 12, days: 0, nanoseconds: 0 }") | ++--------------------------------------------------------------------------------------+ +| P1Y0M0DT0H0M0S | ++--------------------------------------------------------------------------------------+ +1 row in set (0.01 sec) + +mysql> SELECT INTERVAL '1 YEAR 2' MONTH; ++--------------------------------------------------------------------------------------+ +| IntervalMonthDayNano("IntervalMonthDayNano { months: 14, days: 0, nanoseconds: 0 }") | ++--------------------------------------------------------------------------------------+ +| P1Y2M0DT0H0M0S | ++--------------------------------------------------------------------------------------+ +1 row in set (0.00 sec) +``` + +2. In PostgreSQL and the default GreptimeDB dialect, it is `INTERVAL '{quantity unit}'`, where the INTERVAL keyword is followed by the interval string: +```sql +public=> SELECT INTERVAL '1 year'; + IntervalMonthDayNano("IntervalMonthDayNano { months: 12, days: 0, nanoseconds: 0 }") +-------------------------------------------------------------------------------------- + 1 year +(1 row) + +public=> SELECT INTERVAL '1 year 2 month'; + IntervalMonthDayNano("IntervalMonthDayNano { months: 14, days: 0, nanoseconds: 0 }") +-------------------------------------------------------------------------------------- + 1 year 2 mons +(1 row) +``` + +## JSON Type (Experimental) + +:::warning +The JSON feature is currently experimental and may change in future releases. +::: + +GreptimeDB supports the JSON type, allowing users to store and query JSON-formatted data. The JSON type is highly flexible and can store various forms of structured or unstructured data, making it suitable for use cases such as logging, analytics, and semi-structured data storage. + +```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; +``` + +Output: + +``` ++------------------------------------------+---------------------+ +| my_json | ts | ++------------------------------------------+---------------------+ +| {"key1":"value1","key2":10} | 1970-01-01 00:00:01 | +| {"name":"GreptimeDB","open_source":true} | 1970-01-01 00:00:02 | ++------------------------------------------+---------------------+ +``` + +### Query JSON data + +You can query the JSON data directly or extract specific fields using [JSON functions](./functions/overview.md#json-functions) provided by GreptimeDB. Here's an example: + +```sql +SELECT json_get_string(my_json, '$.name') as name FROM json_data; +``` + +Output: + +``` ++---------------------------------------------------+ +| name | ++---------------------------------------------------+ +| NULL | +| GreptimeDB | ++---------------------------------------------------+ +``` + + +## Boolean Type + +| Type Name | Description | Size | +| --------- | ----------- | ------ | +| `Boolean` | Bool values | 1 Byte | + +Use `TRUE` or `FALSE` to represent boolean values in SQL statements. For example: + +```sql +CREATE TABLE bools( + b BOOLEAN, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, +); +``` + +```sql +INSERT INTO bools(b) VALUES (TRUE), (FALSE); +``` + +## Data types compatible with MySQL and PostgreSQL + +### Type aliases + +For users migrating from MySQL or PostgreSQL to GreptimeDB, GreptimeDB supports the following alias types. + +| Data Type | Alias Types | +| ---------------------- | --------------------------------------------------------------- | +| `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)` | + +You can use these alias types when creating tables. +For example, use `Varchar` instead of `String`, `Double` instead of `Float64`, and `Timestamp(0)` instead of `TimestampSecond`. + +```sql +CREATE TABLE alias_types ( + s TEXT, + i DOUBLE, + ts0 TIMESTAMP(0) DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + PRIMARY KEY(s) +); +``` + +### Date and time types + +In addition to the `Timestamp` types used as the default time type in GreptimeDB, GreptimeDB also supports `Date` and `DateTime` types for compatibility with MySQL and PostgreSQL. + +| Type name | Description | Size | +| ---------- | ----------------------------------------------------------------------------------------- | ------- | +| `Date` | 32-bit date values represent the days since UNIX Epoch | 4 Bytes | +| `DateTime` | 64-bit timestamp values with milliseconds precision, equivalent to `TimestampMicrosecond` | 8 Bytes | + +## Examples + +### Create Table + +```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)); +``` + +### Describe Table + +```sql +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 | TimestampMicrosecond | | YES | | FIELD | +| ts0 | TimestampSecond | | YES | | FIELD | +| ts3 | TimestampMillisecond | | YES | | FIELD | +| ts6 | TimestampMicrosecond | | YES | | FIELD | +| ts9 | TimestampNanosecond | PRI | NO | current_timestamp() | TIMESTAMP | ++--------+----------------------+------+------+---------------------+---------------+ +``` diff --git a/versioned_docs/version-1.0/reference/sql/delete.md b/versioned_docs/version-1.0/reference/sql/delete.md new file mode 100644 index 0000000000..0edb86e9f3 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/delete.md @@ -0,0 +1,30 @@ +--- +keywords: [SQL DELETE, SQL data removal, SQL syntax, SQL examples, SQL conditional deletion] +description: Details the SQL DELETE statement for removing rows from a table based on a specified condition, including syntax and examples. +--- + +# DELETE + +`DELETE` is used to remove rows from a table. + +## Syntax + +```sql +DELETE FROM [db.]table WHERE expr +``` + +It removes rows from the table `[db.]table` that satisfies the expression `expr` after `WHERE`. The removed rows are marked immediately and can't be retrieved by all subsequent queries. + +## Example + +For example, there is a table with the primary key `host`: + +```sql +CREATE TABLE monitor ( host STRING, ts TIMESTAMP, cpu DOUBLE DEFAULT 0, memory DOUBLE, TIME INDEX (ts), PRIMARY KEY(host)) ; +``` + +To delete a row from it by primary key `host` and timestamp index `ts`: + +```sql +DELETE FROM monitor WHERE host = 'host1' and ts = 1655276557000; +``` diff --git a/versioned_docs/version-1.0/reference/sql/describe_table.md b/versioned_docs/version-1.0/reference/sql/describe_table.md new file mode 100644 index 0000000000..dc19d6dff8 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/describe_table.md @@ -0,0 +1,45 @@ +--- +keywords: [SQL DESCRIBE TABLE, SQL table structure, SQL syntax, SQL examples, SQL column details] +description: Describes the SQL DESCRIBE TABLE statement to display the structure of a table, including column names, data types, keys, nullability, default values, and semantic types, with examples. +--- + +# DESCRIBE TABLE + +`DESCRIBE [TABLE] [db.]table` describes the table structure in the `db` or the current database in-use. + +## Examples + +Describes the table `monitor`: + +```sql +DESCRIBE TABLE monitor; +``` + +or + +```sql +DESCRIBE monitor; +``` + +Output: + +```sql ++--------+----------------------+------+------+---------------------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------+----------------------+------+------+---------------------+---------------+ +| host | String | PRI | YES | | TAG | +| ts | TimestampMillisecond | PRI | NO | current_timestamp() | TIMESTAMP | +| cpu | Float64 | | YES | 0 | FIELD | +| memory | Float64 | | YES | | FIELD | ++--------+----------------------+------+------+---------------------+---------------+ +4 rows in set (0.00 sec) +``` + +It produces the table structure: + +* `Column`: the column names +* `Type`: the column data types +* `Key`: `PRI` means the column is in the primary key constraint. +* `Null`: `YES` means nullable, otherwise `NO` +* `Default`: default value or expression of the column +* `Semantic Type`: This column represents the semantic type, corresponding to `TAG`, `FIELD` or `TIMESTAMP` in the data model. diff --git a/versioned_docs/version-1.0/reference/sql/distinct.md b/versioned_docs/version-1.0/reference/sql/distinct.md new file mode 100644 index 0000000000..db79ee28b5 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/distinct.md @@ -0,0 +1,26 @@ +--- +keywords: [SQL DISTINCT, SQL unique values, SQL syntax, SQL examples, SQL data filtering] +description: Explains the SQL SELECT DISTINCT statement used to retrieve unique values from a dataset, with examples of using DISTINCT with and without filters. +--- + +# DISTINCT + +`SELECT DISTINCT` is used to select unique values from a set of data. This keyword returns distinct values +from the output of the query. + +The basic syntax for a `SELECT DISTINCT` statement is as followings: + +```sql +SELECT DISTINCT idc +FROM system_metrics; +``` + +`SELECT DISTINCT` can be used in conjunction with filters. + +```sql +SELECT DISTINCT idc, host +FROM system_metrics +WHERE host != 'host2'; +``` + +`SELECT DISTINCT` is a simple but powerful command of GreptimeDB SQL that allows users to easily condense the data into a summary of unique values. It can be used on one column or multiple columns, making it very versatile for data analysis and reporting. Using "SELECT DISTINCT" is a great way to get an overview of the types of data stored in the tables. diff --git a/versioned_docs/version-1.0/reference/sql/drop.md b/versioned_docs/version-1.0/reference/sql/drop.md new file mode 100644 index 0000000000..c56a1d129b --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/drop.md @@ -0,0 +1,103 @@ +--- +keywords: [SQL DROP, DROP DATABASE, DROP TABLE, DROP VIEW, SQL syntax, SQL examples] +description: Covers the SQL DROP statement for removing databases, tables, flows, and views in GreptimeDB, including syntax, examples. +--- + +# DROP + +## DROP DATABASE + +`DROP DATABASE` drops a database. It removes the catalog entries for the database and deletes the directory containing the data. + +:::danger Danger + +`DROP DATABASE` cannot be undone. Use it with care! + +::: + +### Syntax + +```sql +DROP DATABASE [ IF EXISTS ] db_name +``` + +- `IF EXISTS`: Do not throw an error if the database does not exist. +- `db_name`: The name of the database to remove. + +### Examples + +To drop a database named `test`: + +```sql +DROP DATABASE test; +``` + + +## DROP TABLE + +`DROP TABLE` removes tables from the database. It will remove the table definition and all table data, indexes, rules, and constraints for that table. + +:::danger Danger + +`DROP TABLE` cannot be undone. Use it with care! + +::: + +### Syntax + +```sql +DROP TABLE [ IF EXISTS ] table_name +``` + +- `IF EXISTS`: Do not throw an error if the table does not exist. +- `table_name`: The name of the table to remove. + + +### Examples + +Drop the table `monitor` in the current database: + +```sql +DROP TABLE monitor; +``` + + +## DROP FLOW + +```sql +DROP FLOW [ IF EXISTS ] flow_name; +``` + +- `IF EXISTS`: Do not throw an error if the flow does not exist. +- `flow_name`: The name of the flow to destroy. + +```sql +DROP FLOW IF EXISTS test_flow; +``` + +``` +Query OK, 0 rows affected (0.00 sec) +``` + +## DROP VIEW + +```sql +DROP VIEW [ IF EXISTS ] view_name; +``` + +- `IF EXISTS`: Do not throw an error if the view does not exist. +- `view_name`: The name of the view to remove. + +```sql +DROP VIEW IF EXISTS test_view; +``` + +``` +Query OK, 0 rows affected (0.00 sec) +``` + +## DROP TRIGGER + +Please refer to the [Trigger syntax](/reference/sql/trigger-syntax.md#drop-trigger) documentation. + + diff --git a/versioned_docs/version-1.0/reference/sql/explain.md b/versioned_docs/version-1.0/reference/sql/explain.md new file mode 100644 index 0000000000..933a91c3d3 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/explain.md @@ -0,0 +1,94 @@ +--- +keywords: [SQL EXPLAIN, SQL execution plan, SQL ANALYZE, SQL query optimization, SQL examples] +description: Provides information on the SQL EXPLAIN statement to obtain the execution plan of a query, including the optional ANALYZE clause to measure execution time and output rows, with examples. +--- + +# EXPLAIN + +`EXPLAIN` is used to provide the execution plan of a statement. + +## Syntax + +```sql +EXPLAIN [ANALYZE] [VERBOSE] SELECT ... +``` + +The `ANALYZE` clause will execute the statement and measure time spent at each plan node and the total rows of the output etc. + +The `VERBOSE` clause will provide more detailed information about the execution plan. + +## Examples + +Explains the following query: + +```sql +EXPLAIN SELECT * FROM monitor where host='host1'\G +``` + +Example: + +```sql +*************************** 1. row *************************** +plan_type: logical_plan + plan: MergeScan [is_placeholder=false] +*************************** 2. row *************************** +plan_type: physical_plan + plan: MergeScanExec: peers=[4612794875904(1074, 0), ] +``` + +The column `plan_type` indicates whether it's a`logical_plan` or `physical_plan`. And the column `plan` explains the plan in detail. + +The `MergeScan` plan merges the results from multiple regions. The `peers` array in the `MergeScanExec` physical plan contains the IDs of the regions that the plan will scan. + +Explains the execution of the plan by `ANALYZE`: + +```sql +EXPLAIN ANALYZE SELECT * FROM monitor where host='host1'\G +``` + +Example: + +```sql +*************************** 1. row *************************** +stage: 0 + node: 0 + plan: MergeScanExec: peers=[4612794875904(1074, 0), ] metrics=[output_rows: 0, greptime_exec_read_cost: 0, finish_time: 3301415, first_consume_time: 3299166, ready_time: 3104209, ] + +*************************** 2. row *************************** +stage: 1 + node: 0 + plan: SeqScan: region=4612794875904(1074, 0), partition_count=0 (0 memtable ranges, 0 file 0 ranges) metrics=[output_rows: 0, mem_used: 0, build_parts_cost: 1, build_reader_cost: 1, elapsed_await: 1, elapsed_poll: 21250, scan_cost: 1, yield_cost: 1, ] + +*************************** 3. row *************************** +stage: NULL + node: NULL + plan: Total rows: 0 +``` + +The `EXPLAIN ANALYZE` command provides metrics about the execution of each stage. The `SeqScan` plan scans the data from a single region. + +Explains the verbose information of the plan execution: +```sql +EXPLAIN ANALYZE VERBOSE SELECT * FROM monitor where host='host1'; +``` + +Example: + +```sql +*************************** 1. row *************************** +stage: 0 + node: 0 + plan: MergeScanExec: peers=[4612794875904(1074, 0), ] metrics=[output_rows: 0, greptime_exec_read_cost: 0, finish_time: 3479084, first_consume_time: 3476000, ready_time: 3209041, ] + +*************************** 2. row *************************** +stage: 1 + node: 0 + plan: SeqScan: region=4612794875904(1074, 0), partition_count=0 (0 memtable ranges, 0 file 0 ranges), projection=["host", "ts", "cpu", "memory"], filters=[host = Utf8("host1")], metrics_per_partition: [[partition=0, {prepare_scan_cost=579.75µs, build_reader_cost=0ns, scan_cost=0ns, convert_cost=0ns, yield_cost=0ns, total_cost=789.708µs, num_rows=0, num_batches=0, num_mem_ranges=0, num_file_ranges=0, build_parts_cost=0ns, rg_total=0, rg_fulltext_filtered=0, rg_inverted_filtered=0, rg_minmax_filtered=0, rg_bloom_filtered=0, rows_before_filter=0, rows_fulltext_filtered=0, rows_inverted_filtered=0, rows_bloom_filtered=0, rows_precise_filtered=0, num_sst_record_batches=0, num_sst_batches=0, num_sst_rows=0, first_poll=785.041µs}]] metrics=[output_rows: 0, mem_used: 0, build_parts_cost: 1, build_reader_cost: 1, elapsed_await: 1, elapsed_poll: 17208, scan_cost: 1, yield_cost: 1, ] + +*************************** 3. row *************************** +stage: NULL + node: NULL + plan: Total rows: 0 +``` + +The `EXPLAIN ANALYZE VERBOSE` command provides the detail metrics about the execution of scan plans. diff --git a/versioned_docs/version-1.0/reference/sql/functions/approximate.md b/versioned_docs/version-1.0/reference/sql/functions/approximate.md new file mode 100644 index 0000000000..e24dff6a25 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/functions/approximate.md @@ -0,0 +1,265 @@ +--- +keywords: [Approximate functions, approximate count distinct, approximate quantile, SQL functions] +description: Lists and describes approximate functions available in GreptimeDB, including their usage and examples. +--- + +# Approximate Functions + +This page lists approximate functions in GreptimeDB, which are used for approximate data analysis. + +:::warning +The following approximate functions is currently experimental and may change in future releases. +::: + +## Approximate Count Distinct (HLL) + +The [HyperLogLog](https://algo.inria.fr/flajolet/Publications/FlFuGaMe07.pdf) (HLL) algorithm is used to calculate the approximate count distinct of a set of values. It provides efficient memory usage and speed for this purpose. Three functions are provided to work with the HLL algorithm, described in following chapters: + +:::warning +Notice that due to the approximate nature of the algorithm, the results may not be exact but are usually very close to the actual count distinct. The relative standard error of the HyperLogLog algorithm is about 1.04/sqrt(m), where m is the number of registers used in the algorithm. GreptimeDB uses 16384 registers by default, which gives a relative standard error of about 0.008125(or 0.8125%). +::: + +### `hll` + +`hll(value)` creates a HyperLogLog state in binary from a given column. The `value` can be any column that you want to calculate the approximate count distinct for. It returns a binary representation of the HLL state, which can be stored in a table or used in further calculations. See [Full Usage Example](#full-usage-example) for a full example of how to use this function in combination with other functions to calculate approximate count distinct. + +### `hll_merge` + +`hll_merge(hll_state)` merges multiple HyperLogLog states into one. This is useful when you want to combine the results of multiple HLL calculations, such as when aggregating data from different time windows or sources. The `hll_state` parameter is the binary representation of the HLL state created by [`hll`](#hll). The merged state can then be used to calculate the approximate count distinct across all the merged states. See [Full Usage Example](#full-usage-example) for a full example of how to use this function in combination with other functions to calculate approximate count distinct. + + +### `hll_count` + +`hll_count(hll_state)` retrieves the approximate count distinct from a HyperLogLog state. This function takes the HLL state created by `hll` or merged by `hll_merge` and returns the approximate count of distinct values. See [Full Usage Example](#full-usage-example) for a full example of how to use this function in combination with other functions to calculate approximate count distinct. + +### Full Usage Example +This example demonstrates how to use these functions in combination to calculate the approximate count distinct user id. + +First create the base table `access_log` for storing user access logs, and the `access_log_10s` table for storing the HyperLogLog states within a 10-second time window. Notice the `state` column is of type `BINARY`, which will store the HyperLogLog state in binary format. +```sql +CREATE TABLE access_log ( + `url` STRING, + user_id BIGINT, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY (`url`, `user_id`) +); + +CREATE TABLE access_log_10s ( + `url` STRING, + time_window timestamp time INDEX, + state BINARY, + PRIMARY KEY (`url`) +); +``` + +Insert some sample data into access_log: +```sql +INSERT INTO access_log VALUES + ("/dashboard", 1, "2025-03-04 00:00:00"), + ("/dashboard", 1, "2025-03-04 00:00:01"), + ("/dashboard", 2, "2025-03-04 00:00:05"), + ("/dashboard", 2, "2025-03-04 00:00:10"), + ("/dashboard", 2, "2025-03-04 00:00:13"), + ("/dashboard", 4, "2025-03-04 00:00:15"), + ("/not_found", 1, "2025-03-04 00:00:10"), + ("/not_found", 3, "2025-03-04 00:00:11"), + ("/not_found", 4, "2025-03-04 00:00:12"); +``` + +Now we can use the `hll` function to create a HyperLogLog state for the `user_id` column with a 10-second time window. The output will be a binary representation of the HLL state, which contains the necessary information to calculate approximate count distinct later. The `date_bin` function is used to group the data into 10-second time windows. Hence this `INSERT INTO` statement will create a HyperLogLog state for each 10-second time window in the `access_log` table, and insert it into the `access_log_10s` table: +```sql +-- Use a 10-second windowed query to calculate the HyperLogLog states +INSERT INTO + access_log_10s +SELECT + `url`, + date_bin("10s" :: INTERVAL, ts) AS time_window, + hll(`user_id`) AS state +FROM + access_log +GROUP BY + `url`, + time_window; +-- results will be similar to this: +-- Query OK, 3 rows affected (0.05 sec) +``` + +Then we can use the `hll_count` function to retrieve the approximate count distinct from the HyperLogLog state(which is the `state` column). For example, to get the approximate count distinct of user visits for each 10-second time window, we can run the following query: +```sql +-- use hll_count to query approximate data in access_log_10s, notice for small datasets, the results may not be very accurate. +SELECT `url`, `time_window`, hll_count(state) FROM access_log_10s; + +-- results as follows: +-- +------------+---------------------+---------------------------------+ +-- | url | time_window | hll_count(access_log_10s.state) | +-- +------------+---------------------+---------------------------------+ +-- | /dashboard | 2025-03-04 00:00:00 | 2 | +-- | /dashboard | 2025-03-04 00:00:10 | 2 | +-- | /not_found | 2025-03-04 00:00:10 | 3 | +-- +------------+---------------------+---------------------------------+ +``` + +In addition, we can aggregate the 10-second data to a 1-minute level by merging the HyperLogLog states using `hll_merge`. This allows us to calculate the approximate count distinct for a larger time window, which can be useful for analyzing trends over time. The following query demonstrates how to do this: +```sql +-- aggregate the 10-second data to a 1-minute level by merging the HyperLogLog states using `hll_merge`. +SELECT + `url`, + date_bin('1 minute' :: INTERVAL, `time_window`) AS time_window_1m, + hll_count(hll_merge(state)) as uv_per_min +FROM + access_log_10s +GROUP BY + `url`, + date_bin('1 minute' :: INTERVAL, `time_window`); + +-- results as follows: +-- +------------+---------------------+------------+ +-- | url | time_window_1m | uv_per_min | +-- +------------+---------------------+------------+ +-- | /dashboard | 2025-03-04 00:00:00 | 3 | +-- | /not_found | 2025-03-04 00:00:00 | 3 | +-- +------------+---------------------+------------+ +``` + +Note how the `hll_merge` function is used to merge the HyperLogLog states from the `access_log_10s` table, and then the `hll_count` function is used to calculate the approximate count distinct for each 1-minute time window. If only use `hll_merge` without `hll_count`, the result will just be a unreadable binary representation of the merged HyperLogLog state, which is not very useful for analysis. Hence we use `hll_count` to retrieve the approximate count distinct from the merged state. + +This following flowchart illustrates above usage of the HyperLogLog functions. First raw event data is first group by time window and url, then the `hll` function is used to create a HyperLogLog state for each time window and url, then the `hll_count` function is used to retrieve the approximate count distinct for each time window and url. Finally, the `hll_merge` function is used to merge the HyperLogLog states for each url, and then the `hll_count` function is used again to retrieve the approximate count distinct for the 1-minute time window. +![HLL Usage Flowchart](/hll.svg) + +## Approximate Quantile (UDDSketch) + +Three functions are provided for approximate quantile calculation using the [UDDSketch](https://arxiv.org/abs/2004.08604) algorithm. + +:::warning +Notice that the UDDSketch algorithm is designed to provide approximate quantiles with a tunable error rate, which allows for efficient memory usage and fast calculations. The results may not be exact but are usually very close to the actual quantiles. +::: + +### `uddsketch_state` + +The `uddsketch_state` function is used to create a UDDSketch state in binary from a given column. It takes three parameters: +- `bucket_num`, which is the number of buckets to use for the sketch, see [How to determine bucket number and error rate](#how-to-determine-bucket_num-and-error_rate) for how to decide the value. +- `error_rate`, which is the desired error rate for the quantile calculation. +- `value` parameter is the column from which the sketch will be created. + +for example, for a simple table `percentile_base` shown below, we can create a `uddsketch_state` for the `value` column with a bucket number of 128 and an error rate of 0.01 (1%). The output will be a binary representation of the UDDSketch state, which contains the necessary information to calculate approximate quantiles later. + +This output binary state can be think of as a histogram of the values in the `value` column, which can then be merged using `uddsketch_merge` or used to calculate quantiles using `uddsketch_calc` as shown later. See [UDDSketch Full Usage Example](#uddsketch-full-usage-example) for a full example of how to use these functions in combination to calculate approximate quantiles. + +### `uddsketch_merge` + +The `uddsketch_merge` function is used to merge multiple UDDSketch states into one. It takes three parameters: +- `bucket_num`, which is the number of buckets to use for the sketch, see [How to determine bucket number and error rate](#how-to-determine-bucket_num-and-error_rate) for how to decide the value. +- `error_rate`, which is the desired error rate for the quantile calculation. +- `udd_state`, which is the binary representation of the UDDSketch state created by `uddsketch_state`. + +This is useful when you want to combine results from different time windows or sources. Notice that the `bucket_num` and `error_rate` must match the original sketch where the state was created, or else the merge will fail. + +For example, if you have multiple UDDSketch states from different time windows, you can merge them into a single state to calculate the overall quantile across all the data.This output binary state can then be used to calculate quantiles using `uddsketch_calc`. See [UDDSketch Full Usage Example](#uddsketch-full-usage-example) for a full example of how to use these functions in combination to calculate approximate quantiles. + + +### `uddsketch_calc` + +The `uddsketch_calc` function is used to calculate the approximate quantile from a UDDSketch state. It takes two parameters: +- `quantile`, which is a value between 0 and 1 representing the desired quantile to calculate, i.e., 0.99 for the 99th percentile. +- `udd_state`, which is the binary representation of the UDDSketch state created by `uddsketch_state` or merged by `uddsketch_merge`. + +see [UDDSketch Full Usage Example](#uddsketch-full-usage-example) for a full example of how to use these functions in combination to calculate approximate quantiles. + +### How to determine `bucket_num` and `error_rate` + +The `bucket_num` parameter sets the maximum number of internal containers the sketch can use, directly controlling its memory footprint. Think of it as the physical storage capacity for tracking different value ranges. A larger `bucket_num` allows the sketch to accurately represent a wider dynamic range of data (i.e. a larger ratio between the maximum and minimum values). If this limit is too small for your data, the sketch will be forced to merge very high or low values, which degrades its accuracy. A recommended value for `bucket_num` is 128, which provides a good balance between accuracy and memory usage for most use cases. + +The `error_rate` defines the desired precision for your quantile calculations. It guarantees that any computed quantile (e.g., p99) is within a certain *relative* percentage of the true value. For example, an `error_rate` of `0.01` ensures the result is within 1% of the actual value. A smaller `error_rate` provides higher accuracy, as it forces the sketch to use more granular buckets to distinguish between closer numbers. + +These two parameters create a direct trade-off. To achieve the high precision promised by a small `error_rate`, the sketch needs a sufficient `bucket_num`, especially for data that spans a wide range. `bucket_num` acts as the physical limit on accuracy. If your `bucket_num` is restricted by memory constraints, setting the `error_rate` to an extremely small value will not improve precision because the limit imposed by the available buckets. + +### UDDSketch Full Usage Example +This example demonstrates how to use three `uddsketch` functions describe above to calculate the approximate quantile of a set of values. + +First create the base table `percentile_base` for store the raw data, and the `percentile_5s` table for storing the UDDSketch states within a 5-second time window. notice the `percentile_state` column is of type `BINARY`, which will store the UDDSketch state in binary format. +```sql +CREATE TABLE percentile_base ( + `id` INT PRIMARY KEY, + `value` DOUBLE, + `ts` timestamp(0) time index +); + +CREATE TABLE percentile_5s ( + `percentile_state` BINARY, + `time_window` timestamp(0) time index +); +``` + +Insert some sample data into `percentile_base` : +```sql +INSERT INTO percentile_base (`id`, `value`, `ts`) VALUES + (1, 10.0, 1), + (2, 20.0, 2), + (3, 30.0, 3), + (4, 40.0, 4), + (5, 50.0, 5), + (6, 60.0, 6), + (7, 70.0, 7), + (8, 80.0, 8), + (9, 90.0, 9), + (10, 100.0, 10); +``` + +Now we can use the `uddsketch_state` function to create a UDDSketch state for the `value` column with a bucket number of 128 and an error rate of 0.01 (1%). The output will be a binary representation of the UDDSketch state, which contains the necessary information to calculate approximate quantiles later, the `date_bin` function is used to group the data into 5-second time windows. Hence this `INSERT INTO` statement will create a UDDSketch state for each 5-second time window in the `percentile_base` table, and insert it into the `percentile_5s` table: + +```sql +INSERT INTO + percentile_5s +SELECT + uddsketch_state(128, 0.01, `value`) AS percentile_state, + date_bin('5 seconds' :: INTERVAL, `ts`) AS time_window +FROM + percentile_base +GROUP BY + time_window; +-- results will be similar to this: +-- Query OK, 3 rows affected (0.05 sec) +``` + +Now we can use the `uddsketch_calc` function to calculate the approximate quantile from the UDDSketch state. For example, to get the approximate 99th percentile (p99) for each 5-second time window, we can run the following query: +```sql +-- query percentile_5s to get the approximate 99th percentile +SELECT + time_window, + uddsketch_calc(0.99, `percentile_state`) AS p99 +FROM + percentile_5s; + +-- results as follows: +-- +---------------------+--------------------+ +-- | time_window | p99 | +-- +---------------------+--------------------+ +-- | 1970-01-01 00:00:00 | 40.04777053326359 | +-- | 1970-01-01 00:00:05 | 89.13032933635911 | +-- | 1970-01-01 00:00:10 | 100.49456770856492 | +-- +---------------------+--------------------+ +``` +Notice in above query the `percentile_state` column is the UDDSketch state created by `uddsketch_state`. + +In addition, we can aggregate the 5-second data to a 1-minute level by merging the UDDSketch states using `uddsketch_merge`. This allows us to calculate the approximate quantile for a larger time window, which can be useful for analyzing trends over time. The following query demonstrates how to do this: +```sql +-- in addition, we can aggregate the 5-second data to a 1-minute level by merging the UDDSketch states using `uddsketch_merge`. +SELECT + date_bin('1 minute' :: INTERVAL, `time_window`) AS time_window_1m, + uddsketch_calc(0.99, uddsketch_merge(128, 0.01, `percentile_state`)) AS p99 +FROM + percentile_5s +GROUP BY + time_window_1m; + +-- results as follows: +-- +---------------------+--------------------+ +-- | time_window_1m | p99 | +-- +---------------------+--------------------+ +-- | 1970-01-01 00:00:00 | 100.49456770856492 | +-- +---------------------+--------------------+ +``` +Notice how the `uddsketch_merge` function is used to merge the UDDSketch states from the `percentile_5s` table, and then the `uddsketch_calc` function is used to calculate the approximate 99th percentile (p99) for each 1-minute time window. + +This following flowchart illustrates above usage of the UDDSketch functions. First raw event data is first group by time window, then the `uddsketch_state` function is used to create a UDDSketch state for each time window, then the `uddsketch_calc` function is used to retrieve the approximate 99th quantile for each time window. Finally, the `uddsketch_merge` function is used to merge the UDDSketch states for each time window, and then the `uddsketch_calc` function is used again to retrieve the approximate 99th quantile for the 1-minute time window. +![UDDSketch Usage Flowchart](/udd.svg) diff --git a/versioned_docs/version-1.0/reference/sql/functions/df-functions.md b/versioned_docs/version-1.0/reference/sql/functions/df-functions.md new file mode 100644 index 0000000000..382e32f1bb --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/functions/df-functions.md @@ -0,0 +1,5812 @@ +--- +keywords: [DataFusion functions, scalar functions, window functions, array functions] +description: Generated from the Apache DataFusion project's documents, this page lists and describes DataFusion functions, including scalar, window, and array functions. +--- +# 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. + +### Math Functions + +- [abs](#abs) +- [acos](#acos) +- [acosh](#acosh) +- [asin](#asin) +- [asinh](#asinh) +- [atan](#atan) +- [atan2](#atan2) +- [atanh](#atanh) +- [cbrt](#cbrt) +- [ceil](#ceil) +- [cos](#cos) +- [cosh](#cosh) +- [cot](#cot) +- [degrees](#degrees) +- [exp](#exp) +- [factorial](#factorial) +- [floor](#floor) +- [gcd](#gcd) +- [isnan](#isnan) +- [iszero](#iszero) +- [lcm](#lcm) +- [ln](#ln) +- [log](#log) +- [log10](#log10) +- [log2](#log2) +- [nanvl](#nanvl) +- [pi](#pi) +- [pow](#pow) +- [power](#power) +- [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. + +```sql +abs(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `acos` + +Returns the arc cosine or inverse cosine of a number. + +```sql +acos(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `acosh` + +Returns the area hyperbolic cosine or inverse hyperbolic cosine of a number. + +```sql +acosh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `asin` + +Returns the arc sine or inverse sine of a number. + +```sql +asin(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `asinh` + +Returns the area hyperbolic sine or inverse hyperbolic sine of a number. + +```sql +asinh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `atan` + +Returns the arc tangent or inverse tangent of a number. + +```sql +atan(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `atan2` + +Returns the arc tangent or inverse tangent of `expression_y / expression_x`. + +```sql +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. + +##### `atanh` + +Returns the area hyperbolic tangent or inverse hyperbolic tangent of a number. + +```sql +atanh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `cbrt` + +Returns the cube root of a number. + +```sql +cbrt(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `ceil` + +Returns the nearest integer greater than or equal to a number. + +```sql +ceil(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `cos` + +Returns the cosine of a number. + +```sql +cos(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `cosh` + +Returns the hyperbolic cosine of a number. + +```sql +cosh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `cot` + +Returns the cotangent of a number. + +```sql +cot(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `degrees` + +Converts radians to degrees. + +```sql +degrees(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `exp` + +Returns the base-e exponential of a number. + +```sql +exp(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `factorial` + +Factorial. Returns 1 if value is less than 2. + +```sql +factorial(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `floor` + +Returns the nearest integer less than or equal to a number. + +```sql +floor(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `gcd` + +Returns the greatest common divisor of `expression_x` and `expression_y`. Returns 0 if both inputs are zero. + +```sql +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 operators. +- **expression_y**: Second numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `isnan` + +Returns true if a given number is +NaN or -NaN otherwise returns false. + +```sql +isnan(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `iszero` + +Returns true if a given number is +0.0 or -0.0 otherwise returns false. + +```sql +iszero(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `lcm` + +Returns the least common multiple of `expression_x` and `expression_y`. Returns 0 if either input is zero. + +```sql +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 operators. +- **expression_y**: Second numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `ln` + +Returns the natural logarithm of a number. + +```sql +ln(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `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. + +```sql +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. + +##### `log10` + +Returns the base-10 logarithm of a number. + +```sql +log10(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `log2` + +Returns the base-2 logarithm of a number. + +```sql +log2(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `nanvl` + +Returns the first argument if it's not _NaN_. +Returns the second argument otherwise. + +```sql +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 π. + +```sql +pi() +``` + +##### `pow` + +_Alias of [power](#power)._ + +##### `power` + +Returns a base expression raised to the power of an exponent. + +```sql +power(base, exponent) +``` + +###### Arguments + +- **base**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **exponent**: Exponent numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Aliases + +- pow + +##### `radians` + +Converts degrees to radians. + +```sql +radians(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `random` + +Returns a random float value in the range [0, 1). +The random seed is unique to each row. + +```sql +random() +``` + +##### `round` + +Rounds a number to the nearest integer. + +```sql +round(numeric_expression[, decimal_places]) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of 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`. + +```sql +signum(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `sin` + +Returns the sine of a number. + +```sql +sin(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `sinh` + +Returns the hyperbolic sine of a number. + +```sql +sinh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `sqrt` + +Returns the square root of a number. + +```sql +sqrt(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `tan` + +Returns the tangent of a number. + +```sql +tan(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `tanh` + +Returns the hyperbolic tangent of a number. + +```sql +tanh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `trunc` + +Truncates a number to a whole number or truncated to the specified decimal places. + +```sql +trunc(numeric_expression[, decimal_places]) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of 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 + +- [coalesce](#coalesce) +- [greatest](#greatest) +- [ifnull](#ifnull) +- [least](#least) +- [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. + +```sql +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 | ++----------------------------------------+ +``` + +##### `greatest` + +Returns the greatest value in a list of expressions. Returns _null_ if all expressions are _null_. + +```sql +greatest(expression1[, ..., expression_n]) +``` + +###### Arguments + +- **expression1, expression_n**: Expressions to compare and return the greatest value.. Can be a constant, column, or function, and any combination of arithmetic operators. Pass as many expression arguments as necessary. + +###### Example + +```sql +> select greatest(4, 7, 5); ++---------------------------+ +| greatest(4,7,5) | ++---------------------------+ +| 7 | ++---------------------------+ +``` + +##### `ifnull` + +_Alias of [nvl](#nvl)._ + +##### `least` + +Returns the smallest value in a list of expressions. Returns _null_ if all expressions are _null_. + +```sql +least(expression1[, ..., expression_n]) +``` + +###### Arguments + +- **expression1, expression_n**: Expressions to compare and return the smallest value. Can be a constant, column, or function, and any combination of arithmetic operators. Pass as many expression arguments as necessary. + +###### Example + +```sql +> select least(4, 7, 5); ++---------------------------+ +| least(4,7,5) | ++---------------------------+ +| 4 | ++---------------------------+ +``` + +##### `nullif` + +Returns _null_ if _expression1_ equals _expression2_; otherwise it returns _expression1_. +This can be used to perform the inverse operation of [`coalesce`](#coalesce). + +```sql +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_. + +```sql +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_. + +```sql +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) +- [overlay](#overlay) +- [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. + +```sql +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. + +```sql +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. + +```sql +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 | ++-------------------------------------------+ +``` + +###### Alternative Syntax + +```sql +trim(BOTH trim_str FROM str) +``` + +```sql +trim(trim_str FROM str) +``` + +###### 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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +###### 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). + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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___ | ++-------------------------------------------+ +``` + +###### Alternative Syntax + +```sql +trim(LEADING trim_str FROM str) +``` + +**Related functions**: + +- [btrim](#btrim) +- [rtrim](#rtrim) + +##### `octet_length` + +Returns the length of a string in bytes. + +```sql +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) + +##### `overlay` + +Returns the string which is replaced by another string from the specified position and specified count length. + +```sql +overlay(str PLACING substr FROM pos [FOR count]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **substr**: Substring to replace in str. +- **pos**: The start position to start the replace in str. +- **count**: The count of characters to be replaced from start position of str. If not specified, will use substr length instead. + +###### Example + +```sql +> select overlay('Txxxxas' placing 'hom' from 2 for 4); ++--------------------------------------------------------+ +| overlay(Utf8("Txxxxas"),Utf8("hom"),Int64(2),Int64(4)) | ++--------------------------------------------------------+ +| Thomas | ++--------------------------------------------------------+ +``` + +##### `position` + +_Alias of [strpos](#strpos)._ + +##### `repeat` + +Returns a string with an input string repeated a specified number. + +```sql +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. + +```sql +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 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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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 | ++-------------------------------------------+ +``` + +###### Alternative Syntax + +```sql +trim(TRAILING trim_str FROM str) +``` + +**Related functions**: + +- [btrim](#btrim) +- [ltrim](#ltrim) + +##### `split_part` + +Splits a string based on a specified delimiter and returns the substring in the specified position. + +```sql +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. + +```sql +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. + +```sql +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 | ++----------------------------------------+ +``` + +###### Alternative Syntax + +```sql +position(substr in origstr) +``` + +###### Aliases + +- instr +- position + +##### `substr` + +Extracts a substring of a specified number of characters from a specific starting position in a string. + +```sql +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 | ++----------------------------------------------+ +``` + +###### Alternative Syntax + +```sql +substring(str from start_pos for length) +``` + +###### 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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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_count](#regexp_count) +- [regexp_like](#regexp_like) +- [regexp_match](#regexp_match) +- [regexp_replace](#regexp_replace) + +##### `regexp_count` + +Returns the number of matches that a [regular expression](https://docs.rs/regex/latest/regex/#syntax) has in a string. + +```sql +regexp_count(str, regexp[, start, 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. +- **start**: - **start**: Optional start position (the first position is 1) to search for the regular expression. 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_count('abcAbAbc', 'abc', 2, 'i'); ++---------------------------------------------------------------+ +| regexp_count(Utf8("abcAbAbc"),Utf8("abc"),Int64(2),Utf8("i")) | ++---------------------------------------------------------------+ +| 1 | ++---------------------------------------------------------------+ +``` + +##### `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. + +```sql +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 the first [regular expression](https://docs.rs/regex/latest/regex/#syntax) matches in a string. + +```sql +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). + +```sql +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 + +- [current_date](#current_date) +- [current_time](#current_time) +- [current_timestamp](#current_timestamp) +- [date_bin](#date_bin) +- [date_format](#date_format) +- [date_part](#date_part) +- [date_trunc](#date_trunc) +- [datepart](#datepart) +- [datetrunc](#datetrunc) +- [from_unixtime](#from_unixtime) +- [make_date](#make_date) +- [now](#now) +- [to_char](#to_char) +- [to_date](#to_date) +- [to_local_time](#to_local_time) +- [to_timestamp](#to_timestamp) +- [to_timestamp_micros](#to_timestamp_micros) +- [to_timestamp_millis](#to_timestamp_millis) +- [to_timestamp_nanos](#to_timestamp_nanos) +- [to_timestamp_seconds](#to_timestamp_seconds) +- [to_unixtime](#to_unixtime) +- [today](#today) + +##### `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. + +```sql +current_date() +``` + +###### Aliases + +- today + +##### `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. + +```sql +current_time() +``` + +##### `current_timestamp` + +_Alias of [now](#now)._ + +##### `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`. + +```sql +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 + +###### Example + +```sql +-- Bin the timestamp into 1 day intervals +> SELECT date_bin(interval '1 day', time) as bin +FROM VALUES ('2023-01-01T18:18:18Z'), ('2023-01-03T19:00:03Z') t(time); ++---------------------+ +| bin | ++---------------------+ +| 2023-01-01T00:00:00 | +| 2023-01-03T00:00:00 | ++---------------------+ +2 row(s) fetched. + +-- Bin the timestamp into 1 day intervals starting at 3AM on 2023-01-01 +> SELECT date_bin(interval '1 day', time, '2023-01-01T03:00:00') as bin +FROM VALUES ('2023-01-01T18:18:18Z'), ('2023-01-03T19:00:03Z') t(time); ++---------------------+ +| bin | ++---------------------+ +| 2023-01-01T03:00:00 | +| 2023-01-03T03:00:00 | ++---------------------+ +2 row(s) fetched. +``` + +##### `date_format` + +_Alias of [to_char](#to_char)._ + +##### `date_part` + +Returns the specified part of the date as an integer. + +```sql +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. + +###### Alternative Syntax + +```sql +extract(field FROM source) +``` + +###### Aliases + +- datepart + +##### `date_trunc` + +Truncates a timestamp value to a specified precision. + +```sql +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 + +##### `datepart` + +_Alias of [date_part](#date_part)._ + +##### `datetrunc` + +_Alias of [date_trunc](#date_trunc)._ + +##### `from_unixtime` + +Converts an integer to RFC3339 timestamp format (`YYYY-MM-DDT00:00:00.000000000Z`). Integers and unsigned integers are interpreted as seconds since the unix epoch (`1970-01-01T00:00:00Z`) return the corresponding timestamp. + +```sql +from_unixtime(expression[, timezone]) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **timezone**: Optional timezone to use when converting the integer to a timestamp. If not provided, the default timezone is UTC. + +###### Example + +```sql +> select from_unixtime(1599572549, 'America/New_York'); ++-----------------------------------------------------------+ +| from_unixtime(Int64(1599572549),Utf8("America/New_York")) | ++-----------------------------------------------------------+ +| 2020-09-08T09:42:29-04:00 | ++-----------------------------------------------------------+ +``` + +##### `make_date` + +Make a date from year/month/day component parts. + +```sql +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 + +```sql +> 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) + +##### `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. + +```sql +now() +``` + +###### Aliases + +- current_timestamp + +##### `to_char` + +Returns a string representation of a date, time, timestamp or duration based on a [Chrono format](https://docs.rs/chrono/latest/chrono/format/strftime/index.html). Unlike the PostgreSQL equivalent of this function numerical formatting is not supported. + +```sql +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](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) string to use to convert the expression. +- **day**: Day to use when making the date. Can be a constant, column or function, and any combination of arithmetic operators. + +###### Example + +```sql +> 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](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/to_char.rs) + +###### Aliases + +- date_format + +##### `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`. + +```sql +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) + +##### `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. + +```sql +to_local_time(expression) +``` + +###### Arguments + +- **expression**: Time expression to operate on. Can be a constant, column, or function. + +###### Example + +```sql +> 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. + +```sql +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](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_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_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](https://docs.rs/chrono/latest/chrono/format/strftime/index.html)s are provided. Integers and unsigned integers are interpreted as microseconds since the unix epoch (`1970-01-01T00:00:00Z`) Returns the corresponding timestamp. + +```sql +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](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_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_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 formats](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) are provided. Integers and unsigned integers are interpreted as milliseconds since the unix epoch (`1970-01-01T00:00:00Z`). Returns the corresponding timestamp. + +```sql +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](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_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_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](https://docs.rs/chrono/latest/chrono/format/strftime/index.html)s are provided. Integers and unsigned integers are interpreted as nanoseconds since the unix epoch (`1970-01-01T00:00:00Z`). Returns the corresponding timestamp. + +```sql +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](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_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](https://docs.rs/chrono/latest/chrono/format/strftime/index.html)s are provided. Integers and unsigned integers are interpreted as seconds since the unix epoch (`1970-01-01T00:00:00Z`). Returns the corresponding timestamp. + +```sql +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](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_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) + +##### `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](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) are provided. + +```sql +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](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_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 | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +##### `today` + +_Alias of [current_date](#current_date)._ + +### Array Functions + +- [array_any_value](#array_any_value) +- [array_append](#array_append) +- [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_element](#array_element) +- [array_empty](#array_empty) +- [array_except](#array_except) +- [array_extract](#array_extract) +- [array_has](#array_has) +- [array_has_all](#array_has_all) +- [array_has_any](#array_has_any) +- [array_indexof](#array_indexof) +- [array_intersect](#array_intersect) +- [array_join](#array_join) +- [array_length](#array_length) +- [array_max](#array_max) +- [array_ndims](#array_ndims) +- [array_pop_back](#array_pop_back) +- [array_pop_front](#array_pop_front) +- [array_position](#array_position) +- [array_positions](#array_positions) +- [array_prepend](#array_prepend) +- [array_push_back](#array_push_back) +- [array_push_front](#array_push_front) +- [array_remove](#array_remove) +- [array_remove_all](#array_remove_all) +- [array_remove_n](#array_remove_n) +- [array_repeat](#array_repeat) +- [array_replace](#array_replace) +- [array_replace_all](#array_replace_all) +- [array_replace_n](#array_replace_n) +- [array_resize](#array_resize) +- [array_reverse](#array_reverse) +- [array_slice](#array_slice) +- [array_sort](#array_sort) +- [array_to_string](#array_to_string) +- [array_union](#array_union) +- [arrays_overlap](#arrays_overlap) +- [cardinality](#cardinality) +- [empty](#empty) +- [flatten](#flatten) +- [generate_series](#generate_series) +- [list_any_value](#list_any_value) +- [list_append](#list_append) +- [list_cat](#list_cat) +- [list_concat](#list_concat) +- [list_contains](#list_contains) +- [list_dims](#list_dims) +- [list_distance](#list_distance) +- [list_distinct](#list_distinct) +- [list_element](#list_element) +- [list_empty](#list_empty) +- [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_max](#list_max) +- [list_ndims](#list_ndims) +- [list_pop_back](#list_pop_back) +- [list_pop_front](#list_pop_front) +- [list_position](#list_position) +- [list_positions](#list_positions) +- [list_prepend](#list_prepend) +- [list_push_back](#list_push_back) +- [list_push_front](#list_push_front) +- [list_remove](#list_remove) +- [list_remove_all](#list_remove_all) +- [list_remove_n](#list_remove_n) +- [list_repeat](#list_repeat) +- [list_replace](#list_replace) +- [list_replace_all](#list_replace_all) +- [list_replace_n](#list_replace_n) +- [list_resize](#list_resize) +- [list_reverse](#list_reverse) +- [list_slice](#list_slice) +- [list_sort](#list_sort) +- [list_to_string](#list_to_string) +- [list_union](#list_union) +- [make_array](#make_array) +- [make_list](#make_list) +- [range](#range) +- [string_to_array](#string_to_array) +- [string_to_list](#string_to_list) + +##### `array_any_value` + +Returns the first non-null element in the array. + +```sql +array_any_value(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select array_any_value([NULL, 1, 2, 3]); ++-------------------------------+ +| array_any_value(List([NULL,1,2,3])) | ++-------------------------------------+ +| 1 | ++-------------------------------------+ +``` + +###### Aliases + +- list_any_value + +##### `array_append` + +Appends an element to the end of an array. + +```sql +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 + +```sql +> select array_append([1, 2, 3], 4); ++--------------------------------------+ +| array_append(List([1,2,3]),Int64(4)) | ++--------------------------------------+ +| [1, 2, 3, 4] | ++--------------------------------------+ +``` + +###### Aliases + +- list_append +- array_push_back +- list_push_back + +##### `array_cat` + +_Alias of [array_concat](#array_concat)._ + +##### `array_concat` + +Concatenates arrays. + +```sql +array_concat(array[, ..., array_n]) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. +- **array_n**: Subsequent array column or literal array to concatenate. + +###### Example + +```sql +> 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_concat +- list_cat + +##### `array_contains` + +_Alias of [array_has](#array_has)._ + +##### `array_dims` + +Returns an array of the array's dimensions. + +```sql +array_dims(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> 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. + +```sql +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 + +```sql +> 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. + +```sql +array_distinct(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> 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. + +```sql +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 + +```sql +> 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_empty` + +_Alias of [empty](#empty)._ + +##### `array_except` + +Returns an array of the elements that appear in the first array but not in the second. + +```sql +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 + +```sql +> 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 + +##### `array_extract` + +_Alias of [array_element](#array_element)._ + +##### `array_has` + +Returns true if the array contains the element. + +```sql +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. + +###### Example + +```sql +> select array_has([1, 2, 3], 2); ++-----------------------------+ +| array_has(List([1,2,3]), 2) | ++-----------------------------+ +| true | ++-----------------------------+ +``` + +###### Aliases + +- list_has +- array_contains +- list_contains + +##### `array_has_all` + +Returns true if all elements of sub-array exist in array. + +```sql +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. + +###### Example + +```sql +> select array_has_all([1, 2, 3, 4], [2, 3]); ++--------------------------------------------+ +| array_has_all(List([1,2,3,4]), List([2,3])) | ++--------------------------------------------+ +| true | ++--------------------------------------------+ +``` + +###### Aliases + +- list_has_all + +##### `array_has_any` + +Returns true if any elements exist in both arrays. + +```sql +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. + +###### Example + +```sql +> select array_has_any([1, 2, 3], [3, 4]); ++------------------------------------------+ +| array_has_any(List([1,2,3]), List([3,4])) | ++------------------------------------------+ +| true | ++------------------------------------------+ +``` + +###### Aliases + +- list_has_any +- arrays_overlap + +##### `array_indexof` + +_Alias of [array_position](#array_position)._ + +##### `array_intersect` + +Returns an array of elements in the intersection of array1 and array2. + +```sql +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 + +```sql +> 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. + +```sql +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 + +```sql +> select array_length([1, 2, 3, 4, 5], 1); ++-------------------------------------------+ +| array_length(List([1,2,3,4,5]), 1) | ++-------------------------------------------+ +| 5 | ++-------------------------------------------+ +``` + +###### Aliases + +- list_length + +##### `array_max` + +Returns the maximum value in the array. + +```sql +array_max(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select array_max([3,1,4,2]); ++-----------------------------------------+ +| array_max(List([3,1,4,2])) | ++-----------------------------------------+ +| 4 | ++-----------------------------------------+ +``` + +###### Aliases + +- list_max + +##### `array_ndims` + +Returns the number of dimensions of the array. + +```sql +array_ndims(array, element) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. +- **element**: Array element. + +###### Example + +```sql +> select array_ndims([[1, 2, 3], [4, 5, 6]]); ++----------------------------------+ +| array_ndims(List([1,2,3,4,5,6])) | ++----------------------------------+ +| 2 | ++----------------------------------+ +``` + +###### Aliases + +- list_ndims + +##### `array_pop_back` + +Returns the array without the last element. + +```sql +array_pop_back(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select array_pop_back([1, 2, 3]); ++-------------------------------+ +| array_pop_back(List([1,2,3])) | ++-------------------------------+ +| [1, 2] | ++-------------------------------+ +``` + +###### Aliases + +- list_pop_back + +##### `array_pop_front` + +Returns the array without the first element. + +```sql +array_pop_front(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select array_pop_front([1, 2, 3]); ++-------------------------------+ +| array_pop_front(List([1,2,3])) | ++-------------------------------+ +| [2, 3] | ++-------------------------------+ +``` + +###### Aliases + +- list_pop_front + +##### `array_position` + +Returns the position of the first occurrence of the specified element in the array. + +```sql +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 + +```sql +> select array_position([1, 2, 2, 3, 1, 4], 2); ++----------------------------------------------+ +| array_position(List([1,2,2,3,1,4]),Int64(2)) | ++----------------------------------------------+ +| 2 | ++----------------------------------------------+ +> select array_position([1, 2, 2, 3, 1, 4], 2, 3); ++----------------------------------------------------+ +| array_position(List([1,2,2,3,1,4]),Int64(2), Int64(3)) | ++----------------------------------------------------+ +| 3 | ++----------------------------------------------------+ +``` + +###### Aliases + +- list_position +- array_indexof +- list_indexof + +##### `array_positions` + +Searches for an element in the array, returns all occurrences. + +```sql +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 position in the array. + +###### Example + +```sql +> 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_prepend` + +Prepends an element to the beginning of an array. + +```sql +array_prepend(element, array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. +- **element**: Element to prepend to the array. + +###### Example + +```sql +> select array_prepend(1, [2, 3, 4]); ++---------------------------------------+ +| array_prepend(Int64(1),List([2,3,4])) | ++---------------------------------------+ +| [1, 2, 3, 4] | ++---------------------------------------+ +``` + +###### Aliases + +- list_prepend +- array_push_front +- list_push_front + +##### `array_push_back` + +_Alias of [array_append](#array_append)._ + +##### `array_push_front` + +_Alias of [array_prepend](#array_prepend)._ + +##### `array_remove` + +Removes the first element from the array equal to the given value. + +```sql +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 + +```sql +> 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_all` + +Removes all elements from the array equal to the given value. + +```sql +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 + +```sql +> 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_remove_n` + +Removes the first `max` elements from the array equal to the given value. + +```sql +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 + +```sql +> 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_repeat` + +Returns an array containing element `count` times. + +```sql +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 + +```sql +> 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_replace` + +Replaces the first occurrence of the specified element with another specified element. + +```sql +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 + +```sql +> 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_all` + +Replaces all occurrences of the specified element with another specified element. + +```sql +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 + +```sql +> 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_replace_n` + +Replaces the first `max` occurrences of the specified element with another specified element. + +```sql +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 + +```sql +> 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_resize` + +Resizes the list to contain size elements. Initializes new elements with value or empty if value is not set. + +```sql +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 + +```sql +> 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_reverse` + +Returns the array with the order of the elements reversed. + +```sql +array_reverse(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> 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. + +```sql +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 + +```sql +> 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_sort` + +Sort array. + +```sql +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 + +```sql +> select array_sort([3, 1, 2]); ++-----------------------------+ +| array_sort(List([3,1,2])) | ++-----------------------------+ +| [1, 2, 3] | ++-----------------------------+ +``` + +###### Aliases + +- list_sort + +##### `array_to_string` + +Converts each element to its text representation. + +```sql +array_to_string(array, delimiter[, null_string]) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. +- **delimiter**: Array element separator. +- **null_string**: Optional. String to replace null values in the array. If not provided, nulls will be handled by default behavior. + +###### Example + +```sql +> 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 + +- list_to_string +- array_join +- list_join + +##### `array_union` + +Returns an array of elements that are present in both arrays (all elements from both arrays) with out duplicates. + +```sql +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 + +```sql +> 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 + +##### `arrays_overlap` + +_Alias of [array_has_any](#array_has_any)._ + +##### `cardinality` + +Returns the total number of elements in the array. + +```sql +cardinality(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> 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. + +```sql +empty(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select empty([1]); ++------------------+ +| empty(List([1])) | ++------------------+ +| 0 | ++------------------+ +``` + +###### Aliases + +- array_empty +- list_empty + +##### `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. + +```sql +flatten(array) +``` + +###### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +###### Example + +```sql +> select flatten([[1, 2], [3, 4]]); ++------------------------------+ +| flatten(List([1,2], [3,4])) | ++------------------------------+ +| [1, 2, 3, 4] | ++------------------------------+ +``` + +##### `generate_series` + +Similar to the range function, but it includes the upper bound. + +```sql +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 + +```sql +> 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_contains` + +_Alias of [array_has](#array_has)._ + +##### `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_except](#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_intersect](#array_intersect)._ + +##### `list_join` + +_Alias of [array_to_string](#array_to_string)._ + +##### `list_length` + +_Alias of [array_length](#array_length)._ + +##### `list_max` + +_Alias of [array_max](#array_max)._ + +##### `list_ndims` + +_Alias of [array_ndims](#array_ndims)._ + +##### `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_prepend` + +_Alias of [array_prepend](#array_prepend)._ + +##### `list_push_back` + +_Alias of [array_append](#array_append)._ + +##### `list_push_front` + +_Alias of [array_prepend](#array_prepend)._ + +##### `list_remove` + +_Alias of [array_remove](#array_remove)._ + +##### `list_remove_all` + +_Alias of [array_remove_all](#array_remove_all)._ + +##### `list_remove_n` + +_Alias of [array_remove_n](#array_remove_n)._ + +##### `list_repeat` + +_Alias of [array_repeat](#array_repeat)._ + +##### `list_replace` + +_Alias of [array_replace](#array_replace)._ + +##### `list_replace_all` + +_Alias of [array_replace_all](#array_replace_all)._ + +##### `list_replace_n` + +_Alias of [array_replace_n](#array_replace_n)._ + +##### `list_resize` + +_Alias of [array_resize](#array_resize)._ + +##### `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 array using the specified input expressions. + +```sql +make_array(expression1[, ..., expression_n]) +``` + +###### 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 + +```sql +> 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)._ + +##### `range` + +Returns an Arrow array between start and stop with step. The range start..end contains all values with `start <= x < end`. It is empty if `start >= end`. Step cannot be 0. + +```sql +range(start, stop, step) +``` + +###### 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 (cannot be 0). Steps less than a day are supported only for timestamp ranges. + +###### Example + +```sql +> select range(2, 10, 3); ++-----------------------------------+ +| range(Int64(2),Int64(10),Int64(3))| ++-----------------------------------+ +| [2, 5, 8] | ++-----------------------------------+ + +> select range(DATE '1992-09-01', DATE '1993-03-01', INTERVAL '1' MONTH); ++--------------------------------------------------------------+ +| range(DATE '1992-09-01', DATE '1993-03-01', INTERVAL '1' MONTH) | ++--------------------------------------------------------------+ +| [1992-09-01, 1992-10-01, 1992-11-01, 1992-12-01, 1993-01-01, 1993-02-01] | ++--------------------------------------------------------------+ +``` + +##### `string_to_array` + +Splits a string into an array of substrings based on a delimiter. Any substrings matching the optional `null_str` argument are replaced with NULL. + +```sql +string_to_array(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`. + +###### Example + +```sql +> select string_to_array('abc##def', '##'); ++-----------------------------------+ +| string_to_array(Utf8('abc##def')) | ++-----------------------------------+ +| ['abc', 'def'] | ++-----------------------------------+ +> select string_to_array('abc def', ' ', 'def'); ++---------------------------------------------+ +| string_to_array(Utf8('abc def'), Utf8(' '), Utf8('def')) | ++---------------------------------------------+ +| ['abc', NULL] | ++---------------------------------------------+ +``` + +###### Aliases + +- string_to_list + +##### `string_to_list` + +_Alias of [string_to_array](#string_to_array)._ + +### Struct Functions + +- [named_struct](#named_struct) +- [row](#row) +- [struct](#struct) + +##### `named_struct` + +Returns an Arrow struct using the specified name and input expressions pairs. + +```sql +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. + +```sql +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 + +### Map Functions + +- [element_at](#element_at) +- [map](#map) +- [map_extract](#map_extract) +- [map_keys](#map_keys) +- [map_values](#map_values) + +##### `element_at` + +_Alias of [map_extract](#map_extract)._ + +##### `map` + +Returns an Arrow map with the specified key-value pairs. + +The `make_map` function creates a map from two lists: one for keys and one for values. Each key must be unique and non-null. + +```sql +map(key, value) +map(key: value) +make_map(['key1', 'key2'], ['value1', 'value2']) +``` + +###### Arguments + +- **key**: For `map`: Expression to be used for key. Can be a constant, column, function, or any combination of arithmetic or string operators. + For `make_map`: The list of keys to be used in the map. Each key must be unique and non-null. +- **value**: For `map`: Expression to be used for value. Can be a constant, column, function, or any combination of arithmetic or string operators. + For `make_map`: The list of values to be mapped to the corresponding keys. + +###### Example + +```sql +-- Using map function +SELECT MAP('type', 'test'); +---- +{type: test} + +SELECT MAP(['POST', 'HEAD', 'PATCH'], [41, 33, null]); +---- +{POST: 41, HEAD: 33, PATCH: NULL} + +SELECT MAP([[1,2], [3,4]], ['a', 'b']); +---- +{[1, 2]: a, [3, 4]: b} + +SELECT MAP { 'a': 1, 'b': 2 }; +---- +{a: 1, b: 2} + +-- Using make_map function +SELECT MAKE_MAP(['POST', 'HEAD'], [41, 33]); +---- +{POST: 41, HEAD: 33} + +SELECT MAKE_MAP(['key1', 'key2'], ['value1', null]); +---- +{key1: value1, key2: } +``` + +##### `map_extract` + +Returns a list containing the value for the given key or an empty list if the key is not present in the map. + +```sql +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 the previously listed. + +###### Example + +```sql +SELECT map_extract(MAP {'a': 1, 'b': NULL, 'c': 3}, 'a'); +---- +[1] + +SELECT map_extract(MAP {1: 'one', 2: 'two'}, 2); +---- +['two'] + +SELECT map_extract(MAP {'x': 10, 'y': NULL, 'z': 30}, 'y'); +---- +[] +``` + +###### Aliases + +- element_at + +##### `map_keys` + +Returns a list of all keys in the map. + +```sql +map_keys(map) +``` + +###### Arguments + +- **map**: Map expression. Can be a constant, column, or function, and any combination of map operators. + +###### Example + +```sql +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` + +Returns a list of all values in the map. + +```sql +map_values(map) +``` + +###### Arguments + +- **map**: Map expression. Can be a constant, column, or function, and any combination of map operators. + +###### Example + +```sql +SELECT map_values(MAP {'a': 1, 'b': NULL, 'c': 3}); +---- +[1, , 3] + +SELECT map_values(map([100, 5], [42, 43])); +---- +[42, 43] +``` + +### 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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +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. + +```sql +sha512(expression) +``` + +###### Arguments + +- **expression**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select sha512('foo'); ++-------------------------------------------+ +| sha512(Utf8("foo")) | ++-------------------------------------------+ +| | ++-------------------------------------------+ +``` + +### Union Functions + +Functions to work with the union data type, also know as tagged unions, variant types, enums or sum types. Note: Not related to the SQL UNION operator + +- [union_extract](#union_extract) +- [union_tag](#union_tag) + +##### `union_extract` + +Returns the value of the given field in the union when selected, or NULL otherwise. + +```sql +union_extract(union, field_name) +``` + +###### Arguments + +- **union**: Union expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **field_name**: String expression to operate on. Must be a constant. + +###### Example + +```sql +❯ select union_column, union_extract(union_column, 'a'), union_extract(union_column, 'b') from table_with_union; ++--------------+----------------------------------+----------------------------------+ +| union_column | union_extract(union_column, 'a') | union_extract(union_column, 'b') | ++--------------+----------------------------------+----------------------------------+ +| {a=1} | 1 | | +| {b=3.0} | | 3.0 | +| {a=4} | 4 | | +| {b=} | | | +| {a=} | | | ++--------------+----------------------------------+----------------------------------+ +``` + +##### `union_tag` + +Returns the name of the currently selected field in the union + +```sql +union_tag(union_expression) +``` + +###### Arguments + +- **union**: Union expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +❯ select union_column, union_tag(union_column) from table_with_union; ++--------------+-------------------------+ +| union_column | union_tag(union_column) | ++--------------+-------------------------+ +| {a=1} | a | +| {b=3.0} | b | +| {a=4} | a | +| {b=} | b | +| {a=} | a | ++--------------+-------------------------+ +``` + +### 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. + +```sql +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. + +```sql +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')`. + +```sql +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. + +```sql +version() +``` + +###### Example + +```sql +> select version(); ++--------------------------------------------+ +| version() | ++--------------------------------------------+ +| Apache DataFusion 42.0.0, aarch64 on macos | ++--------------------------------------------+ +``` +404: Not Found + + + + +## Aggregate Functions + +Aggregate functions operate on a set of values to compute a single result. + +### General Functions + +- [array_agg](#array_agg) +- [avg](#avg) +- [bit_and](#bit_and) +- [bit_or](#bit_or) +- [bit_xor](#bit_xor) +- [bool_and](#bool_and) +- [bool_or](#bool_or) +- [count](#count) +- [first_value](#first_value) +- [grouping](#grouping) +- [last_value](#last_value) +- [max](#max) +- [mean](#mean) +- [median](#median) +- [min](#min) +- [string_agg](#string_agg) +- [sum](#sum) +- [var](#var) +- [var_pop](#var_pop) +- [var_population](#var_population) +- [var_samp](#var_samp) +- [var_sample](#var_sample) + +##### `array_agg` + +Returns an array created from the expression elements. If ordering is required, elements are inserted in the specified order. +This aggregation function can only mix DISTINCT and ORDER BY if the ordering expression is exactly the same as the argument expression. + +```sql +array_agg(expression [ORDER BY expression]) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT array_agg(column_name ORDER BY other_column) FROM table_name; ++-----------------------------------------------+ +| array_agg(column_name ORDER BY other_column) | ++-----------------------------------------------+ +| [element1, element2, element3] | ++-----------------------------------------------+ +> SELECT array_agg(DISTINCT column_name ORDER BY column_name) FROM table_name; ++--------------------------------------------------------+ +| array_agg(DISTINCT column_name ORDER BY column_name) | ++--------------------------------------------------------+ +| [element1, element2, element3] | ++--------------------------------------------------------+ +``` + +##### `avg` + +Returns the average of numeric values in the specified column. + +```sql +avg(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT avg(column_name) FROM table_name; ++---------------------------+ +| avg(column_name) | ++---------------------------+ +| 42.75 | ++---------------------------+ +``` + +###### Aliases + +- mean + +##### `bit_and` + +Computes the bitwise AND of all non-null input values. + +```sql +bit_and(expression) +``` + +###### Arguments + +- **expression**: Integer expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `bit_or` + +Computes the bitwise OR of all non-null input values. + +```sql +bit_or(expression) +``` + +###### Arguments + +- **expression**: Integer expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `bit_xor` + +Computes the bitwise exclusive OR of all non-null input values. + +```sql +bit_xor(expression) +``` + +###### Arguments + +- **expression**: Integer expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `bool_and` + +Returns true if all non-null input values are true, otherwise false. + +```sql +bool_and(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT bool_and(column_name) FROM table_name; ++----------------------------+ +| bool_and(column_name) | ++----------------------------+ +| true | ++----------------------------+ +``` + +##### `bool_or` + +Returns true if all non-null input values are true, otherwise false. + +```sql +bool_and(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT bool_and(column_name) FROM table_name; ++----------------------------+ +| bool_and(column_name) | ++----------------------------+ +| true | ++----------------------------+ +``` + +##### `count` + +Returns the number of non-null values in the specified column. To include null values in the total count, use `count(*)`. + +```sql +count(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT count(column_name) FROM table_name; ++-----------------------+ +| count(column_name) | ++-----------------------+ +| 100 | ++-----------------------+ + +> SELECT count(*) FROM table_name; ++------------------+ +| count(*) | ++------------------+ +| 120 | ++------------------+ +``` + +##### `first_value` + +Returns the first element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group. + +```sql +first_value(expression [ORDER BY expression]) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT first_value(column_name ORDER BY other_column) FROM table_name; ++-----------------------------------------------+ +| first_value(column_name ORDER BY other_column)| ++-----------------------------------------------+ +| first_element | ++-----------------------------------------------+ +``` + +##### `grouping` + +Returns 1 if the data is aggregated across the specified column, or 0 if it is not aggregated in the result set. + +```sql +grouping(expression) +``` + +###### Arguments + +- **expression**: Expression to evaluate whether data is aggregated across the specified column. Can be a constant, column, or function. + +###### Example + +```sql +> SELECT column_name, GROUPING(column_name) AS group_column + FROM table_name + GROUP BY GROUPING SETS ((column_name), ()); ++-------------+-------------+ +| column_name | group_column | ++-------------+-------------+ +| value1 | 0 | +| value2 | 0 | +| NULL | 1 | ++-------------+-------------+ +``` + +##### `last_value` + +Returns the last element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group. + +```sql +last_value(expression [ORDER BY expression]) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT last_value(column_name ORDER BY other_column) FROM table_name; ++-----------------------------------------------+ +| last_value(column_name ORDER BY other_column) | ++-----------------------------------------------+ +| last_element | ++-----------------------------------------------+ +``` + +##### `max` + +Returns the maximum value in the specified column. + +```sql +max(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT max(column_name) FROM table_name; ++----------------------+ +| max(column_name) | ++----------------------+ +| 150 | ++----------------------+ +``` + +##### `mean` + +_Alias of [avg](#avg)._ + +##### `median` + +Returns the median value in the specified column. + +```sql +median(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT median(column_name) FROM table_name; ++----------------------+ +| median(column_name) | ++----------------------+ +| 45.5 | ++----------------------+ +``` + +##### `min` + +Returns the minimum value in the specified column. + +```sql +min(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT min(column_name) FROM table_name; ++----------------------+ +| min(column_name) | ++----------------------+ +| 12 | ++----------------------+ +``` + +##### `string_agg` + +Concatenates the values of string expressions and places separator values between them. If ordering is required, strings are concatenated in the specified order. This aggregation function can only mix DISTINCT and ORDER BY if the ordering expression is exactly the same as the first argument expression. + +```sql +string_agg([DISTINCT] expression, delimiter [ORDER BY expression]) +``` + +###### Arguments + +- **expression**: The string expression to concatenate. Can be a column or any valid string expression. +- **delimiter**: A literal string used as a separator between the concatenated values. + +###### Example + +```sql +> SELECT string_agg(name, ', ') AS names_list + FROM employee; ++--------------------------+ +| names_list | ++--------------------------+ +| Alice, Bob, Bob, Charlie | ++--------------------------+ +> SELECT string_agg(name, ', ' ORDER BY name DESC) AS names_list + FROM employee; ++--------------------------+ +| names_list | ++--------------------------+ +| Charlie, Bob, Bob, Alice | ++--------------------------+ +> SELECT string_agg(DISTINCT name, ', ' ORDER BY name DESC) AS names_list + FROM employee; ++--------------------------+ +| names_list | ++--------------------------+ +| Charlie, Bob, Alice | ++--------------------------+ +``` + +##### `sum` + +Returns the sum of all values in the specified column. + +```sql +sum(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT sum(column_name) FROM table_name; ++-----------------------+ +| sum(column_name) | ++-----------------------+ +| 12345 | ++-----------------------+ +``` + +##### `var` + +Returns the statistical sample variance of a set of numbers. + +```sql +var(expression) +``` + +###### Arguments + +- **expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Aliases + +- var_sample +- var_samp + +##### `var_pop` + +Returns the statistical population variance of a set of numbers. + +```sql +var_pop(expression) +``` + +###### Arguments + +- **expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Aliases + +- var_population + +##### `var_population` + +_Alias of [var_pop](#var_pop)._ + +##### `var_samp` + +_Alias of [var](#var)._ + +##### `var_sample` + +_Alias of [var](#var)._ + +### Statistical Functions + +- [corr](#corr) +- [covar](#covar) +- [covar_pop](#covar_pop) +- [covar_samp](#covar_samp) +- [nth_value](#nth_value) +- [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_sxy](#regr_sxy) +- [regr_syy](#regr_syy) +- [stddev](#stddev) +- [stddev_pop](#stddev_pop) +- [stddev_samp](#stddev_samp) + +##### `corr` + +Returns the coefficient of correlation between two numeric values. + +```sql +corr(expression1, expression2) +``` + +###### Arguments + +- **expression1**: First expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression2**: Second expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT corr(column1, column2) FROM table_name; ++--------------------------------+ +| corr(column1, column2) | ++--------------------------------+ +| 0.85 | ++--------------------------------+ +``` + +##### `covar` + +_Alias of [covar_samp](#covar_samp)._ + +##### `covar_pop` + +Returns the sample covariance of a set of number pairs. + +```sql +covar_samp(expression1, expression2) +``` + +###### Arguments + +- **expression1**: First expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression2**: Second expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT covar_samp(column1, column2) FROM table_name; ++-----------------------------------+ +| covar_samp(column1, column2) | ++-----------------------------------+ +| 8.25 | ++-----------------------------------+ +``` + +##### `covar_samp` + +Returns the sample covariance of a set of number pairs. + +```sql +covar_samp(expression1, expression2) +``` + +###### Arguments + +- **expression1**: First expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression2**: Second expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT covar_samp(column1, column2) FROM table_name; ++-----------------------------------+ +| covar_samp(column1, column2) | ++-----------------------------------+ +| 8.25 | ++-----------------------------------+ +``` + +###### Aliases + +- covar + +##### `nth_value` + +Returns the nth value in a group of values. + +```sql +nth_value(expression, n ORDER BY expression) +``` + +###### Arguments + +- **expression**: The column or expression to retrieve the nth value from. +- **n**: The position (nth) of the value to retrieve, based on the ordering. + +###### Example + +```sql +> SELECT dept_id, salary, NTH_VALUE(salary, 2) OVER (PARTITION BY dept_id ORDER BY salary ASC) AS second_salary_by_dept + FROM employee; ++---------+--------+-------------------------+ +| dept_id | salary | second_salary_by_dept | ++---------+--------+-------------------------+ +| 1 | 30000 | NULL | +| 1 | 40000 | 40000 | +| 1 | 50000 | 40000 | +| 2 | 35000 | NULL | +| 2 | 45000 | 45000 | ++---------+--------+-------------------------+ +``` + +##### `regr_avgx` + +Computes the average of the independent variable (input) expression_x for the non-null paired data points. + +```sql +regr_avgx(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_avgy` + +Computes the average of the dependent variable (output) expression_y for the non-null paired data points. + +```sql +regr_avgy(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_count` + +Counts the number of non-null paired data points. + +```sql +regr_count(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_intercept` + +Computes the y-intercept of the linear regression line. For the equation (y = kx + b), this function returns b. + +```sql +regr_intercept(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_r2` + +Computes the square of the correlation coefficient between the independent and dependent variables. + +```sql +regr_r2(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of 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. + +```sql +regr_slope(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_sxx` + +Computes the sum of squares of the independent variable. + +```sql +regr_sxx(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_sxy` + +Computes the sum of products of paired data points. + +```sql +regr_sxy(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `regr_syy` + +Computes the sum of squares of the dependent variable. + +```sql +regr_syy(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **expression_x**: Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators. + +##### `stddev` + +Returns the standard deviation of a set of numbers. + +```sql +stddev(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT stddev(column_name) FROM table_name; ++----------------------+ +| stddev(column_name) | ++----------------------+ +| 12.34 | ++----------------------+ +``` + +###### Aliases + +- stddev_samp + +##### `stddev_pop` + +Returns the population standard deviation of a set of numbers. + +```sql +stddev_pop(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT stddev_pop(column_name) FROM table_name; ++--------------------------+ +| stddev_pop(column_name) | ++--------------------------+ +| 10.56 | ++--------------------------+ +``` + +##### `stddev_samp` + +_Alias of [stddev](#stddev)._ + +### Approximate Functions + +- [approx_distinct](#approx_distinct) +- [approx_median](#approx_median) +- [approx_percentile_cont](#approx_percentile_cont) +- [approx_percentile_cont_with_weight](#approx_percentile_cont_with_weight) + +##### `approx_distinct` + +Returns the approximate number of distinct input values calculated using the HyperLogLog algorithm. + +```sql +approx_distinct(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT approx_distinct(column_name) FROM table_name; ++-----------------------------------+ +| approx_distinct(column_name) | ++-----------------------------------+ +| 42 | ++-----------------------------------+ +``` + +##### `approx_median` + +Returns the approximate median (50th percentile) of input values. It is an alias of `approx_percentile_cont(0.5) WITHIN GROUP (ORDER BY x)`. + +```sql +approx_median(expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> SELECT approx_median(column_name) FROM table_name; ++-----------------------------------+ +| approx_median(column_name) | ++-----------------------------------+ +| 23.5 | ++-----------------------------------+ +``` + +##### `approx_percentile_cont` + +Returns the approximate percentile of input values using the t-digest algorithm. + +```sql +approx_percentile_cont(percentile, centroids) WITHIN GROUP (ORDER BY expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **percentile**: Percentile to compute. Must be a float value between 0 and 1 (inclusive). +- **centroids**: Number of centroids to use in the t-digest algorithm. _Default is 100_. A higher number results in more accurate approximation but requires more memory. + +###### Example + +```sql +> SELECT approx_percentile_cont(0.75, 100) WITHIN GROUP (ORDER BY column_name) FROM table_name; ++-----------------------------------------------------------------------+ +| approx_percentile_cont(0.75, 100) WITHIN GROUP (ORDER BY column_name) | ++-----------------------------------------------------------------------+ +| 65.0 | ++-----------------------------------------------------------------------+ +``` + +##### `approx_percentile_cont_with_weight` + +Returns the weighted approximate percentile of input values using the t-digest algorithm. + +```sql +approx_percentile_cont_with_weight(weight, percentile) WITHIN GROUP (ORDER BY expression) +``` + +###### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **weight**: Expression to use as weight. Can be a constant, column, or function, and any combination of arithmetic operators. +- **percentile**: Percentile to compute. Must be a float value between 0 and 1 (inclusive). + +###### Example + +```sql +> SELECT approx_percentile_cont_with_weight(weight_column, 0.90) WITHIN GROUP (ORDER BY column_name) FROM table_name; ++---------------------------------------------------------------------------------------------+ +| approx_percentile_cont_with_weight(weight_column, 0.90) WITHIN GROUP (ORDER BY column_name) | ++---------------------------------------------------------------------------------------------+ +| 78.5 | ++---------------------------------------------------------------------------------------------+ +``` + + + + +## Window Functions + +A _window function_ performs a calculation across a set of table rows that are somehow related to the current row. +This is 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 + +```sql +function([expr]) + OVER( + [PARTITION BY expr[, …]] + [ORDER BY expr [ ASC | DESC ][, …]] + [ frame_clause ] + ) +``` + +where **frame_clause** is one of: + +```sql + { 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 + +- [cume_dist](#cume_dist) +- [dense_rank](#dense_rank) +- [ntile](#ntile) +- [percent_rank](#percent_rank) +- [rank](#rank) +- [row_number](#row_number) + +##### `cume_dist` + +Relative rank of the current row: (number of rows preceding or peer with the current row) / (total rows). + +```sql +cume_dist() +``` + +###### Example + +```sql + --Example usage of the cume_dist window function: + SELECT salary, + cume_dist() OVER (ORDER BY salary) AS cume_dist + FROM employees; +``` + +```sql ++--------+-----------+ +| salary | cume_dist | ++--------+-----------+ +| 30000 | 0.33 | +| 50000 | 0.67 | +| 70000 | 1.00 | ++--------+-----------+ +``` + +##### `dense_rank` + +Returns the rank of the current row without gaps. This function ranks rows in a dense manner, meaning consecutive ranks are assigned even for identical values. + +```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 + +##### `percent_rank` + +Returns the percentage rank of the current row within its partition. The value ranges from 0 to 1 and is computed as `(rank - 1) / (total_rows - 1)`. + +```sql +percent_rank() +``` + +##### `rank` + +Returns the rank of the current row within its partition, allowing gaps between ranks. This function provides a ranking similar to `row_number`, but skips ranks for identical values. + +```sql +rank() +``` + +##### `row_number` + +Number of the current row within its partition, counting from 1. + +```sql +row_number() +``` + +### Analytical Functions + +- [first_value](#first_value) +- [lag](#lag) +- [last_value](#last_value) +- [lead](#lead) +- [nth_value](#nth_value) + +##### `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 + +##### `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). + +```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. + +##### `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 + +##### `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). + +```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. + +##### `nth_value` + +Returns the value evaluated at the nth row of the window frame (counting from 1). Returns NULL if no such row exists. + +```sql +nth_value(expression, n) +``` + +###### Arguments + +- **expression**: The column from which to retrieve the nth value. +- **n**: Integer. Specifies the row number (starting from 1) in the window frame. + +###### Example + +```sql +-- Sample employees table: +CREATE TABLE employees (id INT, salary INT); +INSERT INTO employees (id, salary) VALUES +(1, 30000), +(2, 40000), +(3, 50000), +(4, 60000), +(5, 70000); + +-- Example usage of nth_value: +SELECT nth_value(salary, 2) OVER ( + ORDER BY salary + ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW +) AS nth_value +FROM employees; +``` + +```text ++-----------+ +| nth_value | ++-----------+ +| 40000 | +| 40000 | +| 40000 | +| 40000 | +| 40000 | ++-----------+ +``` diff --git a/versioned_docs/version-1.0/reference/sql/functions/geo.md b/versioned_docs/version-1.0/reference/sql/functions/geo.md new file mode 100644 index 0000000000..9e593db944 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/functions/geo.md @@ -0,0 +1,456 @@ +--- +keywords: [geospatial functions, geo types, geohash, H3, spatial measurement] +description: Lists all geospatial related functions in GreptimeDB, including their usage, examples, and details on geospatial types, geohash, H3, S2, and encodings. +--- + +import TOCInline from '@theme/TOCInline'; + +# Geospatial Functions + +This page lists all geospatial related functions in GreptimeDB. These functions +are enabled when you have `common-function/geo` feature turned on (default: on). + + + +## Geo Types + +Convert data between geospatial types. + +### `wkt_point_from_latlng` + +Convert latitude and longitude to WKT point. + +```sql +SELECT wkt_point_from_latlng(37.76938, -122.3889) AS point; +``` + +## Geohash + +See [more about geohash encoding +algorithms](https://en.wikipedia.org/wiki/Geohash). + +### `geohash` + +Get geohash encoded string from latitude, longitude and resolution. + +```sql +SELECT geohash(37.76938, -122.3889, 11); +``` + +### `geohash_neighbours` + +Get all geohash neighbours for given coordinate and resolution. + +Note that this function returns a String array and it only works on our HTTP +Query API and Postgres channel. + +```sql +SELECT geohash_neighbours(37.76938, -122.3889, 11); +``` + +## H3 + +H3 is a geospatial index algorithm. See [more about h3 +encoding](https://h3geo.org/). + +### `h3_latlng_to_cell` + +Encode coordinate (latitude, longitude) into h3 index at given +resolution. Returns UInt64 representation of the cell. + +```sql +SELECT h3_latlng_to_cell(37.76938, -122.3889, 1); +``` + +### `h3_latlng_to_cell_string` + +Similar to `h3_latlng_to_cell` but returns hex encoding of the cell. + +```sql +h3_latlng_to_cell_string(37.76938, -122.3889, 1); +``` + +### `h3_cell_to_string` + +Convert cell index (UInt64) to its string representation. + +```sql +SELECT h3_cell_to_string(h3_latlng_to_cell(37.76938, -122.3889, 8)); +``` + +### `h3_string_to_cell` + +Convert hex-encoded cell ID to its UInt64 form + +```sql +h3_string_to_cell(h3_latlng_to_cell_string(37.76938, -122.3889, 8::UInt64)); +``` + +### `h3_cell_center_latlng` + +Returns cell centroid as latitude and longitude. + +Note that this function returns a Float array and it only works on our HTTP +Query API and Postgres channel. + +```sql +SELECT h3_cell_center_latlng(h3_latlng_to_cell(37.76938, -122.3889, 8)); +``` + +### `h3_cell_resolution` + +Returns resolution for given cell. + +```sql +SELECT h3_cell_resolution(h3_latlng_to_cell(37.76938, -122.3889, 8)); +``` + +### `h3_cell_base` + +Returns the base cell of given cell. + +```sql +SELECT h3_cell_base(h3_latlng_to_cell(37.76938, -122.3889, 8)); +``` + +### `h3_cell_is_pentagon` + +Returns true if cell is a pentagon. + +```sql +SELECT h3_cell_is_pentagon(h3_latlng_to_cell(37.76938, -122.3889, 8)); +``` + +### `h3_cell_parent` + +Returns parent cell at given resolution. + +```sql +h3_cell_parent(h3_latlng_to_cell(37.76938, -122.3889, 8), 6); +``` + +### `h3_cell_to_children` + +Returns children cells at given resolution. + +Note that this function returns a UInt64 array and it only works on our HTTP +Query API and Postgres channel. + +```sql +h3_cell_to_children(h3_latlng_to_cell(37.76938, -122.3889, 8), 10); +``` + +### `h3_cell_to_children_size` + +Returns cell children count at given resolution. + +```sql +h3_cell_to_children_size(h3_latlng_to_cell(37.76938, -122.3889, 8), 10); +``` + +### `h3_cell_to_child_pos` + +Return the child position for its parent at given resolution. Position is the +index of child in its children. + +```sql +h3_cell_to_child_pos(h3_latlng_to_cell(37.76938, -122.3889, 8), 6) +``` + +### `h3_child_pos_to_cell` + +Returns the cell at given position of the parent at given resolution. + +Arguments: + +- position +- cell index +- resolution + +```sql +h3_child_pos_to_cell(25, h3_latlng_to_cell(37.76938, -122.3889, 8), 11); +``` + +### `h3_cells_contains` + +Return true if given cells contains cell, or cell's parent. + +Arguments: + +- cell set: it can be int64/uint64/string array, and comma-separated string cell + ID. +- cell index: the cell to test + +```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` + +Returns cells with k distances of given cell. + +Note that this function returns a UInt64 array and it only works on our HTTP +Query API and Postgres channel. + +```sql +h3_grid_disk(h3_latlng_to_cell(37.76938, -122.3889, 8), 3); +``` + +### `h3_grid_disk_distances` + +Returns all cells **within** k distances of given cell. + +Note that this function returns a UInt64 array and it only works on our HTTP +Query API and Postgres channel. + +```sql +h3_grid_disk_distance(h3_latlng_to_cell(37.76938, -122.3889, 8), 3); +``` + +### `h3_grid_distance` + +Returns distance between two cells. + +```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` + +Returns path cells between two cells. Note that this function can fail if two +cells are very far apart. + +```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` + +Returns sphere distance between centroid of two cells, in 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` + +Returns euclidean distance between centroid of two cells, in 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 + +Learn [more about S2 encoding](http://s2geometry.io/). + +### `s2_latlng_to_cell` + +Returns s2 cell index of given coordinate. + +```sql +SELECT s2_latlng_to_cell(37.76938, -122.3889); +``` + +### `s2_cell_to_token` + +Returns string representation of given cell. + +```sql +SELECT s2_cell_to_token(s2_latlng_to_cell(37.76938, -122.3889)); +``` + +### `s2_cell_level` + +Returns s2 level of given cell. + +```sql +SELECT s2_cell_level(s2_latlng_to_cell(37.76938, -122.3889)); +``` + +### `s2_cell_parent` + +Returns parent of given cell at level. + +```sql +SELECT s2_cell_parent(s2_latlng_to_cell(37.76938, -122.3889), 3); +``` + +## Encodings + +### `json_encode_path` + +Encode rows of latitude, longitude in a JSON array, sorted by timestamp. + +Arguments: + +- latitude +- longitude +- timestamp + +Returns a JSON array in string type. Note that the sequence in result coordinate +is [longitude, latitude] to align with GeoJSON spec. + +```sql +SELECT json_encode_path(lat, lon, ts); +``` + +Example output: + +```json +[[-122.3888,37.77001],[-122.3839,37.76928],[-122.3889,37.76938],[-122.382,37.7693]] +``` + +## Spatial Relation + +### `st_contains` + +Test spatial relationship between two objects: contains. + +Arguments: two spatial objects encoded with 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` + +Test spatial relationship between two objects: within. + +Arguments: two spatial objects encoded with 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` + +Test spatial relationship between two objects: intersects. + +Arguments: two spatial objects encoded with 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` + +Returns WGS84(SRID: 4326) euclidean distance between two geometry object, in +degree. + +Arguments: two spatial objects encoded with 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` + +Return great circle distance between two point, in meters. + +Arguments: two spatial objects encoded with 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` + +Returns area of given geometry object. + +Arguments: the spatial object encoded with 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/versioned_docs/version-1.0/reference/sql/functions/ip.md b/versioned_docs/version-1.0/reference/sql/functions/ip.md new file mode 100644 index 0000000000..1a0af99a45 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/functions/ip.md @@ -0,0 +1,257 @@ +--- +keywords: ["IP", "IPv4", "IPv6", "CIDR", "address", "network", "range", "conversion", "manipulation", "SQL", "functions"] +description: Documentation for SQL functions related to IP address manipulation, conversion between string/numeric formats, CIDR notation, and range checking for both IPv4 and IPv6. +--- + +import TOCInline from '@theme/TOCInline'; + +# IP Functions + + + +This document describes the IP address manipulation and comparison functions available. + +### `ipv4_to_cidr(ip_string [, subnet_mask])` + +**Description:** + +Converts an IPv4 address string to CIDR notation. If a `subnet_mask` (UInt8, 0-32) is provided, it uses that mask. Otherwise, it automatically detects the subnet based on trailing zeros or the number of octets provided in the input string (e.g., '192.168' implies /16, '192' implies /8). The resulting IP address in the CIDR notation will have host bits zeroed out according to the mask. + +**Arguments:** + +* `ip_string`: String - The IPv4 address string (e.g., '192.168.1.1', '10.0.0.0', '172.16'). Partial addresses are completed with zeros. +* `subnet_mask` (Optional): UInt8 - The desired subnet mask length (e.g., 24, 16, 8). + +**Return Type:** + +String - The IPv4 address in CIDR notation (e.g., '192.168.1.0/24'). Returns NULL for invalid inputs. + +**Examples:** + +```sql +-- Auto-detect subnet +SELECT ipv4_to_cidr('192.168.1.0'); +-- Output: '192.168.1.0/24' + +SELECT ipv4_to_cidr('172.16'); +-- Output: '172.16.0.0/16' + +-- Explicit subnet mask +SELECT ipv4_to_cidr('192.168.1.1', 24); +-- Output: '192.168.1.0/24' + +SELECT ipv4_to_cidr('10.0.0.1', 16); +-- Output: '10.0.0.0/16' +``` + +### `ipv6_to_cidr(ip_string [, subnet_mask])` + +**Description:** + +Converts an IPv6 address string to CIDR notation. If a `subnet_mask` (UInt8, 0-128) is provided, it uses that mask. Otherwise, it attempts to automatically detect the subnet based on trailing zero segments or common prefixes (like `fe80::` for /16 or `2001:db8::` for /32). The resulting IP address in the CIDR notation will have host bits zeroed out according to the mask. + +**Arguments:** + +* `ip_string`: String - The IPv6 address string (e.g., '2001:db8::1', 'fe80::'). Partial addresses are completed if possible (e.g., '2001:db8' becomes '2001:db8::'). +* `subnet_mask` (Optional): UInt8 - The desired subnet mask length (e.g., 48, 64, 128). + +**Return Type:** + +String - The IPv6 address in CIDR notation (e.g., '2001:db8::/32'). Returns NULL for invalid inputs. + +**Examples:** + +```sql +-- Auto-detect subnet +SELECT ipv6_to_cidr('2001:db8::'); +-- Output: '2001:db8::/32' + +SELECT ipv6_to_cidr('fe80::1'); +-- Output: 'fe80::/16' + +SELECT ipv6_to_cidr('::1'); +-- Output: '::1/128' + +-- Explicit subnet mask +SELECT ipv6_to_cidr('2001:db8::', 48); +-- Output: '2001:db8::/48' + +SELECT ipv6_to_cidr('fe80::1', 10); +-- Output: 'fe80::/10' +``` + +### `ipv4_num_to_string(ip_number)` + +**Description:** + +Converts a UInt32 number to an IPv4 address string in the standard A.B.C.D format. The number is interpreted as an IPv4 address in big-endian byte order. + +**Arguments:** + +* `ip_number`: UInt32 - The numeric representation of the IPv4 address. + +**Return Type:** + +String - The IPv4 address in dot-decimal notation (e.g., '192.168.0.1'). + +**Examples:** + +```sql +SELECT ipv4_num_to_string(3232235521); -- 0xC0A80001 +-- Output: '192.168.0.1' + +SELECT ipv4_num_to_string(167772161); -- 0x0A000001 +-- Output: '10.0.0.1' + +SELECT ipv4_num_to_string(0); +-- Output: '0.0.0.0' +``` + +### `ipv4_string_to_num(ip_string)` + +**Description:** + +Converts a string representation of an IPv4 address (A.B.C.D format) to its UInt32 numeric equivalent (big-endian). + +**Arguments:** + +* `ip_string`: String - The IPv4 address in dot-decimal notation. + +**Return Type:** + +UInt32 - The numeric representation of the IPv4 address. Returns NULL or throws an error for invalid input formats. + +**Examples:** + +```sql +SELECT ipv4_string_to_num('192.168.0.1'); +-- Output: 3232235521 + +SELECT ipv4_string_to_num('10.0.0.1'); +-- Output: 167772161 + +SELECT ipv4_string_to_num('0.0.0.0'); +-- Output: 0 +``` + +### `ipv6_num_to_string(hex_string)` + +**Description:** + +Converts a 32-character hexadecimal string representation of an IPv6 address to its standard formatted string representation (e.g., '2001:db8::1'). Handles IPv4-mapped IPv6 addresses correctly (e.g., '::ffff:192.168.0.1'). Case-insensitive for hex characters. + +**Arguments:** + +* `hex_string`: String - A 32-character hexadecimal string representing the 16 bytes of an IPv6 address. + +**Return Type:** + +String - The formatted IPv6 address string. Returns NULL or throws an error if the input is not a valid 32-character hex string. + +**Examples:** + +```sql +SELECT ipv6_num_to_string('20010db8000000000000000000000001'); +-- Output: '2001:db8::1' + +SELECT ipv6_num_to_string('00000000000000000000ffffc0a80001'); +-- Output: '::ffff:192.168.0.1' +``` + +### `ipv6_string_to_num(ip_string)` + +**Description:** + +Converts a string representation of an IPv6 address (standard format) or an IPv4 address (dot-decimal format) to its 16-byte binary representation. If an IPv4 address string is provided, it is converted to its IPv6-mapped equivalent (e.g., '192.168.0.1' becomes '::ffff:192.168.0.1' internally before conversion to binary). + +**Arguments:** + +* `ip_string`: String - The IPv6 or IPv4 address string. + +**Return Type:** + +Binary - The 16-byte binary representation of the IPv6 address. Returns NULL or throws an error for invalid input formats. + +**Examples:** + +```sql +-- IPv6 input +SELECT ipv6_string_to_num('2001:db8::1'); +-- Output: Binary representation of 2001:db8::1 + +-- IPv4 input (gets mapped to IPv6) +SELECT ipv6_string_to_num('192.168.0.1'); +-- Output: Binary representation of ::ffff:192.168.0.1 + +-- IPv4-mapped IPv6 input +SELECT ipv6_string_to_num('::ffff:192.168.0.1'); +-- Output: Binary representation of ::ffff:192.168.0.1 +``` + +### `ipv4_in_range(ip_string, cidr_string)` + +**Description:** + +Checks if a given IPv4 address string falls within a specified CIDR range string. + +**Arguments:** + +* `ip_string`: String - The IPv4 address to check (e.g., '192.168.1.5'). +* `cidr_string`: String - The CIDR range to check against (e.g., '192.168.1.0/24'). + +**Return Type:** + +Boolean - `true` if the IP address is within the range, `false` otherwise. Returns NULL or throws an error for invalid inputs. + +**Examples:** + +```sql +SELECT ipv4_in_range('192.168.1.5', '192.168.1.0/24'); +-- Output: true + +SELECT ipv4_in_range('192.168.2.1', '192.168.1.0/24'); +-- Output: false + +SELECT ipv4_in_range('10.0.0.1', '10.0.0.0/8'); +-- Output: true + +SELECT ipv4_in_range('8.8.8.8', '0.0.0.0/0'); -- /0 matches everything +-- Output: true + +SELECT ipv4_in_range('192.168.1.1', '192.168.1.1/32'); -- /32 is an exact match +-- Output: true +``` + +### `ipv6_in_range(ip_string, cidr_string)` + +**Description:** + +Checks if a given IPv6 address string falls within a specified CIDR range string. + +**Arguments:** + +* `ip_string`: String - The IPv6 address to check (e.g., '2001:db8::1'). +* `cidr_string`: String - The CIDR range to check against (e.g., '2001:db8::/32'). + +**Return Type:** + +Boolean - `true` if the IP address is within the range, `false` otherwise. Returns NULL or throws an error for invalid inputs. + +**Examples:** + +```sql +SELECT ipv6_in_range('2001:db8::1', '2001:db8::/32'); +-- Output: true + +SELECT ipv6_in_range('2001:db8:1::', '2001:db8::/32'); +-- Output: true + +SELECT ipv6_in_range('2001:db9::1', '2001:db8::/32'); +-- Output: false + +SELECT ipv6_in_range('::1', '::1/128'); +-- Output: true + +SELECT ipv6_in_range('fe80::1', 'fe80::/16'); +-- Output: true +``` diff --git a/versioned_docs/version-1.0/reference/sql/functions/json.md b/versioned_docs/version-1.0/reference/sql/functions/json.md new file mode 100644 index 0000000000..4e720ce1d9 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/functions/json.md @@ -0,0 +1,128 @@ +--- +keywords: [JSON functions, JSON conversion, JSON extraction, JSON validation, SQL functions] +description: Lists and describes JSON functions available in GreptimeDB, including their usage and examples. +--- + +# JSON Functions (Experimental) + +This page lists all json type related functions in GreptimeDB. + +:::warning +The JSON feature is currently experimental and may change in future releases. +::: + +## Conversion + +Conversion between JSON and other types. + +* `parse_json(string)` to parse a JSON string into a JSON value. Illegal JSON strings will return an error. +* `json_to_string(json)` to convert a JSON value to a string. + +```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} | ++----------------------------------------------------------+ +``` + +## Extraction + +Extracts values with specific types from JSON values through specific paths. + +* `json_get_bool(json, path)` to extract a boolean value from a JSON value by the path. +* `json_get_int(json, path)` to extract an integer value from a JSON value by the path, while boolean values will be converted to integers. +* `json_get_float(json, path)` to extract a float value from a JSON value by the path, while integer and boolean values will be converted to floats. +* `json_get_string(json, path)` to extract a string value from a JSON value by the path. All valid JSON values will be converted to strings, including null values, objects and arrays. + +`path` is a string that select and extract elements from a json value. The following operators in the path are supported: + +| Operator | Description | Examples | +| ------------------------ | ------------------------------------------------------------ | ------------------ | +| `$` | The root element | `$` | +| `@` | The current element in the filter expression | `$.event?(@ == 1)` | +| `.*` | Selecting all elements in an Object | `$.*` | +| `.` | Selecting element that match the name in an Object | `$.event` | +| `:` | Alias of `.` | `$:event` | +| `[""]` | Alias of `.` | `$["event"]` | +| `[*]` | Selecting all elements in an Array | `$[*]` | +| `[, ..]` | Selecting 0-based `n-th` elements in an Array | `$[1, 2]` | +| `[last - , ..]` | Selecting `n-th` element before the last element in an Array | `$[0, last - 1]` | +| `[ to , ..]` | Selecting all elements of a range in an Array | `$[1 to last - 2]` | +| `?()` | Selecting all elements that matched the filter expression | `$?(@.price < 10)` | + +If the path is invalid, the function will return a NULL value. + +```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 | ++-----------------------------------------------------------------------+ +``` + +## Validation + +Check the type of a JSON value. + +* `json_is_null(json)` to check whether a JSON value is a null value. +* `json_is_bool(json)` to check whether a JSON value is a boolean value. +* `json_is_int(json)` to check whether a JSON value is an integer value. +* `json_is_float(json)` to check whether a JSON value is a float value. +* `json_is_string(json)` to check whether a JSON value is a string value. +* `json_is_object(json)` to check whether a JSON value is an object value. +* `json_is_array(json)` to check whether a JSON value is an array value. + +```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)` to check whether a path exists in a JSON value. + +If the path is invalid, the function will return an error. + +If the path or the JSON value is `NULL`, the function will return a `NULL` value. + +```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/versioned_docs/version-1.0/reference/sql/functions/overview.md b/versioned_docs/version-1.0/reference/sql/functions/overview.md new file mode 100644 index 0000000000..e0161d9d16 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/functions/overview.md @@ -0,0 +1,289 @@ +--- +keywords: [SQL functions, DataFusion functions, aggregate functions, scalar functions, window functions] +description: Provides an overview of the SQL functions available in GreptimeDB, including categories and examples of their usage. +--- + +import TOCInline from '@theme/TOCInline'; + +# Functions + + + + + +## Datafusion Functions + +Since GreptimeDB's query engine is built based on Apache Arrow DataFusion, GreptimeDB inherits all built-in +functions in DataFusion. These functions include: + +* **Aggregate functions**: such as `COUNT`, `SUM`, `MIN`, `MAX`, etc. For a detailed list, please refer to [Aggregate Functions](./df-functions.md#aggregate-functions) +* **Scalar functions**: such as `ABS`, `COS`, `FLOOR`, etc. For a detailed list, please refer to [Scalar Functions](./df-functions.md#scalar-functions) +* **Window functions**: performs a calculation across a set of table rows that are somehow related to the current row. For a detailed list, please refer to [Window Functions](./df-functions.md#window-functions) + +To find all the DataFusion functions, please refer to [DataFusion Functions](df-functions.md). + +### `arrow_cast` + +`arrow_cast` function is from DataFusion's [`arrow_cast`](./df-functions.md#arrow-cast). It's illustrated as: + +```sql +arrow_cast(expression, datatype) +``` + +Where the `datatype` can be any valid Arrow data type in this [list](https://arrow.apache.org/datafusion/user-guide/sql/data_types.html). The four timestamp types are: + +- Timestamp(Second, None) +- Timestamp(Millisecond, None) +- Timestamp(Microsecond, None) +- Timestamp(Nanosecond, None) + +(Notice that the `None` means the timestamp is timezone naive) + +## GreptimeDB Functions + +### String Functions + +DataFusion [String Function](./df-functions.md#string-functions). + +GreptimeDB provides: +* `matches_term(expression, term)` for full text search. For details, read the [Fulltext Search](/user-guide/logs/fulltext-search.md). +* `regexp_extract(str, regexp)` to extract the first substring in a string that matches a regular expression. Returns `NULL` if no match is found. + +#### regexp_extract + +Extracts the first substring in a string that matches a [regular expression](https://docs.rs/regex/latest/regex/#syntax). Returns `NULL` if no match is found. + +```sql +regexp_extract(str, regexp) +``` + +**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. + +**Note on Escaping:** + +GreptimeDB's regex escape behavior differs between MySQL and PostgreSQL compatibility modes: +- **MySQL mode**: Requires double backslashes for escape sequences (e.g., `\\d`, `\\s`) +- **PostgreSQL mode**: Single backslashes work by default (e.g., `\d`, `\s`), or use `E''` prefix for consistency with MySQL (e.g., `E'\\d'`) + +**Examples:** + +```sql +SELECT regexp_extract('version 1.2.3', '\d+\.\d+\.\d+'); +-- Returns: 1.2.3 + +SELECT regexp_extract('Phone: 123-456-7890', '\d{3}-\d{3}-\d{4}'); +-- Returns: 123-456-7890 + +SELECT regexp_extract('no match here', '\d+\.\d+\.\d+'); +-- Returns: NULL +``` + +### Math Functions + +DataFusion [Math Function](./df-functions.md#math-functions). + +GreptimeDB provides: + +* `clamp(value, lower, upper)` to restrict a given value between a lower and upper bound: + +```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)` to get the remainder of a number divided by another number: +```sql +SELECT mod(18, 4); + ++-------------------------+ +| mod(Int64(18),Int64(4)) | ++-------------------------+ +| 2 | ++-------------------------+ +``` + +### Date and Time Functions + +DataFusion [Time and Date Function](./df-functions.md#time-and-date-functions). +GreptimeDB provides: + +* [date_add](#data_add) +* [date_sub](#data_sub) +* [date_format](#date_format) +* [to_unixtime](#to_unixtime) +* [timezone](#timezone) + +#### date_add + +* `date_add(expression, interval)` to add an interval value to Timestamp, Date, or 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 | ++----------------------------------------------------+ +``` + +#### data_sub + +* `date_sub(expression, interval)` to subtract an interval value to Timestamp, Date, or DateTime + +```sql +SELECT date_sub('2023-12-06 07:39:46.222'::TIMESTAMP_MS, '5 day'::INTERVAL); +``` + +``` ++-----------------------------------------------------------------------------------------------------------------------------------------+ +| 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 + +* `date_format(expression, fmt)` to format Timestamp, Date, or DateTime into string by the format: + +Supports `Date32`, `Date64`, and all `Timestamp` types. + +```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 | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +Supported specifiers refer to the [chrono::format::strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) module. + +#### to_unixtime + +* `to_unixtime(expression)` to convert the expression into the Unix timestamp in seconds. The argument can be integers (Unix timestamp in milliseconds), Timestamp, Date, DateTime, or String. If the argument is the string type, the function will first try to convert it into a DateTime, Timestamp, or 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 + +* `timezone()` to retrieve the current session timezone: + +```sql +select timezone(); +``` + +``` ++------------+ +| timezone() | ++------------+ +| UTC | ++------------+ +``` + +### System Functions + +* `isnull(expression)` to check whether an expression is `NULL`: +```sql + SELECT isnull(1); + + +------------------+ +| isnull(Int64(1)) | ++------------------+ +| 0 | ++------------------+ +``` + +```sql +SELECT isnull(NULL); + ++--------------+ +| isnull(NULL) | ++--------------+ +| 1 | ++--------------+ +``` + + +* `build()` retrieves the GreptimeDB build info. +* `version()` retrieves the GreptimeDB version. +* `database()` retrieves the current session database: + +```sql +select database(); + ++------------+ +| database() | ++------------+ +| public | ++------------+ +``` + +### Admin Functions + +GreptimeDB provides `ADMIN` statement to run the administration functions, please refer to [ADMIN](/reference/sql/admin.md) reference. + +### JSON Functions + +GreptimeDB provide functions for jsons. [Learn more about these functions](./json.md) + +### Geospatial Functions + +GreptimeDB provide functions for geo-index, trajectory analytics. [Learn more +about these functions](./geo.md) + +### Vector Functions + +GreptimeDB supports vector functions for vector operations, such as distance calculation, similarity measurement, etc. [Learn more about these functions](./vector.md) + +### Approximate Functions + +GreptimeDB supports some approximate functions for data analysis, such as approximate count distinct(hll), approximate quantile(uddsketch), etc. [Learn more about these functions](./approximate.md) diff --git a/versioned_docs/version-1.0/reference/sql/functions/vector.md b/versioned_docs/version-1.0/reference/sql/functions/vector.md new file mode 100644 index 0000000000..74fc8f34ee --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/functions/vector.md @@ -0,0 +1,479 @@ +--- +keywords: [vector functions, distance calculations, similarity measurement, vector operations, SQL functions] +description: Lists and describes vector functions available in GreptimeDB, including their usage and examples. +--- + +# Vector Functions + +This page lists all supported vector-related functions in GreptimeDB. Vector functions are primarily used for handling vector operations, such as basic arithmetic, distance calculations, conversion functions, and more. + +## Basic Operations + +### `vec_scalar_add` + +Adds a scalar to a vector. Each element in the vector is added to the scalar, returning a new vector. + +Examples: + +```sql +SELECT vec_to_string(vec_scalar_add(2.0, parse_vec('[1.0, 2.0, 3.0]'))); +``` + +```sql ++------------------------------------------------------------------------------+ +| vec_to_string(vec_scalar_add(Float64(2),parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++------------------------------------------------------------------------------+ +| [3,4,5] | ++------------------------------------------------------------------------------+ +``` + +``` +SELECT vec_to_string(vec_scalar_add(2.0, '[1.0, 2.0, 3.0]')); -- Implicitly convert string to vector +``` + +```sql ++-------------------------------------------------------------------+ +| vec_to_string(vec_scalar_add(Float64(2),Utf8("[1.0, 2.0, 3.0]"))) | ++-------------------------------------------------------------------+ +| [3,4,5] | ++-------------------------------------------------------------------+ +``` + +``` +SELECT vec_to_string(vec_scalar_add(-2.0, parse_vec('[1.0, 2.0, 3.0]'))); -- Subtraction +``` + +```sql ++-------------------------------------------------------------------------------+ +| vec_to_string(vec_scalar_add(Float64(-2),parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++-------------------------------------------------------------------------------+ +| [-1,0,1] | ++-------------------------------------------------------------------------------+ +``` + +### `vec_scalar_mul` + +Multiplies a vector by a scalar. Each element in the vector is multiplied by the scalar, returning a new vector. + +Examples: + +```sql +SELECT vec_to_string(vec_scalar_mul(2.0, parse_vec('[1.0, 2.0, 3.0]'))); +``` + +```sql ++------------------------------------------------------------------------------+ +| vec_to_string(vec_scalar_mul(Float64(2),parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++------------------------------------------------------------------------------+ +| [2,4,6] | ++------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_scalar_mul(2.0, '[1.0, 2.0, 3.0]')); -- Implicitly convert string to vector +``` + +```sql ++------------------------------------------------------------------------------+ +| vec_to_string(vec_scalar_mul(Float64(2),parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++------------------------------------------------------------------------------+ +| [2,4,6] | ++------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_scalar_mul(1.0/2.0, parse_vec('[1.0, 2.0, 3.0]'))); -- Division +``` + +```sql ++-------------------------------------------------------------------------------------------+ +| vec_to_string(vec_scalar_mul(Float64(1) / Float64(2),parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++-------------------------------------------------------------------------------------------+ +| [0.5,1,1.5] | ++-------------------------------------------------------------------------------------------+ +``` + +### `vec_add` + +Adds two vectors element-wise. Returns a new vector where each element is the sum of corresponding elements in the input vectors. + +Examples: + +```sql +SELECT vec_to_string(vec_add(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]'))); +``` + +```sql ++-----------------------------------------------------------------------------------------------+ +| vec_to_string(vec_add(parse_vec(Utf8("[1.0, 2.0, 3.0]")),parse_vec(Utf8("[2.0, 1.0, 4.0]")))) | ++-----------------------------------------------------------------------------------------------+ +| [3,3,7] | ++-----------------------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_add('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]')); -- Implicitly convert strings to vectors +``` + +```sql ++-------------------------------------------------------------------------+ +| vec_to_string(vec_add(Utf8("[1.0, 2.0, 3.0]"),Utf8("[2.0, 1.0, 4.0]"))) | ++-------------------------------------------------------------------------+ +| [3,3,7] | ++-------------------------------------------------------------------------+ +``` + +### `vec_sub` + +Subtracts two vectors element-wise. Returns a new vector where each element is the difference of corresponding elements in the input vectors. + +Examples: + +```sql +SELECT vec_to_string(vec_sub(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]'))); +``` + +```sql ++-----------------------------------------------------------------------------------------------+ +| vec_to_string(vec_sub(parse_vec(Utf8("[1.0, 2.0, 3.0]")),parse_vec(Utf8("[2.0, 1.0, 4.0]")))) | ++-----------------------------------------------------------------------------------------------+ +| [-1,1,-1] | ++-----------------------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_sub('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]')); -- Implicitly convert strings to vectors +``` + +```sql ++-------------------------------------------------------------------------+ +| vec_to_string(vec_sub(Utf8("[1.0, 2.0, 3.0]"),Utf8("[2.0, 1.0, 4.0]"))) | ++-------------------------------------------------------------------------+ +| [-1,1,-1] | ++-------------------------------------------------------------------------+ +``` + +### `vec_mul` + +Multiplies two vectors element-wise. Returns a new vector where each element is the product of corresponding elements in the input vectors. + + +Examples: + +```sql +SELECT vec_to_string(vec_mul(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]'))); +``` + +```sql ++-----------------------------------------------------------------------------------------------+ +| vec_to_string(vec_mul(parse_vec(Utf8("[1.0, 2.0, 3.0]")),parse_vec(Utf8("[2.0, 1.0, 4.0]")))) | ++-----------------------------------------------------------------------------------------------+ +| [2,2,12] | ++-----------------------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_mul('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]')); -- Implicitly convert strings to vectors +``` + +```sql ++-------------------------------------------------------------------------+ +| vec_to_string(vec_mul(Utf8("[1.0, 2.0, 3.0]"),Utf8("[2.0, 1.0, 4.0]"))) | ++-------------------------------------------------------------------------+ +| [2,2,12] | ++-------------------------------------------------------------------------+ +``` + +### `vec_div` + +Divides two vectors element-wise. Returns a new vector where each element is the quotient of corresponding elements in the input vectors. + +Examples: + +```sql +SELECT vec_to_string(vec_div(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]'))); +``` + +```sql ++-----------------------------------------------------------------------------------------------+ +| vec_to_string(vec_div(parse_vec(Utf8("[1.0, 2.0, 3.0]")),parse_vec(Utf8("[2.0, 1.0, 4.0]")))) | ++-----------------------------------------------------------------------------------------------+ +| [0.5,2,0.75] | ++-----------------------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_div('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]')); -- Implicitly convert strings to vectors +``` + +```sql ++-------------------------------------------------------------------------+ +| vec_to_string(vec_div(Utf8("[1.0, 2.0, 3.0]"),Utf8("[2.0, 1.0, 4.0]"))) | ++-------------------------------------------------------------------------+ +| [0.5,2,0.75] | ++-------------------------------------------------------------------------+ +``` + +### `vec_elem_sum` + +Sums all elements of a vector, returning a scalar value. + +Examples: + +```sql +SELECT vec_elem_sum(parse_vec('[1.0, 2.0, 3.0]')); +``` + +```sql ++--------------------------------------------------+ +| vec_elem_sum(parse_vec(Utf8("[1.0, 2.0, 3.0]"))) | ++--------------------------------------------------+ +| 6 | ++--------------------------------------------------+ +``` + +```sql +SELECT vec_elem_sum('[1.0, 2.0, 3.0]'); -- Implicitly convert string to vector +``` + +```sql ++---------------------------------------+ +| vec_elem_sum(Utf8("[1.0, 2.0, 3.0]")) | ++---------------------------------------+ +| 6 | ++---------------------------------------+ +``` + +### `vec_elem_product` + +Computes the product of all elements in a vector, returning a scalar value. + +Examples: + +```sql +SELECT vec_elem_product(parse_vec('[1.0, 2.0, 3.0]')); +``` + +```sql ++------------------------------------------------------+ +| vec_elem_product(parse_vec(Utf8("[1.0, 2.0, 3.0]"))) | ++------------------------------------------------------+ +| 6 | ++------------------------------------------------------+ +``` + +```sql +SELECT vec_elem_product('[1.0, 2.0, 3.0]'); -- Implicitly convert string to vector +``` + +```sql ++-------------------------------------------+ +| vec_elem_product(Utf8("[1.0, 2.0, 3.0]")) | ++-------------------------------------------+ +| 6 | ++-------------------------------------------+ +``` + +### `vec_norm` + +Normalizes a vector. Divides each element of the vector by the L2 norm of the vector, returning a new unit vector. + +Equivalent to `vec_scalar_mul(1.0 / sqrt(vec_elem_sum(vec_mul(vec, vec))), vec)`. + +Examples: + +```sql +SELECT vec_to_string(vec_norm(parse_vec('[1.0, 2.0, 3.0]'))); +``` + +```sql ++-------------------------------------------------------------+ +| vec_to_string(vec_norm(parse_vec(Utf8("[1.0, 2.0, 3.0]")))) | ++-------------------------------------------------------------+ +| [0.26726124,0.5345225,0.8017837] | ++-------------------------------------------------------------+ + +-- Equivalent to: +-- SELECT vec_to_string(vec_scalar_mul(1.0 / sqrt(vec_elem_sum(vec_mul(vec, vec))), vec)) +-- FROM (SELECT '[1.0, 2.0, 3.0]' AS vec); +-- +--------------------------------------------------------------------------------------+ +-- | vec_to_string(vec_scalar_mul(Float64(1) / sqrt(vec_elem_sum(vec_mul(vec,vec))),vec)) | +-- +--------------------------------------------------------------------------------------+ +-- | [0.26726124,0.5345225,0.8017837] | +-- +--------------------------------------------------------------------------------------+ +``` + +```sql +SELECT vec_to_string(vec_norm('[1.0, 2.0, 3.0]')); -- Implicitly convert string to vector +``` + +```sql ++--------------------------------------------------+ +| vec_to_string(vec_norm(Utf8("[1.0, 2.0, 3.0]"))) | ++--------------------------------------------------+ +| [0.26726124,0.5345225,0.8017837] | ++--------------------------------------------------+ +``` + +## Aggregate Functions + +### `vec_sum` + +Sums all vectors in a vector column element-wise, returning a new vector. + +Examples: + +```sql +CREATE TABLE vectors ( + ts TIMESTAMP TIME INDEX, + vec_col VECTOR(3), +); + +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:01', '[1.0, 2.0, 3.0]'); +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:02', '[2.0, 1.0, 4.0]'); +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:03', '[3.0, 3.0, 3.0]'); + +SELECT vec_to_string(vec_sum(vec_col)) FROM vectors; +``` + +```sql ++-----------------------------------------+ +| vec_to_string(vec_sum(vectors.vec_col)) | ++-----------------------------------------+ +| [6,6,10] | ++-----------------------------------------+ +``` + +### `vec_product` + +Multiplies all vectors in a vector column element-wise, returning a new vector. + +Examples: + +```sql +CREATE TABLE vectors ( + ts TIMESTAMP TIME INDEX, + vec_col VECTOR(3), +); + +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:01', '[1.0, 2.0, 3.0]'); +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:02', '[2.0, 1.0, 4.0]'); +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:03', '[3.0, 3.0, 3.0]'); + +SELECT vec_to_string(vec_product(vec_col)) FROM vectors; +``` + +```sql ++---------------------------------------------+ +| vec_to_string(vec_product(vectors.vec_col)) | ++---------------------------------------------+ +| [6,6,36] | ++---------------------------------------------+ +``` + +## Distance Calculations + +* `vec_l2sq_distance(vec1, vec2)`: Computes the squared L2 distance between two vectors. +* `vec_cos_distance(vec1, vec2)`: Computes the cosine distance between two vectors. +* `vec_dot_product(vec1, vec2)`: Computes the dot product of two vectors. + +These functions accept vector values as parameters. You can use the `parse_vec` function to convert a string into a vector value, such as `parse_vec('[1.0, 2.0, 3.0]')`. Also, vector strings (e.g., `[1.0, 2.0, 3.0]`) can be used directly and will be automatically converted. Regardless of the method used, the dimensionality of the vectors must remain consistent. + +--- + +### `vec_l2sq_distance` + +Calculates the squared Euclidean distance (squared L2 distance) between two vectors. L2 distance is the straight-line distance between two points in geometric space. This function returns the squared value to improve computational efficiency. + +Example: + +```sql +SELECT vec_l2sq_distance(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]')); +``` + +Or + +```sql +SELECT vec_l2sq_distance('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]'); +``` + + +Details: + +* Parameters are two vectors with consistent dimensions. +* Output: A scalar value of type `Float32`. + +--- + +### `vec_cos_distance` + +Calculates the cosine distance between two vectors. Cosine distance measures the cosine of the angle between two vectors and is used to quantify similarity. + +Example: + +```sql +SELECT vec_cos_distance(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]')); +``` + +Or + +```sql +SELECT vec_cos_distance('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]'); +``` + +Details: + +* Parameters are two vectors with consistent dimensions. +* Output: A scalar value of type `Float32`. + +--- + +### `vec_dot_product` + +Computes the dot product of two vectors. The dot product is the sum of the element-wise multiplications of two vectors. It is commonly used to measure similarity or for linear transformations in machine learning. + +Example: + +```sql +SELECT vec_dot_product(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]')); +``` + +Or + +```sql +SELECT vec_dot_product('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]'); +``` + +Details: + +* Parameters are two vectors with consistent dimensions. +* Output: A scalar value of type `Float32`. + +## Conversion Functions + +When dealing with vector data in the database, GreptimeDB provides convenient functions for converting between strings and vector values. + +### `parse_vec` + +Converts a string to a vector value. The string must be enclosed in square brackets `[]` and contain elements of type `Float32`, separated by commas. + +Example: + +```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` + +Converts a vector object to a string. The converted string format is `[, , ...]`. + +Example: + +```sql +SELECT vec_to_string(vec_col) FROM vectors; +``` diff --git a/versioned_docs/version-1.0/reference/sql/greptime-private/overview.md b/versioned_docs/version-1.0/reference/sql/greptime-private/overview.md new file mode 100644 index 0000000000..6b481e13c6 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/greptime-private/overview.md @@ -0,0 +1,15 @@ +--- +keywords: [system tables, greptime private, pipelines, slow queries] +description: The overview of system tables in the `greptime_private` database. +--- + +# Greptime Private + +GreptimeDB stores some important internal information as system tables in the `greptime_private` database. Similar to the normal tables, the system tables will be persistently stored. You can obtain system configurations and statistical information through the system tables. + +## Tables + +| Table Name | Description | +| ----------------------------------- | --------------------------------------------------------------------------------------------- | +| [`slow_queries`](./slow_queries.md) | Contains GreptimeDB slow query information, including query statements, execution times, etc. | +| [`pipelines`](./pipelines.md) | Contains GreptimeDB Pipeline information. | diff --git a/versioned_docs/version-1.0/reference/sql/greptime-private/pipelines.md b/versioned_docs/version-1.0/reference/sql/greptime-private/pipelines.md new file mode 100644 index 0000000000..6a0b9dca8f --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/greptime-private/pipelines.md @@ -0,0 +1,39 @@ +--- +keywords: [pipelines, greptime private] +description: The pipelines table in the `greptime_private` database. +--- + +# pipelines + +The `pipelines` table contains GreptimeDB Pipeline information. + +```sql +USE greptime_private; + +SELECT * FROM pipelines; +``` + +The output is as follows: + +```sql ++----------------+--------+--------------+----------------------------------------------------------------------------------------------------------------------------------+----------------------------+ +| name | schema | content_type | pipeline | created_at | ++----------------+--------+--------------+----------------------------------------------------------------------------------------------------------------------------------+----------------------------+ +| nginx_pipeline | | yaml | transform: | 2025-07-03 07:23:15.227539 | + - fields: + - response_size + type: int32 + - fields: + - timestamp + type: time + index: timestamp ++----------------+--------+--------------+----------------------------------------------------------------------------------------------------------------------------------+----------------------------+ +``` + +- `name`: The name of the pipeline; +- `schema`: Deprecated. If you create the pipeline after `v0.15`, this field should be an empty string. +- `content_type`: The type of the pipeline; +- `pipeline`: The content of the pipeline; +- `created_at`: The creation time of the pipeline; + +For more details, please refer to the [Manage Pipelines](/user-guide/logs/manage-pipelines.md) documentation. diff --git a/versioned_docs/version-1.0/reference/sql/greptime-private/slow_queries.md b/versioned_docs/version-1.0/reference/sql/greptime-private/slow_queries.md new file mode 100644 index 0000000000..7216432be7 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/greptime-private/slow_queries.md @@ -0,0 +1,37 @@ +--- +keywords: [slow queries, greptime private] +description: The slow queries table in the `greptime_private` database. +--- + +# slow_queries + +The `slow_queries` table contains the slow queries of GreptimeDB: + +```sql +USE greptime_private; + +SELECT * FROM slow_queries; +``` + +The output is as follows: + +```sql ++------+-----------+---------------------------------------------+-----------+----------------------------+--------------+-------------+---------------------+---------------------+ +| cost | threshold | query | is_promql | timestamp | promql_range | promql_step | promql_start | promql_end | ++------+-----------+---------------------------------------------+-----------+----------------------------+--------------+-------------+---------------------+---------------------+ +| 2 | 0 | irate(process_cpu_seconds_total[1h]) | 1 | 2025-05-14 13:59:36.368575 | 86400000 | 3600000 | 2024-11-24 00:00:00 | 2024-11-25 00:00:00 | +| 22 | 0 | SELECT * FROM greptime_private.slow_queries | 0 | 2025-05-14 13:59:44.844201 | 0 | 0 | 1970-01-01 00:00:00 | 1970-01-01 00:00:00 | ++------+-----------+---------------------------------------------+-----------+----------------------------+--------------+-------------+---------------------+---------------------+ +``` + +- `cost`: The cost of the query in milliseconds. +- `threshold`: The threshold of the query in milliseconds. +- `query`: The query string. It can be SQL or PromQL. +- `is_promql`: Whether the query is a PromQL query. +- `timestamp`: The timestamp of the query. +- `promql_range`: The range of the query. Only used when is_promql is true. +- `promql_step`: The step of the query. Only used when is_promql is true. +- `promql_start`: The start time of the query. Only used when is_promql is true. +- `promql_end`: The end time of the query. Only used when is_promql is true. + +You can refer to the [Slow Query](/user-guide/deployments-administration/monitoring/slow-query.md) documentation for more details. diff --git a/versioned_docs/version-1.0/reference/sql/group_by.md b/versioned_docs/version-1.0/reference/sql/group_by.md new file mode 100644 index 0000000000..f6bca64285 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/group_by.md @@ -0,0 +1,74 @@ +--- +keywords: [SQL GROUP BY, SQL aggregate functions, SQL syntax, SQL examples, SQL data grouping] +description: Details the SQL GROUP BY clause used to group rows with the same values in specified columns, typically used with aggregate functions like COUNT, SUM, and AVG, with examples. +--- + +# GROUP BY + +The `GROUP BY` clause in SQL is used to group rows that have the same values in one or more columns. +This clause is typically used with aggregate functions such as `COUNT`, `SUM`, `AVG`, etc., to generate +summary reports. + +## Syntax + +The basic syntax of the `GROUP BY` clause is as follows: + +```sql +SELECT column1, column2, ..., aggregate_function(column_name) +FROM table_name +GROUP BY column1, column2, ...; +``` + +The `GROUP BY` clause groups the result set based on the columns specified in the clause. The aggregate +function is applied to each group of rows that have the same values in the specified columns. + +## Examples + +Consider the following table named "system_metrics": + +```sql ++-------+-------+----------+-------------+-----------+---------------------+ +| host | idc | cpu_util | memory_util | disk_util | ts | ++-------+-------+----------+-------------+-----------+---------------------+ +| host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 | +| host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 | +| host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 | ++-------+-------+----------+-------------+-----------+---------------------+ +``` + +### Group by Tags + +To get the avg memory_util for each idc, the following SQL query can be used: + +```sql +SELECT idc, AVG(memory_util) +FROM system_metrics +GROUP BY idc; +``` + +The result of the above query would be: + +```sql ++-------+---------------------------------+ +| idc | AVG(system_metrics.memory_util) | ++-------+---------------------------------+ +| idc_b | 66.7 | +| idc_c | 66.8 | +| idc_e | 66.7 | +| idc_a | 40.3 | ++-------+---------------------------------+ +``` + +### Group by Time Interval + +To get the avg memory_util for each day, the following SQL query can be used: + +```sql +SELECT date_trunc('day', ts) as dt, avg(memory_util) +FROM system_metrics +GROUP BY dt +``` + +Please refer to [date_trunc](./functions/overview.md#date_trunc) for more details. diff --git a/versioned_docs/version-1.0/reference/sql/having.md b/versioned_docs/version-1.0/reference/sql/having.md new file mode 100644 index 0000000000..5eb55bd314 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/having.md @@ -0,0 +1,38 @@ +--- +keywords: [SQL HAVING clause, data retrieval, filtering rows for aggregate functions] +description: Describes the HAVING clause in SQL, which is used to filter rows for aggregate functions. +--- + +# HAVING + +The `HAVING` clause allows you to filter grouped (aggregated) results—it works like `WHERE`, but after grouping has taken place. The `HAVING` clause was added to SQL because the `WHERE` clause cannot be used with aggregate functions. + + +## Examples +Find days where the average CPU utilization exceeded 80%: +```sql +SELECT + date_trunc('day', ts) AS day, + AVG(cpu_util) AS avg_cpu_util +FROM + system_metrics +GROUP BY + day +HAVING + avg_cpu_util > 80; +``` + +Find hours where the number of error logs is greater than 100: +```sql +SELECT + DATE_TRUNC('hour', log_time) AS hour, + COUNT(*) AS error_count +FROM + application_logs +WHERE + log_level = 'ERROR' +GROUP BY + hour +HAVING + error_count > 100; +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/build-info.md b/versioned_docs/version-1.0/reference/sql/information-schema/build-info.md new file mode 100644 index 0000000000..66e1aa2ae5 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/build-info.md @@ -0,0 +1,33 @@ +--- +keywords: [build information, SQL information schema, version details, build metadata, system build info] +description: Contains build information for the SQL information schema, including version details, build date, and other relevant metadata. +--- + +# BUILD_INFO + +The `BUILD_INFO` table provides the system build info: + +```sql +USE INFORMATION_SCHEMA; + +SELECT * FROM BUILD_INFO; +``` + +The output is as follows: + +```sql ++------------+------------------------------------------+------------------+-----------+-------------+ +| git_branch | git_commit | git_commit_short | git_clean | pkg_version | ++------------+------------------------------------------+------------------+-----------+-------------+ +| | c595a56ac89bef78b19a76aa60d8c6bcac7354a5 | c595a56a | true | 0.9.0 | ++------------+------------------------------------------+------------------+-----------+-------------+ +``` + +The columns in the output: + +* `branch`: the build git branch name. +* `git_commit`: the build commit revision. +* `git_commit_short`: the short commit revision. +* `git_clean`: `true` if the build source directory contains all the committed changes. +* `pkg_version`: the GreptimeDB version. + diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/character-sets.md b/versioned_docs/version-1.0/reference/sql/information-schema/character-sets.md new file mode 100644 index 0000000000..4be713f825 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/character-sets.md @@ -0,0 +1,31 @@ +--- +keywords: [character sets, SQL information schema, character set details, character set management, available character sets] +description: Provides details on the character sets available in the SQL information schema, including how to use and manage different character sets. +--- + +# CHARACTER_SETS + +The `CHARACTER_SETS` provides the available character sets that GreptimeDB supports. + +```sql +USE INFORMATION_SCHEMA; + +SELECT * FROM CHARACTER_SETS; +``` + +The output is as follows: + +```sql ++--------------------+----------------------+---------------+--------+ +| character_set_name | default_collate_name | description | maxlen | ++--------------------+----------------------+---------------+--------+ +| utf8 | utf8_bin | UTF-8 Unicode | 4 | ++--------------------+----------------------+---------------+--------+ +``` + +The columns in the output: + +* `character_set_name`: the name of the character set. +* `default_collate_name`: the default collation name of the character set. +* `description`: the description of the character set. +* `MAXLEN`: the maximum number of bytes required to store one character. \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/cluster-info.md b/versioned_docs/version-1.0/reference/sql/information-schema/cluster-info.md new file mode 100644 index 0000000000..320c5edc61 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/cluster-info.md @@ -0,0 +1,88 @@ +--- +keywords: [cluster information, cluster configuration, SQL information schema, cluster status, cluster nodes] +description: Contains information about the cluster configuration and status within the SQL information schema, including nodes, roles, and other cluster-related details. +--- + +# CLUSTER_INFO + +The `CLUSTER_INFO` table provides the topology information of the cluster. + + +```sql +USE INFORMATION_SCHEMA; + +DESC TABLE CLUSTER_INFO; +``` + +The output is as follows: + +```sql ++-----------------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-----------------------+----------------------+------+------+---------+---------------+ +| peer_id | Int64 | | NO | | FIELD | +| peer_type | String | | NO | | FIELD | +| peer_addr | String | | YES | | FIELD | +| peer_hostname | String | | YES | | FIELD | +| total_cpu_millicores | Int64 | | NO | | FIELD | +| total_memory_bytes | Int64 | | NO | | FIELD | +| cpu_usage_millicores | Int64 | | NO | | FIELD | +| memory_usage_bytes | Int64 | | NO | | FIELD | +| version | String | | NO | | FIELD | +| git_commit | String | | NO | | FIELD | +| start_time | TimestampMillisecond | | YES | | FIELD | +| uptime | String | | YES | | FIELD | +| active_time | String | | YES | | FIELD | +| node_status | String | | YES | | FIELD | ++-----------------------+----------------------+------+------+---------+---------------+ +``` + + +The columns in table: + +* `peer_id`: the server id of the node. It's always `0` for standalone mode and `-1` for frontends because it doesn't make sense in such cases. +* `peer_type`: the node type, `METASRV`,`FRONTEND`, or `DATANODE` for distributed clusters and `STANDALONE` for standalone deployments. +* `peer_addr`: the GRPC server address of the node. It's always empty for standalone deployments. +* `peer_hostname`: the hostname of the peer. +* `total_cpu_millicores`: the total CPU millicores of the node. +* `total_memory_bytes`: the total memory bytes of the node. +* `cpu_usage_millicores`: the CPU usage millicores of the node. This only works in a containerized environment (cgroup v2). +* `memory_usage_bytes`: the memory usage bytes of the node. This only works in a containerized environment (cgroup v2). +* `version`: The build version of the node, such as `0.7.2` etc. +* `git_commit`: The build git commit of the node. +* `start_time`: The node start time. +* `uptime`: The uptime of the node, in the format of duration string `24h 10m 59s 150ms`. +* `active_time`: The duration string in the format of `24h 10m 59s 150ms` since the node's last active time(sending the heartbeats), it's always empty for standalone deployments. +* `node_status`: the status info of the peer. + +Query the table: + +```sql +SELECT * FROM CLUSTER_INFO; +``` + +An example output in standalone deployments: + +```sql ++---------+------------+-----------+---------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+--------+-------------+-------------+ +| peer_id | peer_type | peer_addr | peer_hostname | total_cpu_millicores | total_memory_bytes | cpu_usage_millicores | memory_usage_bytes | version | git_commit| start_time | uptime | active_time | node_status | ++---------+------------+-----------+---------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+--------+-------------+-------------+ +| 0 | STANDALONE | | | 16000 | 17179869184 | 0 | 0 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:02.074 | 18ms | | NULL | ++---------+------------+-----------+---------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+--------+-------------+-------------+ +``` + +Another example is from a distributed cluster that has three Datanodes, one Frontend, and one Metasrv. + +```sql ++---------+-----------+----------------+-------------------------------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+----------+-------------+-------------------------------------------------------------------+ +| peer_id | peer_type | peer_addr | peer_hostname | total_cpu_millicores | total_memory_bytes | cpu_usage_millicores | memory_usage_bytes | version | git_commit| start_time | uptime | active_time | node_status | ++---------+-----------+----------------+-------------------------------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+----------+-------------+-------------------------------------------------------------------+ +| 1 | DATANODE | 127.0.0.1:4101 | mycluster-datanode-0 | 1000 | 1073741824 | 1 | 34570240 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:04.791 | 4s 478ms | 1s 467ms | {"workloads":["hybrid"],"leader_regions":46,"follower_regions":0} | +| 2 | DATANODE | 127.0.0.1:4102 | mycluster-datanode-1 | 1000 | 1073741824 | 1 | 38170624 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:06.098 | 3s 171ms | 162ms | {"workloads":["hybrid"],"leader_regions":46,"follower_regions":0} | +| 3 | DATANODE | 127.0.0.1:4103 | mycluster-datanode-2 | 1000 | 1073741824 | 1 | 37085184 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:07.425 | 1s 844ms | 1s 839ms | {"workloads":["hybrid"],"leader_regions":46,"follower_regions":0} | +| -1 | FRONTEND | 127.0.0.1:4001 | mycluster-frontend-6c5d4bcf78-m7jtx | 1000 | 1073741824 | 1 | 45465600 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:08.815 | 454ms | 47ms | NULL | +| 0 | METASRV | 127.0.0.1:3002 | mycluster-meta-54bd44bd94-g8dzm | 1000 | 1073741824 | 0 | 28368896 | unknown | unknown | | | | {"is_leader":true} | ++---------+-----------+----------------+-------------------------------------+----------------------+--------------------+----------------------+--------------------+---------+-----------+----------------------------+----------+-------------+-------------------------------------------------------------------+ +``` + + diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/collation-character-set-applicability.md b/versioned_docs/version-1.0/reference/sql/information-schema/collation-character-set-applicability.md new file mode 100644 index 0000000000..53d463ff2b --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/collation-character-set-applicability.md @@ -0,0 +1,29 @@ +--- +keywords: [collation applicability, character sets, SQL information schema, collation management, collation details] +description: Describes the applicability of collation character sets within the SQL information schema, detailing how they can be applied and managed. +--- + +# COLLATION_CHARACTER_SET_APPLICABILITY + +The `COLLATION_CHARACTER_SET_APPLICABILITY` table indicates what character set is applicable for what collation. + +```sql +USE INFORMATION_SCHEMA; + +SELECT * FROM COLLATION_CHARACTER_SET_APPLICABILITY; +``` + +The output is as follows: + +```sql ++----------------+--------------------+ +| collation_name | character_set_name | ++----------------+--------------------+ +| utf8_bin | utf8 | ++----------------+--------------------+ +``` + +The output has these columns: + +* `collation_name`: the collation name. +* `character_set_name`: the name of the character set with which the collation is associated. diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/collations.md b/versioned_docs/version-1.0/reference/sql/information-schema/collations.md new file mode 100644 index 0000000000..5575630ac9 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/collations.md @@ -0,0 +1,33 @@ +--- +keywords: [collations, character sets, SQL information schema, collation details, collation management] +description: Provides information about the collations available in the SQL information schema, including details on how to use and manage them. +--- + +# COLLATIONS + +The `COLLATIONS` provides information about collations for each character set. + +```sql +USE INFORMATION_SCHEMA; + +SELECT * FROM COLLATIONS; +``` + +The output is as follows: + +```sql ++----------------+--------------------+------+------------+-------------+---------+ +| collation_name | character_set_name | id | is_default | is_compiled | sortlen | ++----------------+--------------------+------+------------+-------------+---------+ +| utf8_bin | utf8 | 1 | Yes | Yes | 1 | ++----------------+--------------------+------+------------+-------------+---------+ +``` + +The table has these columns: + +* `collation_name`: the collation name. +* `character_set_name`: the name of the character set. +* `id`: the collation ID. +* `is_default`: Whether this collation is the default collation of the character set it belongs to. +* `is_compiled`: Whether the character set is compiled into the system. +* `sortlen`: the minimum amount of memory required to sort strings expressed in the character set. \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/columns.md b/versioned_docs/version-1.0/reference/sql/information-schema/columns.md new file mode 100644 index 0000000000..7446165ef3 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/columns.md @@ -0,0 +1,179 @@ +--- +keywords: [table schema, column attributes, SQL information schema, column details] +description: Provides detailed information about columns in tables, including column names, data types, default values, and other attributes. +--- + +# COLUMNS + +The `COLUMNS` provides detailed information about columns in tables. + +```sql +USE INFORMATION_SCHEMA; +DESC COLUMNS; +``` +The output is as follows: + +```sql ++--------------------------+--------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------------+--------+------+------+---------+---------------+ +| table_catalog | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| column_name | String | | NO | | FIELD | +| ordinal_position | Int64 | | NO | | FIELD | +| character_maximum_length | Int64 | YES | | FIELD | +| character_octet_length | Int64 | YES | | FIELD | +| numeric_precision | Int64 | YES | | FIELD | +| numeric_scale | Int64 | YES | | FIELD | +| datetime_precision | Int64 | YES | | FIELD | +| character_set_name | String | | YES | | FIELD | +| collation_name | String | | YES | | FIELD | +| column_key | String | | NO | | FIELD | +| extra | String | | NO | | FIELD | +| privileges | String | | NO | | FIELD | +| generation_expression | String | | NO | | FIELD | +| greptime_data_type | String | | NO | | FIELD | +| data_type | String | | NO | | FIELD | +| semantic_type | String | | NO | | FIELD | +| column_default | String | | YES | | FIELD | +| is_nullable | String | | NO | | FIELD | +| column_type | String | | NO | | FIELD | +| column_comment | String | | YES | | FIELD | +| srs_id | Int64 | | YES | | FIELD | ++--------------------------+--------+------+------+---------+---------------+ +24 rows in set (0.00 sec) +``` +Create a table `public.t1` and query the information in the `COLUMNS` table: + +```sql +CREATE TABLE public.t1 (h STRING, v FLOAT64, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, PRIMARY KEY(h)); +SELECT * FROM COLUMNS WHERE table_schema='public' AND TABLE_NAME='t1'\G +``` + +The output is as follows: + +```sql +*************************** 1. row *************************** + table_catalog: greptime + table_schema: public + table_name: t1 + column_name: h + ordinal_position: 1 +character_maximum_length: 2147483647 + character_octet_length: 2147483647 + numeric_precision: NULL + numeric_scale: NULL + datetime_precision: NULL + character_set_name: utf8 + collation_name: utf8_bin + column_key: PRI + extra: + privileges: select,insert + generation_expression: + greptime_data_type: String + data_type: string + semantic_type: TAG + column_default: NULL + is_nullable: Yes + column_type: string + column_comment: NULL + srs_id: NULL +*************************** 2. row *************************** + table_catalog: greptime + table_schema: public + table_name: t1 + column_name: v + ordinal_position: 2 +character_maximum_length: NULL + character_octet_length: NULL + numeric_precision: 22 + numeric_scale: NULL + datetime_precision: NULL + character_set_name: NULL + collation_name: NULL + column_key: + extra: + privileges: select,insert + generation_expression: + greptime_data_type: Float64 + data_type: double + semantic_type: FIELD + column_default: NULL + is_nullable: Yes + column_type: double + column_comment: NULL + srs_id: NULL +*************************** 3. row *************************** + table_catalog: greptime + table_schema: public + table_name: t1 + column_name: ts + ordinal_position: 3 +character_maximum_length: NULL + character_octet_length: NULL + numeric_precision: NULL + numeric_scale: NULL + datetime_precision: 3 + character_set_name: NULL + collation_name: NULL + column_key: TIME INDEX + extra: + privileges: select,insert + generation_expression: + greptime_data_type: TimestampMillisecond + data_type: timestamp(3) + semantic_type: TIMESTAMP + column_default: current_timestamp() + is_nullable: No + column_type: timestamp(3) + column_comment: NULL + srs_id: NULL +3 rows in set (0.03 sec) +``` + +The description of columns in the `COLUMNS` table is as follows: + +- `table_catalog`: The name of the catalog to which the table with the column belongs. The value is always `greptime` in OSS project. +- `table_schema`: The name of the database in which the table with the column is located. +- `table_name`: The name of the table with the column. +- `column_name`: The name of the column. +- `ordinal_position`: The position of the column in the table. +- `character_maximum_length`: For string columns, the maximum length in characters. +- `character_octet_length`: For string columns, the maximum length in bytes. +- `numeric_precision`: The precision of the column for numeric data types. +- `numeric_scale`: The scale of the column for numeric data types. +- `datetime_precision`: The fractional seconds precision of the column for datetime data types. +- `character_set_name`: The name of the character set of a string column. +- `collation_name`: The name of the collation of a string column. +- `column_key`: The key type of the column. It can be one of the following: `PRI`, `TIME INDEX`, or an empty string. +- `extra`: Additional information about the column. +- `privileges`: The privilege that the current user has on this column. +- `generation_expression`: For generated columns, this value displays the expression used to calculate the column value. For non-generated columns, the value is empty. +- `greptime_data_type`: The GreptimeDB [data type](/reference/sql/data-types.md) of the column. +- `data_type`: The type of data in the column. +- `semantic_type`: The type of the column. It can be one of the following: `TAG`, `FIELD`, or `TIMESTAMP`. +- `column_default`: The default value of the column. If the explicit default value is `NULL`, or if the column definition does not include the `default` clause, this value is `NULL`. +- `is_nullable`: Whether the column is nullable. If the column can store null values, this value is `YES`; otherwise, it is `NO`. +- `column_type`: The data type of the column. It is the same as the `DATA_TYPE` column. +- `column_comment`: Comments contained in the column definition. +- `srs_id`: The ID of the spatial reference system (SRS) of the column. + +The corresponding `SHOW` statement is as follows: + +```sql +SHOW COLUMNS FROM t1 FROM public; +``` + +The output is as follows: + +```sql ++-------+--------------+------+------------+---------------------+-------+----------------------+ +| Field | Type | Null | Key | Default | Extra | Greptime_type | ++-------+--------------+------+------------+---------------------+-------+----------------------+ +| h | string | Yes | PRI | NULL | | String | +| ts | timestamp(3) | No | TIME INDEX | current_timestamp() | | TimestampMillisecond | +| v | double | Yes | | NULL | | Float64 | ++-------+--------------+------+------------+---------------------+-------+----------------------+ +3 rows in set (0.01 sec) +``` diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/engines.md b/versioned_docs/version-1.0/reference/sql/information-schema/engines.md new file mode 100644 index 0000000000..95edd3d78c --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/engines.md @@ -0,0 +1,50 @@ +--- +keywords: [storage engines, engine support, transactions, XA transactions, savepoints] +description: Provides information about storage engines, including their support level, comments, and whether they support transactions, XA transactions, and savepoints. +--- + +# ENGINES + +The `ENGINES` table provides information about storage engines. This is particularly useful for checking whether a storage engine is supported, or to see what the default engine is. + +The `ENGINES` table has the following columns: + +* `engine`: the storage engine name. +* `support`: the level of support for the storage engine: + +| Value | Meaning | +| --- | --- | +| `YES` | The engine is supported and is active | +| `DEFAULT` | Like `YES`, plus this is the default engine | +| `NO` | The engine is not supported | +| `DISABLED` | The engine is supported but has been disabled | + +* `comment`: A brief description of the storage engine. +* `transactions`: Whether the storage engine supports transactions. +* `xa`: Whether the storage engine supports XA transactions. +* `savepoints`: Whether the storage engine supports savepoints. + +For example: + +```sql +SELECT * from INFORMATION_SCHEMA.ENGINES\G +``` + +The output is as follows: + +```sql +*************************** 1. row *************************** + engine: mito + support: DEFAULT + comment: Storage engine for time-series data +transactions: NO + xa: NO + savepoints: NO +*************************** 2. row *************************** + engine: metric + support: YES + comment: Storage engine for observability scenarios, which is adept at handling a large number of small tables, making it particularly suitable for cloud-native monitoring +transactions: NO + xa: NO + savepoints: NO +``` diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/flows.md b/versioned_docs/version-1.0/reference/sql/information-schema/flows.md new file mode 100644 index 0000000000..47c5f7e5d7 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/flows.md @@ -0,0 +1,40 @@ +--- +keywords: [flows, flow task, flow definition, source table IDs, sink table name] +description: Provides the flow task information, including flow name, ID, definition, source table IDs, sink table name, and other details. +--- + +# FLOWS +The `Flows` table provides the flow task information. + +```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) +``` + +The columns in table: + +* `flow_name`: the flow task's name. +* `flow_id`: the flow task's id. +* `table_catalog`: the catalog this flow belongs to, named as `table_catalog` to keep consistent with the `INFORMATION_SCHEMA` standard. +* `flow_definition`: the flow task's definition. It's the SQL statement used to create the flow task. +* `comment`: the comment of the flow task. +* `expire_after`: the expire time of the flow task. +* `source_table_ids`: the source table ids of the flow task. +* `sink_table_name`: the sink table name of the flow task. +* `flownode_ids`: the flownode ids used by the flow task. +* `options`: extra options of the flow task. \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/key-column-usage.md b/versioned_docs/version-1.0/reference/sql/information-schema/key-column-usage.md new file mode 100644 index 0000000000..63e1ffdded --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/key-column-usage.md @@ -0,0 +1,88 @@ +--- +keywords: [key column usage, key constraints, time index key, primary key] +description: Describes the key constraints of the columns, such as the time index key constraint. +--- + +# KEY_COLUMN_USAGE + +The `KEY_COLUMN_USAGE` table describes the key constraints of the columns, such as the time index key constraint. + +```sql +USE INFORMATION_SCHEMA; +DESC KEY_COLUMN_USAGE; +``` + +The output is as follows: + +```sql ++-------------------------------+--------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-------------------------------+--------+------+------+---------+---------------+ +| constraint_catalog | String | | NO | | FIELD | +| constraint_schema | String | | NO | | FIELD | +| constraint_name | String | | NO | | FIELD | +| table_catalog | String | | NO | | FIELD | +| real_table_catalog | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| column_name | String | | NO | | FIELD | +| ordinal_position | UInt32 | | NO | | FIELD | +| position_in_unique_constraint | UInt32 | | YES | | FIELD | +| referenced_table_schema | String | | YES | | FIELD | +| referenced_table_name | String | | YES | | FIELD | +| referenced_column_name | String | | YES | | FIELD | ++-------------------------------+--------+------+------+---------+---------------+ +``` + +```sql +SELECT * FROM key_column_usage WHERE table_schema='public' and table_name='monitor'\G +``` + +```sql +*************************** 1. row *************************** + constraint_catalog: def + constraint_schema: public + constraint_name: TIME INDEX + table_catalog: def + real_table_catalog: greptime + table_schema: public + table_name: monitor + column_name: ts + ordinal_position: 1 +position_in_unique_constraint: NULL + referenced_table_schema: NULL + referenced_table_name: NULL + referenced_column_name: NULL +*************************** 2. row *************************** + constraint_catalog: def + constraint_schema: public + constraint_name: PRIMARY + table_catalog: def + real_table_catalog: greptime + table_schema: public + table_name: monitor + column_name: host + ordinal_position: 1 +position_in_unique_constraint: NULL + referenced_table_schema: NULL + referenced_table_name: NULL + referenced_column_name: NULL +2 rows in set (0.02 sec) +``` + +The description of columns in the `KEY_COLUMN_USAGE` table is as follows: + +- `constraint_catalog`: The name of the catalog to which the constraint belongs. The value is always `def`. +- `constraint_schema`: The name of the database to which the constraint belongs. +- `constraint_name`: The name of the constraint. +- `table_catalog`: The name of the catalog to which the table with the constraint belongs. The value is always `def`. +- `real_table_catalog`: The real name of the catalog to which the table with the constraint belongs. The value is always `greptime`. +- `table_schema`: The name of the database to which the table belongs. +- `table_name`: The name of the table with the constraint. +- `column_name`: The name of the column with the constraint. +- `ordinal_position`: The position of the column in the constraint, rather than in the table. The position number starts from `1`. +- `position_in_unique_constraint`: The unique constraint and the primary key constraint are empty. For foreign key constraints, this column is the position of the referenced table's key. +- `referenced_table_schema`: The name of the schema referenced by the constraint. Currently in GreptimeDB, the value of this column in all constraints is `NULL`, except for the foreign key constraint. +- `referenced_table_name`: The name of the table referenced by the constraint. Currently in GreptimeDB, the value of this column in all constraints is `NULL`, except for the foreign key constraint. +- `referenced_column_name`: The name of the column referenced by the constraint. Currently in TiDB, the value of this column in all constraints is `NULL`, except for the foreign key constraint. + diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/overview.md b/versioned_docs/version-1.0/reference/sql/information-schema/overview.md new file mode 100644 index 0000000000..664fd87127 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/overview.md @@ -0,0 +1,68 @@ +--- +keywords: [system metadata, database names, table names, column data types, INFORMATION_SCHEMA] +description: Provides access to system metadata, such as database or table names, column data types, and INFORMATION_SCHEMA tables for querying GreptimeDB system metadata. +--- + +# INFORMATION_SCHEMA + +`INFORMATION_SCHEMA` provides access to system metadata, such as the name of a database or table, the data type of a column, etc. GreptimeDB also provides some custom `INFORMATION_SCHEMA` tables to query metadata about the GreptimeDB system itself, cluster information, and runtime telemetry for example. + +Many `INFORMATION_SCHEMA` tables have a corresponding `SHOW` command. The benefit of querying `INFORMATION_SCHEMA` is that it is possible to join between tables. + +There is still lots of work to do for `INFORMATION_SCHEMA`. The tracking [issue](https://github.com/GreptimeTeam/greptimedb/issues/2931) for `INFORMATION_SCHEMA`. + +## Tables for MySQL compatibility + +| Table Name | Description | +| --- | --- | +| [`CHARACTER_SETS`](./character-sets.md) | provides information about available character sets. | +| `CHECK_CONSTRAINTS`| Not implemented. Returns zero rows. | +| [`COLLATIONS`](./collations.md) | Provides a list of collations that the server supports. | +| [`COLLATION_CHARACTER_SET_APPLICABILITY`](./collation-character-set-applicability.md) | Explains which collations apply to which character sets. | +| [`COLUMNS`](./columns.md) | Provides a list of columns for all tables. | +| `COLUMN_PRIVILEGES` | Not implemented. Returns zero rows. | +| `COLUMN_STATISTICS` | Not supported. | +| [`ENGINES`](./engines.md) | Provides a list of supported storage engines. | +| `EVENTS` | Not implemented. Returns zero rows. | +| `FILES` | Not implemented. Returns zero rows. | +| `GLOBAL_STATUS` | Not implemented. Returns zero rows. | +| `GLOBAL_VARIABLES` | Not supported. | +| [`KEY_COLUMN_USAGE`](./key-column-usage.md) | Describes the key constraints of the columns, such as the primary key, and time index constraint. | +| `OPTIMIZER_TRACE` | Not implemented. Returns zero rows. | +| `PARAMETERS` | Not implemented. Returns zero rows. | +| [`PARTITIONS`](./partitions.md) | Provides a list of table partitions. | +| `PLUGINS` | Not supported.| +| `PROCESSLIST` | Not supported, please use `PROCESS_LIST` instead. | +| `PROFILING` | Not implemented. Returns zero rows. | +| `REFERENTIAL_CONSTRAINTS` | Not implemented. Returns zero rows. | +| `ROUTINES` | Not implemented. Returns zero rows. | +| [`SCHEMATA`](./schemata.md) | Provides similar information to `SHOW DATABASES`. | +| `SCHEMA_PRIVILEGES` | Not implemented. Returns zero rows. | +| `SESSION_STATUS` | Not implemented. Returns zero rows. | +| `SESSION_VARIABLES` | Not supported. | +| `STATISTICS` | Not supported. | +| [`TABLES`](./tables.md) | Provides a list of tables that the current user has visibility of. Similar to `SHOW TABLES`. | +| `TABLESPACES` | Not supported. | +| `TABLE_PRIVILEGES` | Not implemented. Returns zero rows. | +| `TRIGGERS` | Not implemented. Returns zero rows. | +| `USER_ATTRIBUTES` | Not supported. | +| `USER_PRIVILEGES` | Not supported.| +| `VARIABLES_INFO` | Not supported. | +| [`VIEWS`](./views.md)| Provides a list of views that the current user has visibility of. Similar to running `SHOW FULL TABLES WHERE table_type = 'VIEW'` | +| [`TABLE_CONSTRAINTS`](./table-constraints.md) | Provides information on primary keys, unique indexes, and foreign keys. | + +## Tables that GreptimeDB provides + +| Table Name | Description | +| --- | --- | +| [`BUILD_INFO`](./build-info.md) | Provides the system build info. | +| [`REGION_PEERS`](./region-peers.md) | Provides details about where regions are stored. | +| [`REGION_STATISTICS`](./region-statistics.md) | Provides details about region statistics info, such as disk size, etc. | +| [`RUNTIME_METRICS`](./runtime-metrics.md)| Provides the system runtime metrics.| +| [`CLUSTER_INFO`](./cluster-info.md)| Provides the topology information of the cluster.| +| [`FLOWS`](./flows.md) | Provides the flow information.| +| [`PROCEDURE_INFO`](./procedure-info.md) | Procedure information.| +| [`PROCESS_LIST`](./process-list.md) | Running queries information.| +| [`SSTS_INDEX_META`](./ssts-index-meta.md) | Provides SST index metadata including inverted indexes, fulltext indexes, and bloom filters.| +| [`SSTS_MANIFEST`](./ssts-manifest.md) | Provides SST file information from the manifest including file paths, sizes, time ranges, and row counts.| +| [`SSTS_STORAGE`](./ssts-storage.md) | Provides SST file information from the storage layer for verification and debugging.| diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/partitions.md b/versioned_docs/version-1.0/reference/sql/information-schema/partitions.md new file mode 100644 index 0000000000..5e9d04f1c7 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/partitions.md @@ -0,0 +1,164 @@ +--- +keywords: [partitions, partitioned tables, partition names, partition methods, partition expressions] +description: Provides information about partitioned tables, including partition names, methods, expressions, and other details. +--- + +# PARTITIONS + +The `PARTITIONS` table provides information about partitioned tables. + +```sql +USE INFORMATION_SCHEMA; +DESC PARTITIONS; +``` + +The output is as follows: + +```sql ++-------------------------------+----------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-------------------------------+----------+------+------+---------+---------------+ +| table_catalog | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| partition_name | String | | NO | | FIELD | +| subpartition_name | String | | YES | | FIELD | +| partition_ordinal_position | Int64 | | YES | | FIELD | +| subpartition_ordinal_position | Int64 | | YES | | FIELD | +| partition_method | String | | YES | | FIELD | +| subpartition_method | String | | YES | | FIELD | +| partition_expression | String | | YES | | FIELD | +| subpartition_expression | String | | YES | | FIELD | +| partition_description | String | | YES | | FIELD | +| table_rows | Int64 | | YES | | FIELD | +| avg_row_length | Int64 | | YES | | FIELD | +| data_length | Int64 | | YES | | FIELD | +| max_data_length | Int64 | | YES | | FIELD | +| index_length | Int64 | | YES | | FIELD | +| data_free | Int64 | | YES | | FIELD | +| create_time | TimestampSecond | | YES | | FIELD | +| update_time | TimestampSecond | | YES | | FIELD | +| check_time | TimestampSecond | | YES | | FIELD | +| checksum | Int64 | | YES | | FIELD | +| partition_comment | String | | YES | | FIELD | +| nodegroup | String | | YES | | FIELD | +| tablespace_name | String | | YES | | FIELD | +| greptime_partition_id | UInt64 | | YES | | FIELD | ++-------------------------------+----------+------+------+---------+---------------+ +26 rows in set (0.01 sec) +``` + +Main columns: +* `table_catalog`: The name of the catalog to which the table belongs. This value is always `def`. +* `table_schema`: The name of the schema (database) to which the table belongs. +* `table_name`: The name of the table containing the partition(region). +* `partition_name`: The name of the partition(region). +* `partition_ordinal_position`: All partitions are indexed in the same order as they are defined, with 1 being the number assigned to the first partition. +* `partition_method`: This value is always `RANGE`, GreptimeDB only supports range partitioning. +* `partition_expression`: The expression of this partition. +* `create_time`: The time that the partition was created. +* `greptime_partition_id`: GreptimeDB extended field, it's the Region Id. + +For example, create a partitioned table: + +```sql +CREATE TABLE public.test_p ( + a INT PRIMARY KEY, + b STRING, + ts TIMESTAMP TIME INDEX, +) +PARTITION ON COLUMNS (a) ( + a < 10, + a >= 10 AND a < 20, + a >= 20 +); + +-- Query the partitions of the table +SELECT * FROM PARTITIONS WHERE table_schema='public' AND table_name='test_p'\G +``` + +Outputs: + +```sql +*************************** 1. row *************************** + table_catalog: greptime + table_schema: public + table_name: test_p + partition_name: p0 + subpartition_name: NULL + partition_ordinal_position: 1 +subpartition_ordinal_position: NULL + partition_method: RANGE + subpartition_method: NULL + partition_expression: (a) VALUES LESS THAN (PartitionExpr { lhs: Column("a"), op: Lt, rhs: Value(Int32(10)) }) + subpartition_expression: NULL + partition_description: NULL + table_rows: NULL + avg_row_length: NULL + data_length: NULL + max_data_length: NULL + index_length: NULL + data_free: NULL + create_time: 2024-04-01 10:49:49.468000 + update_time: NULL + check_time: NULL + checksum: NULL + partition_comment: NULL + nodegroup: NULL + tablespace_name: NULL + greptime_partition_id: 4453881085952 +*************************** 2. row *************************** + table_catalog: greptime + table_schema: public + table_name: test_p + partition_name: p1 + subpartition_name: NULL + partition_ordinal_position: 2 +subpartition_ordinal_position: NULL + partition_method: RANGE + subpartition_method: NULL + partition_expression: (a) VALUES LESS THAN (PartitionExpr { lhs: Column("a"), op: GtEq, rhs: Value(Int32(20)) }) + subpartition_expression: NULL + partition_description: NULL + table_rows: NULL + avg_row_length: NULL + data_length: NULL + max_data_length: NULL + index_length: NULL + data_free: NULL + create_time: 2024-04-01 10:49:49.468000 + update_time: NULL + check_time: NULL + checksum: NULL + partition_comment: NULL + nodegroup: NULL + tablespace_name: NULL + greptime_partition_id: 4453881085954 +*************************** 3. row *************************** + table_catalog: greptime + table_schema: public + table_name: test_p + partition_name: p2 + subpartition_name: NULL + partition_ordinal_position: 3 +subpartition_ordinal_position: NULL + partition_method: RANGE + subpartition_method: NULL + partition_expression: (a) VALUES LESS THAN (PartitionExpr { lhs: Expr(PartitionExpr { lhs: Column("a"), op: Gt, rhs: Value(Int32(10)) }), op: And, rhs: Expr(PartitionExpr { lhs: Column("a"), op: Lt, rhs: Value(Int32(20)) }) }) + subpartition_expression: NULL + partition_description: NULL + table_rows: NULL + avg_row_length: NULL + data_length: NULL + max_data_length: NULL + index_length: NULL + data_free: NULL + create_time: 2024-04-01 10:49:49.468000 + update_time: NULL + check_time: NULL + checksum: NULL + partition_comment: NULL + nodegroup: NULL + tablespace_name: NULL + greptime_partition_id: 4453881085953 +``` diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/procedure-info.md b/versioned_docs/version-1.0/reference/sql/information-schema/procedure-info.md new file mode 100644 index 0000000000..f1cf13693f --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/procedure-info.md @@ -0,0 +1,37 @@ +--- +keywords: [procedure info, procedure ID, procedure type, status] +description: Provides detailed information about various procedures, including procedure ID, type, start and end time, status, and locked keys. +--- + +# PROCEDURE_INFO +The `PROCEDURE_INFO` table provides detailed information about various procedures. + +:::tip NOTE +This table is not available on [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 | ++----------------+----------------------+------+------+---------+---------------+ +``` + +Fields in the `PROCEDURE_INFO` table are described as follows: + +- `procedure_id`: The ID of the Procedure. +- `procedure_type`: The type of the Procedure. +- `start_time`: Timestamp indicating when the procedure started. +- `end_time`: Timestamp indicating when the procedure ended. +- `status`: Current status of the procedure. +- `lock_keys`: Keys locked by the procedure, if any. \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/process-list.md b/versioned_docs/version-1.0/reference/sql/information-schema/process-list.md new file mode 100644 index 0000000000..93e244c603 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/process-list.md @@ -0,0 +1,65 @@ +--- +keywords: [query, process_list, processlist, task management] +description: Provides a view of running queries in cluster. +--- + +# PROCESS_LIST + +The `PROCESS_LIST` table provides a view of all running queries in GreptimeDB cluster. + +:::tip NOTE +It's intentionally to have a different table name than MySQL's `PROCESSLIST` because it has a very different set of columns. +::: + +```sql +USE INFORMATION_SCHEMA; +DESC PROCESS_LIST; +``` + +The output is as follows: + +```sql ++-----------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-----------------+----------------------+------+------+---------+---------------+ +| id | String | | NO | | FIELD | +| catalog | String | | NO | | FIELD | +| schemas | String | | NO | | FIELD | +| query | String | | NO | | FIELD | +| client | String | | NO | | FIELD | +| frontend | String | | NO | | FIELD | +| start_timestamp | TimestampMillisecond | | NO | | FIELD | +| elapsed_time | DurationMillisecond | | NO | | FIELD | ++-----------------+----------------------+------+------+---------+---------------+ +``` + +Fields in the `PROCESS_LIST` table are described as follows: + +- `id`: The ID of query. +- `catalog`: The catalog name of the query. +- `schemas`: The schema name in which client issues the query. +- `query`: The query statement. +- `client`: Client information, including client address and channel. +- `frontend`: On which frontend instance the query is running. +- `start_timestamp`: The start timestamp of query. +- `elapsed_time`: How long the query has been running. + +:::tip NOTE +You can also use `SHOW [FULL] PROCESSLIST` statement as an alternative to querying from `INFORMATION_SCHEMA.PROCESS_LIST` table. +::: + + +# Terminating a query +When identified a running query from `PROCESS_LIST` table, you can terminate the query using `KILL ` statement, where the `` is the `id` field in `PROCESS_LIST` table. + +```sql +mysql> select * from process_list; ++-----------------------+----------+--------------------+----------------------------+------------------------+---------------------+----------------------------+-----------------+ +| id | catalog | schemas | query | client | frontend | start_timestamp | elapsed_time | ++-----------------------+----------+--------------------+----------------------------+------------------------+---------------------+----------------------------+-----------------+ +| 112.40.36.208/7 | greptime | public | SELECT * FROM some_very_large_table | mysql[127.0.0.1:34692] | 112.40.36.208:4001 | 2025-06-30 07:04:11.118000 | 00:00:12.002000 | ++-----------------------+----------+--------------------+----------------------------+------------------------+---------------------+----------------------------+-----------------+ + +KILL '112.40.36.208/7'; +Query OK, 1 row affected (0.00 sec) +``` diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/region-peers.md b/versioned_docs/version-1.0/reference/sql/information-schema/region-peers.md new file mode 100644 index 0000000000..ab22a70359 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/region-peers.md @@ -0,0 +1,50 @@ +--- +keywords: [region peers, region node, leader, learner, status] +description: Shows detailed information of a single Region node in GreptimeDB, such as whether it is a learner or leader. +--- + +# REGION_PEERS + +The `REGION_PEERS` table shows detailed information of a single Region node in GreptimeDB, such as whether it is a learner or leader. + +:::tip NOTE +This table is not available on [GreptimeCloud](https://greptime.cloud/). +::: + +```sql +USE INFORMATION_SCHEMA; +DESC REGION_PEERS; +``` + +The output is as follows: + +```sql ++---------------+--------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++---------------+--------+------+------+---------+---------------+ +| table_catalog | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| region_id | UInt64 | | NO | | FIELD | +| peer_id | UInt64 | | YES | | FIELD | +| peer_addr | String | | YES | | FIELD | +| is_leader | String | | YES | | FIELD | +| status | String | | YES | | FIELD | +| down_seconds | Int64 | | YES | | FIELD | ++---------------+--------+------+------+---------+---------------+ +6 rows in set (0.00 sec) +``` + +Fields in the `REGION_PEERS` table are described as follows: + +- `table_catalog`: The catalog of the table. +- `table_schema`: The schema of the table. +- `table_name`: The name of the table. +- `region_id`: The ID of the Region. +- `peer_id`: The ID of the Region peer. +- `peer_addr`: The address of the peer. +- `is_leader`: Whether the peer is the leader. +- `status`: The status of the peer, `ALIVE` or `DOWNGRADED`. + - `ALIVE`: The peer is online. + - `DOWNGRADED`: The Region peer is unavailable (e.g., crashed, network disconnected), or the Region peer was planned to migrate to another peer. +- `down_seconds`: The duration of being offline, in seconds. diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/region-statistics.md b/versioned_docs/version-1.0/reference/sql/information-schema/region-statistics.md new file mode 100644 index 0000000000..9e3fe970a6 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/region-statistics.md @@ -0,0 +1,73 @@ +--- +keywords: [region statistics, rows, disk size, memtable size, sst size, index size] +description: Provides detailed information about a region's statistics, including the total number of rows, disk size, and more. These statistics are approximate values. +--- + +# REGION_STATISTICS + +The `REGION_STATISTICS` table provides detailed information about a region's statistics, including the total number of rows, disk size, and more. These statistics are approximate values. + +:::tip NOTE +This table is not available on [GreptimeCloud](https://greptime.cloud/). +::: + +```sql +USE INFORMATION_SCHEMA; +DESC REGION_STATISTICS; +``` + +The output is as follows: + +```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 | +| written_bytes_since_open | UInt64 | | YES | | FIELD | +| disk_size | UInt64 | | YES | | FIELD | +| memtable_size | UInt64 | | YES | | FIELD | +| manifest_size | UInt64 | | YES | | FIELD | +| sst_size | UInt64 | | YES | | FIELD | +| sst_num | UInt64 | | YES | | FIELD | +| index_size | UInt64 | | YES | | FIELD | +| engine | String | | YES | | FIELD | +| region_role | String | | YES | | FIELD | ++--------------------------+--------+------+------+---------+---------------+ +``` + +Fields in the `REGION_STATISTICS` table are described as follows: + +- `region_id`: The ID of the Region. +- `table_id`: The ID of the table. +- `region_number`: The number of the region in the table. +- `region_rows`: The number of rows in the region. +- `written_bytes_since_open`: The number of bytes written to the region since the region was opened. +- `disk_size`: The total size of data files in the region, including data, index and metadata etc. +- `memtable_size`: The region's total size of memtables. +- `manifest_size`: The region's total size of manifest files. +- `sst_num`: The region's total number of SST files. +- `sst_size`: The region's total size of SST files. +- `index_size`: The region's total size of index files. +- `engine`: The engine type of the region, `mito` or `metric`. +- `region_role`: The region's role, `Leader` or `Follower`. + + +Retrieve a table's region statistics information as follows: + +```sql +SELECT r.* FROM REGION_STATISTICS r LEFT JOIN TABLES t on r.table_id = t.table_id \ +WHERE t.table_name = 'system_metrics'; +``` + + +Output: +```sql ++---------------+----------+---------------+-------------+--------------------------+-----------+---------------+---------------+----------+---------+------------+--------+-------------+ +| region_id | table_id | region_number | region_rows | written_bytes_since_open | disk_size | memtable_size | manifest_size | sst_size | sst_num | index_size | engine | region_role | ++---------------+----------+---------------+-------------+--------------------------+-----------+---------------+---------------+----------+---------+------------+--------+-------------+ +| 4398046511104 | 1024 | 0 | 8 | 0 | 4922 | 0 | 1338 | 3249 | 1 | 335 | mito | Leader | ++---------------+----------+---------------+-------------+--------------------------+-----------+---------------+---------------+----------+---------+------------+--------+-------------+ +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/runtime-metrics.md b/versioned_docs/version-1.0/reference/sql/information-schema/runtime-metrics.md new file mode 100644 index 0000000000..71a2f99845 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/runtime-metrics.md @@ -0,0 +1,59 @@ +--- +keywords: [runtime metrics, system metrics, HTTP endpoint, cluster metrics] +description: Provides information about the `RUNTIME_METRICS` table, which includes system runtime metrics from the `/metrics` HTTP endpoint output in the cluster. +--- + +# RUNTIME_METRICS + +The `RUNTIME_METRICS` table provides system runtime metrics. It includes all metrics from the `/metrics` HTTP endpoint output in the cluster. + +```sql +USE INFORMATION_SCHEMA; + +SELECT * FROM RUNTIME_METRICS; +``` + +Sample output is as follows: + +```sql ++------------------------------------------------------+------------------------+--------------------------------------------------------+---------+-----------+----------------------------+ +| metric_name | value | labels | node | node_type | timestamp | ++------------------------------------------------------+------------------------+--------------------------------------------------------+---------+-----------+----------------------------+ +| greptime_app_version | 1 | short_version=0.7.1, version=greptimedb-main-92a8e86 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_catalog_catalog_count | 1 | | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_catalog_schema_count | 2 | | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.005 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.01 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.025 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.05 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.1 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.25 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=0.5 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=1 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=2.5 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=5 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=10 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_bucket | 1 | le=+Inf | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_sum | 0.000290333 | | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_count | 1 | | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_catalog_counter | 1 | | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.005 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.01 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.025 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.05 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.1 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.25 | unknown | unknown | 2024-03-27 22:43:12.898000 | +| greptime_meta_create_schema_bucket | 3 | le=0.5 | unknown | unknown | 2024-03-27 22:43:12.898000 | + +... +``` + +The columns in the output: + +* `metric_name`: the metric name. +* `value`: the metric value. +* `labels`: the metric labels and values, separated by `,`. +* `node:` the metric which peer it comes from +* `node_type`: the peer type, such as `datanode`, `frontend` etc. +* `timestamp`: the metric timestamp + diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/schemata.md b/versioned_docs/version-1.0/reference/sql/information-schema/schemata.md new file mode 100644 index 0000000000..55ca545336 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/schemata.md @@ -0,0 +1,52 @@ +--- +keywords: [databases, catalog, schema, character set, collation, options] +description: Provides information about databases, including details about each database's catalog, schema name, default character set, collation, and options. +--- + +# SCHEMATA + +The `SCHEMATA` table provides information about databases. The table data is equivalent to the result of the `SHOW DATABASES` statement. + +```sql +USE INFORMATION_SCHEMA; +DESC SCHEMATA; +``` + +The output is as follows: + +```sql ++----------------------------+--------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++----------------------------+--------+------+------+---------+---------------+ +| catalog_name | String | | NO | | FIELD | +| schema_name | String | | NO | | FIELD | +| default_character_set_name | String | | NO | | FIELD | +| default_collation_name | String | | NO | | FIELD | +| sql_path | String | | YES | | FIELD | +| options | String | | YES | | FIELD | ++----------------------------+--------+------+------+---------+---------------+ +``` + +```sql +SELECT * FROM SCHEMATA; +``` + +```sql ++--------------+--------------------+----------------------------+------------------------+----------+-------------+ +| 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' | ++--------------+--------------------+----------------------------+------------------------+----------+-------------+ +``` + +Fields in the `SCHEMATA` table are described as follows: + +- `catalog_name`: The catalog to which the database belongs. +- `schema_name`: The name of the database. +- `default_character_set_name`: The default character set of the database. +- `default_collation_name`: The default collation of the database. +- `sql_path`: The value of this item is always `NULL`. +- `options`: Extending column in GreptimeDB. The database options. diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/ssts-index-meta.md b/versioned_docs/version-1.0/reference/sql/information-schema/ssts-index-meta.md new file mode 100644 index 0000000000..c636050af0 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/ssts-index-meta.md @@ -0,0 +1,125 @@ +--- +keywords: [SST index metadata, Puffin index, inverted index, fulltext index, bloom filter, index metadata] +description: Provides access to SST (Sorted String Table) index metadata, including information about inverted indexes, fulltext indexes, and bloom filters stored in Puffin format. +--- + +# SSTS_INDEX_META + +The `SSTS_INDEX_META` table provides access to SST (Sorted String Table) index metadata collected from the manifest. This table surfaces information about Puffin index metadata, including inverted indexes, fulltext indexes, and bloom filters. + +:::tip NOTE +This table is not available on [GreptimeCloud](https://greptime.cloud/). +::: + +```sql +USE INFORMATION_SCHEMA; +DESC SSTS_INDEX_META; +``` + +The output is as follows: + +```sql ++-----------------+--------+-----+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-----------------+--------+-----+------+---------+---------------+ +| table_dir | String | | NO | | FIELD | +| index_file_path | String | | NO | | FIELD | +| region_id | UInt64 | | NO | | FIELD | +| table_id | UInt32 | | NO | | FIELD | +| region_number | UInt32 | | NO | | FIELD | +| region_group | UInt8 | | NO | | FIELD | +| region_sequence | UInt32 | | NO | | FIELD | +| file_id | String | | NO | | FIELD | +| index_file_size | UInt64 | | YES | | FIELD | +| index_type | String | | NO | | FIELD | +| target_type | String | | NO | | FIELD | +| target_key | String | | NO | | FIELD | +| target_json | String | | NO | | FIELD | +| blob_size | UInt64 | | NO | | FIELD | +| meta_json | String | | YES | | FIELD | +| node_id | UInt64 | | YES | | FIELD | ++-----------------+--------+-----+------+---------+---------------+ +``` + +Fields in the `SSTS_INDEX_META` table are described as follows: + +- `table_dir`: The directory path of the table. +- `index_file_path`: The full path to the Puffin index file. +- `region_id`: The ID of the region. +- `table_id`: The ID of the table. +- `region_number`: The region number within the table. +- `region_group`: The group identifier for the region. +- `region_sequence`: The sequence number of the region. +- `file_id`: The unique identifier of the index file (UUID). +- `index_file_size`: The size of the index file in bytes. +- `index_type`: The type of index. Possible values include: + - `inverted`: Inverted index for fast term lookups + - `fulltext_bloom`: Combined fulltext and bloom filter index + - `bloom_filter`: Bloom filter for fast membership tests +- `target_type`: The type of target being indexed. Typically `column` for column-based indexes. +- `target_key`: The key identifying the target (e.g., column ID). +- `target_json`: JSON representation of the target configuration, such as `{"column":0}`. +- `blob_size`: The size of the blob data in bytes. +- `meta_json`: JSON metadata containing index-specific information such as: + - For inverted indexes: FST size, bitmap type, segment row count, etc. + - For bloom filters: bloom filter size, row count, segment count + - For fulltext indexes: analyzer type, case sensitivity settings +- `node_id`: The ID of the datanode where the index is located. + +## Examples + +Query all index metadata: + +```sql +SELECT * FROM INFORMATION_SCHEMA.SSTS_INDEX_META; +``` + +Query index metadata for a specific table by joining with the `TABLES` table: + +```sql +SELECT s.* +FROM INFORMATION_SCHEMA.SSTS_INDEX_META s +JOIN INFORMATION_SCHEMA.TABLES t ON s.table_id = t.table_id +WHERE t.table_name = 'my_table'; +``` + +Query only inverted index metadata: + +```sql +SELECT table_dir, index_file_path, index_type, target_json, meta_json +FROM INFORMATION_SCHEMA.SSTS_INDEX_META +WHERE index_type = 'inverted'; +``` + +Query index metadata grouped by index type: + +```sql +SELECT index_type, COUNT(*) as count, SUM(index_file_size) as total_size +FROM INFORMATION_SCHEMA.SSTS_INDEX_META +GROUP BY index_type; +``` + + +Output example: + +```sql +mysql> SELECT * FROM INFORMATION_SCHEMA.SSTS_INDEX_META LIMIT 1\G; +*************************** 1. row *************************** + table_dir: data/greptime/public/1814/ +index_file_path: data/greptime/public/1814/1814_0000000000/data/index/aba4af59-1247-4bfb-a20b-69242cdd9374.puffin + region_id: 7791070674944 + table_id: 1814 + region_number: 0 + region_group: 0 +region_sequence: 0 + file_id: aba4af59-1247-4bfb-a20b-69242cdd9374 +index_file_size: 838 + index_type: bloom_filter + target_type: column + target_key: 2147483652 + target_json: {"column":2147483652} + blob_size: 688 + meta_json: {"bloom":{"bloom_filter_size":640,"row_count":2242,"rows_per_segment":1024,"segment_count":3}} + node_id: 0 +1 row in set (0.02 sec) +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/ssts-manifest.md b/versioned_docs/version-1.0/reference/sql/information-schema/ssts-manifest.md new file mode 100644 index 0000000000..7fdad6a832 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/ssts-manifest.md @@ -0,0 +1,139 @@ +--- +keywords: [SST manifest, SST files, region files, file metadata, table data files] +description: Provides access to SST (Sorted String Table) file information from the manifest, including file paths, sizes, time ranges, and row counts. +--- + +# SSTS_MANIFEST + +The `SSTS_MANIFEST` table provides access to SST (Sorted String Table) file information collected from the manifest. This table surfaces detailed information about each SST file, including file paths, sizes, levels, time ranges, and row counts. + +:::tip NOTE +This table is not available on [GreptimeCloud](https://greptime.cloud/). +::: + +```sql +USE INFORMATION_SCHEMA; +DESC SSTS_MANIFEST; +``` + +The output is as follows: + +```sql ++------------------+---------------------+-----+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++------------------+---------------------+-----+------+---------+---------------+ +| table_dir | String | | NO | | FIELD | +| region_id | UInt64 | | NO | | FIELD | +| table_id | UInt32 | | NO | | FIELD | +| region_number | UInt32 | | NO | | FIELD | +| region_group | UInt8 | | NO | | FIELD | +| region_sequence | UInt32 | | NO | | FIELD | +| file_id | String | | NO | | FIELD | +| level | UInt8 | | NO | | FIELD | +| file_path | String | | NO | | FIELD | +| file_size | UInt64 | | NO | | FIELD | +| index_file_path | String | | YES | | FIELD | +| index_file_size | UInt64 | | YES | | FIELD | +| num_rows | UInt64 | | NO | | FIELD | +| num_row_groups | UInt64 | | NO | | FIELD | +| min_ts | TimestampNanosecond | | YES | | FIELD | +| max_ts | TimestampNanosecond | | YES | | FIELD | +| sequence | UInt64 | | YES | | FIELD | +| origin_region_id | UInt64 | | NO | | FIELD | +| node_id | UInt64 | | YES | | FIELD | +| visible | Boolean | | NO | | FIELD | ++------------------+---------------------+-----+------+---------+---------------+ +``` + +Fields in the `SSTS_MANIFEST` table are described as follows: + +- `table_dir`: The directory path of the table. +- `region_id`: The ID of the region that refers to the file. +- `table_id`: The ID of the table. +- `region_number`: The region number within the table. +- `region_group`: The group identifier for the region. +- `region_sequence`: The sequence number of the region. +- `file_id`: The unique identifier of the SST file (UUID). +- `level`: The SST level in the LSM tree (0 for uncompacted, 1 for compacted). +- `file_path`: The full path to the SST file in object storage. +- `file_size`: The size of the SST file in bytes. +- `index_file_path`: The full path to the index file in object storage (if exists). +- `index_file_size`: The size of the index file in bytes (if exists). +- `num_rows`: The number of rows in the SST file. +- `num_row_groups`: The number of row groups in the SST file. +- `min_ts`: The minimum timestamp in the SST file. +- `max_ts`: The maximum timestamp in the SST file. +- `sequence`: The sequence number associated with this file. +- `origin_region_id`: The ID of the region that created the file. +- `node_id`: The ID of the datanode where the file is located. +- `visible`: Whether this file is visible in the current version. + +## Examples + +Query all SST files in the manifest: + +```sql +SELECT * FROM INFORMATION_SCHEMA.SSTS_MANIFEST; +``` + +Query SST files for a specific table by joining with the `TABLES` table: + +```sql +SELECT s.* +FROM INFORMATION_SCHEMA.SSTS_MANIFEST s +JOIN INFORMATION_SCHEMA.TABLES t ON s.table_id = t.table_id +WHERE t.table_name = 'my_table'; +``` + +Query only compacted SST files (level 1): + +```sql +SELECT file_path, file_size, num_rows, level +FROM INFORMATION_SCHEMA.SSTS_MANIFEST +WHERE level = 1; +``` + +Query SST files with their time ranges: + +```sql +SELECT table_id, file_path, num_rows, min_ts, max_ts +FROM INFORMATION_SCHEMA.SSTS_MANIFEST +ORDER BY table_id, min_ts; +``` + +Calculate total SST file size per table: + +```sql +SELECT table_id, COUNT(*) as sst_count, SUM(file_size) as total_size +FROM INFORMATION_SCHEMA.SSTS_MANIFEST +GROUP BY table_id; +``` + + +Output example: + +```sql +mysql> SELECT * FROM INFORMATION_SCHEMA.SSTS_MANIFEST LIMIT 1\G; +*************************** 1. row *************************** + table_dir: data/greptime/public/1024/ + region_id: 4398046511104 + table_id: 1024 + region_number: 0 + region_group: 0 + region_sequence: 0 + file_id: 01234567-89ab-cdef-0123-456789abcdef + level: 0 + file_path: data/greptime/public/1024/4398046511104_0/01234567-89ab-cdef-0123-456789abcdef.parquet + file_size: 1234 + index_file_path: data/greptime/public/1024/4398046511104_0/index/01234567-89ab-cdef-0123-456789abcdef.puffin + index_file_size: 256 + num_rows: 100 + num_row_groups: 1 + min_ts: 2025-01-01 00:00:00.000000000 + max_ts: 2025-01-01 00:01:00.000000000 + sequence: 1 +origin_region_id: 4398046511104 + node_id: 0 + visible: true +1 row in set (0.02 sec) +``` diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/ssts-storage.md b/versioned_docs/version-1.0/reference/sql/information-schema/ssts-storage.md new file mode 100644 index 0000000000..0f5ce2d337 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/ssts-storage.md @@ -0,0 +1,104 @@ +--- +keywords: [SST storage, SST files, file listing, storage layer, object storage] +description: Provides access to SST (Sorted String Table) file information from the storage layer, including file paths, sizes, and last modified timestamps. +--- + +# SSTS_STORAGE + +The `SSTS_STORAGE` table provides access to SST (Sorted String Table) file information listed directly from the storage layer. This table shows raw file metadata from object storage, which may include files that are not yet reflected in the manifest or files that have been orphaned. + +:::tip NOTE +This table is not available on [GreptimeCloud](https://greptime.cloud/). +::: + +```sql +USE INFORMATION_SCHEMA; +DESC SSTS_STORAGE; +``` + +The output is as follows: + +```sql ++------------------+----------------------+-----+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++------------------+----------------------+-----+------+---------+---------------+ +| file_path | String | | NO | | FIELD | +| file_size | UInt64 | | YES | | FIELD | +| last_modified_ms | TimestampMillisecond | | YES | | FIELD | +| node_id | UInt64 | | YES | | FIELD | ++------------------+----------------------+-----+------+---------+---------------+ +``` + +Fields in the `SSTS_STORAGE` table are described as follows: + +- `file_path`: The full path to the file in object storage. +- `file_size`: The size of the file in bytes (if available from storage). +- `last_modified_ms`: The last modified time in milliseconds (if available from storage). +- `node_id`: The ID of the datanode where the file is located. + +## Use Cases + +The `SSTS_STORAGE` table is useful for: + +- **Storage verification**: Compare files in storage against the manifest to detect orphaned files or inconsistencies. +- **Storage debugging**: Identify files that exist in storage but may not be properly tracked in the manifest. +- **Cleanup operations**: Find and remove orphaned SST files that are no longer referenced. +- **Storage auditing**: Get a complete view of all SST files in the storage layer. + +## Examples + +Query all SST files in storage: + +```sql +SELECT * FROM INFORMATION_SCHEMA.SSTS_STORAGE; +``` + +Find files in storage that are not in the manifest (potential orphaned files): + +```sql +SELECT s.file_path, s.file_size, s.last_modified_ms +FROM INFORMATION_SCHEMA.SSTS_STORAGE s +LEFT JOIN INFORMATION_SCHEMA.SSTS_MANIFEST m ON s.file_path = m.file_path +WHERE m.file_path IS NULL; +``` + +Find the largest SST files in storage: + +```sql +SELECT file_path, file_size +FROM INFORMATION_SCHEMA.SSTS_STORAGE +WHERE file_size IS NOT NULL +ORDER BY file_size DESC +LIMIT 10; +``` + +Calculate total storage usage by SST files: + +```sql +SELECT COUNT(*) as file_count, SUM(file_size) as total_size +FROM INFORMATION_SCHEMA.SSTS_STORAGE +WHERE file_size IS NOT NULL; +``` + + +Output example: + +```sql +mysql> SELECT * FROM INFORMATION_SCHEMA.SSTS_STORAGE LIMIT 1\G; +*************************** 1. row *************************** + file_path: data/greptime/public/1024/4398046511104_0/01234567-89ab-cdef-0123-456789abcdef.parquet + file_size: 1234 +last_modified_ms: 2025-01-01 00:00:00.000 + node_id: 0 +1 row in set (0.02 sec) +``` + +## Differences from SSTS_MANIFEST + +| Aspect | SSTS_MANIFEST | SSTS_STORAGE | +|--------|---------------|--------------| +| **Data Source** | Manifest metadata | Storage layer directly | +| **Information** | Detailed SST metadata (rows, time ranges, etc.) | Basic file metadata only | +| **File Coverage** | Only files tracked in manifest | All files in storage | +| **Use Case** | Query SST metadata for analysis | Verify storage, find orphaned files | +| **Performance** | Fast (reads from manifest) | Slower (scans storage) | diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/table-constraints.md b/versioned_docs/version-1.0/reference/sql/information-schema/table-constraints.md new file mode 100644 index 0000000000..6516d04d09 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/table-constraints.md @@ -0,0 +1,60 @@ +--- +keywords: [table constraints, SQL, database constraints, constraint properties, constraint types] +description: Describes which tables have constraints, including details about each constraint's catalog, schema, name, type, and enforcement status. +--- + +# TABLE_CONSTRAINTS + +The `TABLE_CONSTRAINTS` table describes which tables have constraints. + +```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 | ++--------------------+--------+------+------+---------+---------------+ +``` + +The columns in the table: + +* `CONSTRAINT_CATALOG`: The name of the catalog to which the constraint belongs. This value is always `def`. +* `CONSTRAINT_SCHEMA`: The name of the database to which the constraint belongs. +* `CONSTRAINT_NAME`: The name of the constraint, `TIME INDEX` or `PRIMARY`. +* `TABLE_NAME`: The name of the table. +* `CONSTRAINT_TYPE`: The type of the constraint. The value can be `TIME INDEX` or `PRIMARY KEY`. The `TIME INDEX` and `PRIMARY KEY` information is similar to the execution result of the `SHOW INDEX` statement. +* `enforced`: Doesn't support `CHECK` constraints, the value is always` YES`. + +```sql +select * from INFORMATION_SCHEMA.table_constraints WHERE table_name = 'monitor'\G; +``` + +The output: + +```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/versioned_docs/version-1.0/reference/sql/information-schema/tables.md b/versioned_docs/version-1.0/reference/sql/information-schema/tables.md new file mode 100644 index 0000000000..437e34f075 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/tables.md @@ -0,0 +1,111 @@ +--- +keywords: [tables, information schema, SQL, database tables, table properties] +description: Provides information about tables in databases, including details about each table's catalog, schema, name, type, and other properties. +--- + +# TABLES + +The `TABLES` table provides information about tables in databases: + +```sql +USE INFORMATION_SCHEMA; +DESC TABLES; +``` + +The output is as follows: + +```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 | TimestampSecond | | YES | | FIELD | +| update_time | TimestampSecond | | YES | | FIELD | +| check_time | TimestampSecond | | 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) +``` + +The following statements are equivalent: + +```sql +SELECT table_name FROM INFORMATION_SCHEMA.TABLES + WHERE table_schema = '' + [AND table_name LIKE 'monitor'] + +SHOW TABLES + FROM db_name + [LIKE 'monitor'] +``` + +The description of columns in the `TABLES` table is as follows: + +- `table_catalog`: The catalog to which the table belongs. The value is always `greptime`. +- `table_schema`: The database to which the table belongs. +- `table_name`: The name of the table. +- `table_type`: The type of the table. + - `BASE TABLE` for a table. + - `TEMPORARY` for a temporary result set. + - `VIEW` for a view. +- `table_id`: The ID of the table. +- `data_length`: The table size, representing the total length of the table's SST files in bytes. This is an approximate value. +- `index_length`: The size of all indexes of the table, representing the total length of the table's index files in bytes. This is an approximate value. +- `table_rows`: The table's total row number, which is an approximate value. +- `avg_row_length`: The average row length in bytes, which is an approximate value. +- `engine`: The storage engine of the table used. +- `version`: Version. The value is `11` by default. +- `create_time`: The table created timestamp. +- `table_comment`: The table comment. +- Other columns such as `auto_increment`, `row_format` etc. are not supported, just for compatibility with MySQL. GreptimeDB may support some of them in the future. diff --git a/versioned_docs/version-1.0/reference/sql/information-schema/views.md b/versioned_docs/version-1.0/reference/sql/information-schema/views.md new file mode 100644 index 0000000000..9ae21f1bd6 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/information-schema/views.md @@ -0,0 +1,42 @@ +--- +keywords: [views, information schema, SQL, database views, view properties] +description: Provides a list of views that the current user has visibility of, including details about each view's catalog, schema, name, definition, and other properties. +--- + +# VIEWS + +The `VIEWS` table provides a list of views that the current user has visibility of. + +```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 | ++----------------------+---------+------+------+---------+---------------+ +``` + +The columns in table: + +* `table_catalog`: The name of the catalog to which the view belongs. +* `table_schema`: The name of the database to which the view belongs. +* `table_name`: The view name. +* `view_definition`: The definition of view, which is made by the `SELECT` statement when the view is created. +* `check_option`: Doesn't support, is always `NULL`. +* `is_updatable`: Whether `UPDATE/INSERT/DELETE` is applicable to the view, always `NO`. +* `definer`: The name of the user who creates the view. +* `security_type`: Doesn't support, is always `NULL`. +* `character_set_client`: The value of the `character_set_client` session variable when the view is created, is always `utf8`. +* `collation_connection`: The value of the `collation_connection` session variable when the view is created, is always `utf8_bin`. diff --git a/versioned_docs/version-1.0/reference/sql/insert.md b/versioned_docs/version-1.0/reference/sql/insert.md new file mode 100644 index 0000000000..e713332c2d --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/insert.md @@ -0,0 +1,143 @@ +--- +keywords: [SQL INSERT, SQL syntax, SQL examples, inserting records, SQL data manipulation] +description: Describes the SQL INSERT statement for adding records to a table in GreptimeDB, including syntax, examples for inserting single and multiple records, default values, binary data, special numeric values, and the INSERT INTO SELECT statement. +--- + +# INSERT + +The `INSERT` statement is used to insert one or more records into a table in the GreptimeDB. + +## `INSERT INTO` Statement + +### Syntax + +The syntax for the INSERT INTO statement is as follows: + +```sql +INSERT INTO table_name (column1, column2, column3, ...) +VALUES (value1, value2, value3, ...); +``` + +In the above syntax, `table_name` is the name of the table into which you want to insert data, +and `column1`, `column2`, `column3`, etc. are the names of the columns in the table. +You can specify the columns in the `INSERT INTO` statement if you want to insert data into specific columns. +If you do not specify the columns, the values will be inserted into all the columns in the table. + +The `VALUES` keyword is followed by a list of values that correspond to the columns in the `INSERT INTO` +statement. The values must be in the same order as the columns. + +The following types of values are supported: + +- The `DEFAULT` keyword specifies that the default value for that column should be inserted. +This is useful when you do not want to explicitly specify values for some columns when inserting records. +It allows the column's default value, as defined in the table schema, to be used instead. +If no default value is defined for the column, the database's default value will be used (often NULL). +- Use hexadecimal literal to insert a literal binary. +- use the `{Value}::{Type}` syntax to cast the special numeric values `Infinity`, `-Infinity`, and `NaN` into the desired numeric type. + +### Examples + +#### Insert Data + +Here is an example of an `INSERT INTO` statement that inserts a record into a table named `system_metrics`: + +```sql +INSERT INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES + ("host1", "idc_b", 50.0, 66.7, 40.6, 1667446797462); +``` + +This statement inserts a record with the host "host1", idc "idc_b", cpu_util 50.0, memory_util 66.7, +disk_util 40.6, ts 1667446797462 into the `system_metrics` table. + +You can also use the `INSERT INTO` statement to insert multiple records into a table at the same time. +Here is an example of an `INSERT INTO` statement that inserts multiple records into the `system_metrics` table: + +```sql +INSERT INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES + ("host1", "idc_a", 11.8, 10.3, 10.3, 1667446797460), + ("host2", "idc_a", 80.1, 70.3, 90.0, 1667446797461), + ("host1", "idc_c", 50.1, 66.8, 40.8, 1667446797463); +``` + +This statement inserts three records into the `system_metrics` table with the specified values for each column. + +#### Insert Data with Default Values + +The following sql statement use `DEFAULT` keyword to insert the default value for the `cpu_util` column: + +```sql +INSERT INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES ("host1", "idc_a", DEFAULT, 10.3, 10.3, 1667446797460); +``` + +#### Insert Binary Data + +When we want to insert binary data which their column datatypes are `blob` or `bytea`: + +```sql +CREATE TABLE test(b BLOB, ts TIMESTAMP TIME INDEX); +``` + +Recommend using the prepared statement, JDBC for example: + +```java + PreparedStatement pstmt = conn.prepareStatement("insert into test values(?,?)"); + pstmt.setBytes(1, "hello".getBytes()); + pstmt.setInt(2, 1687867163); + pstmt.addBatch(); + ...... + pstmt.executeBatch(); +``` + +If we want to insert a literal binary, we can insert a hexadecimal literal: + +```sql +INSERT INTO test VALUES(X'9fad5e9eefdfb449', 1687867163); +-- or -- +INSERT INTO test VALUES(0x9fad5e9eefdfb449', 1687867163); +``` + +#### Insert Special Numeric Values + +Use `{Value}::{Type}` to cast `Infinity`, `-Infinity`, and `NaN` into the desired numeric type: + +```sql +INSERT INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES ("host1", "idc_a", 66.6, 'NaN'::double, 'Infinity'::double, 1667446797460); +``` + +## `INSERT INTO SELECT` Statement + +The statement copies data from one table and inserts it into another table. + +### Syntax + +The syntax for the `INSERT INTO SELECT` statement is as follows: + +```sql +INSERT INTO table2 (column1, column2, ...) +SELECT column1, column2, ... +FROM table1; +``` + +In the above syntax, `table1` is the source table from which you want to copy data, and `table2` is the target table +into which the data will be inserted. +`table1` and `table2` should have the same names and data types for the columns that you want to copy. +The `SELECT` statement selects the columns you want to insert from the source +table. If you do not specify the column names in the `INSERT INTO` statement, then the data will be inserted into +all columns in the target table. + +The `INSERT INTO SELECT` statement is useful when you want to copy data from one table to another, for example when +archiving or backing up data. It is more efficient than creating a backup of the entire database and restoring it. + +### Examples + +Here is an example of an `INSERT INTO SELECT` statement: + +```sql +INSERT INTO system_metrics2 (host, idc, cpu_util, memory_util, disk_util, ts) +SELECT host, idc, cpu_util, memory_util, disk_util, ts +FROM system_metrics; +``` diff --git a/versioned_docs/version-1.0/reference/sql/join.md b/versioned_docs/version-1.0/reference/sql/join.md new file mode 100644 index 0000000000..226cde5ce0 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/join.md @@ -0,0 +1,40 @@ +--- +keywords: [SQL JOIN, INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, SQL examples, SQL syntax] +description: Explains the usage of SQL JOIN clauses to combine rows from multiple tables based on related columns, including INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN, with examples. +--- + +# JOIN + +`JOIN` is used to combine rows from two or more tables based on a related column between them. +It allows you to extract data from multiple tables and present it as a single result set. + +There are several types of JOIN clauses: + +- INNER JOIN: Returns only the rows that have matching values in both tables. +- LEFT JOIN: Returns all the rows from the left table and the matching rows from the right table. +- RIGHT JOIN: Returns all the rows from the right table and the matching rows from the left table. +- FULL OUTER JOIN: Returns all the rows from both tables. + +## Examples + +Here are some examples of using JOIN clauses: + +```sql +-- Select all rows from the system_metrics table and idc_info table where the idc_id matches +SELECT a.* +FROM system_metrics a +JOIN idc_info b +ON a.idc = b.idc_id; + +-- Select all rows from the idc_info table and system_metrics table where the idc_id matches, and include null values for idc_info without any matching system_metrics +SELECT a.* +FROM idc_info a +LEFT JOIN system_metrics b +ON a.idc_id = b.idc; + +-- Select all rows from the system_metrics table and idc_info table where the idc_id matches, and include null values for idc_info without any matching system_metrics +SELECT b.* +FROM system_metrics a +RIGHT JOIN idc_info b +ON a.idc = b.idc_id; +``` diff --git a/versioned_docs/version-1.0/reference/sql/limit.md b/versioned_docs/version-1.0/reference/sql/limit.md new file mode 100644 index 0000000000..d2057158dd --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/limit.md @@ -0,0 +1,89 @@ +--- +keywords: [SQL LIMIT, SQL query optimization, SQL syntax, SQL examples, SQL performance] +description: Describes the LIMIT clause in SQL for restricting the number of rows returned by a query, including syntax and examples. +--- + +# LIMIT + +`LIMIT` clause is used to limit the number of rows returned by a query. This clause is particularly +useful when working with large data sets, as it allows for faster query performance by reducing the +amount of data that needs to be processed. + +## Syntax + +The basic syntax of the `LIMIT` clause is as follows: + +```sql +SELECT column1, column2, ... +FROM table_name +LIMIT number_of_rows; +``` + +The number_of_rows parameter specifies the maximum number of rows to be returned. If the value of this parameter is negative, no rows will be returned. + +## Examples + +Consider the following table named "system_metrics": + +```sql ++-------+-------+----------+-------------+-----------+---------------------+ +| host | idc | cpu_util | memory_util | disk_util | ts | ++-------+-------+----------+-------------+-----------+---------------------+ +| host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 | +| host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 | +| host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 | ++-------+-------+----------+-------------+-----------+---------------------+ +``` + +To retrieve the top 3 rows by `memory_util`, we can use the`LIMIT` clause: + +```sql +SELECT host, idc, memory_util +FROM system_metrics +ORDER BY memory_util DESC +LIMIT 3; +``` + +The result of the above query would be: + +```sql ++-------+-------+-------------+ +| host | idc | memory_util | ++-------+-------+-------------+ +| host2 | idc_a | 70.3 | +| host1 | idc_c | 66.8 | +| host1 | idc_b | 66.7 | ++-------+-------+-------------+ +``` + +`LIMIT n, m` allows to select the m rows from the result after skipping the first n rows. The `LIMIT m OFFSET n` syntax +is equivalent. + +```sql +SELECT host, idc, memory_util +FROM system_metrics +ORDER BY memory_util DESC +LIMIT 2 OFFSET 1; +``` + +OR + +```sql +SELECT host, idc, memory_util +FROM system_metrics +ORDER BY memory_util DESC +LIMIT 1, 2; +``` + +The result of the above query would be: + +```sql ++-------+-------+-------------+ +| host | idc | memory_util | ++-------+-------+-------------+ +| host1 | idc_c | 66.8 | +| host1 | idc_b | 66.7 | ++-------+-------+-------------+ +``` diff --git a/versioned_docs/version-1.0/reference/sql/offset.md b/versioned_docs/version-1.0/reference/sql/offset.md new file mode 100644 index 0000000000..652669e66c --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/offset.md @@ -0,0 +1,45 @@ +--- +keywords: [SQL OFFSET clause, data retrieval, skipping rows] +description: Describes the OFFSET clause in SQL, which specifies how many rows to skip before starting to return rows from a query. +--- + +# OFFSET + +The `OFFSET` clause specifies how many rows to skip before starting to return rows from a query. It's commonly used with LIMIT for paginating through large result sets. + +For example: +```sql +SELECT * +FROM system_metrics +ORDER BY cpu_util DESC +LIMIT 10 +OFFSET 10; +``` + +It selects all columns from rows ranked 11th to 20th (by descending `cpu_util`) from the `system_metrics` table. + +Although combining `OFFSET` and `LIMIT` with an `ORDER BY` clause can achieve pagination, this approach is not very efficient. We recommend recording the time index (timestamp) of the last record returned on each page and using this value to filter and limit the data for subsequent pages. This method provides much better pagination performance. + +## Efficient Pagination Using Timestamps +Suppose your `system_metrics` table has a `ts` column that acts as a time index (timestamp). You can use the last record’s timestamp from the previous page to efficiently fetch the next page. + +First Page (Latest 10 Records): +```sql +SELECT * +FROM system_metrics +ORDER BY ts DESC +LIMIT 10; +``` + +Second Page (Using Last Timestamp from Previous Page): If the last record from the first page has a `ts` value of `'2024-07-01 16:03:00'`, you can get the next page like this: + +```sql +SELECT * +FROM system_metrics +WHERE ts < '2024-07-01 16:03:00' +ORDER BY ts DESC +LIMIT 10; +``` + +After each query, record the `ts` value of the last row and use it for the next query’s filter. +This method eliminates the need to scan and skip rows (as with OFFSET), making pagination much more efficient, especially for large tables. diff --git a/versioned_docs/version-1.0/reference/sql/order_by.md b/versioned_docs/version-1.0/reference/sql/order_by.md new file mode 100644 index 0000000000..ffc2f5c08c --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/order_by.md @@ -0,0 +1,80 @@ +--- +keywords: [SQL ORDER BY clause, sorting data, ascending order, descending order, SQL syntax] +description: Details the ORDER BY clause in SQL for sorting data in ascending or descending order based on one or more columns, with syntax and examples. +--- + +# ORDER BY + +The `ORDER BY` clause is used to order the data in ascending or descending order based on one or more columns in the +`SELECT` statement. + +## Syntax + +The basic syntax of the `ORDER BY` clause is as follows: + +```sql +SELECT column1, column2, ... +FROM table_name +ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...; +``` + +The `ORDER BY` clause can be used with one or more columns. The ASC keyword is used to sort the data +in ascending order (default), and the DESC keyword is used to sort the data in descending order. + +## Examples + +Consider the following table named "system_metrics": + +```sql ++-------+-------+----------+-------------+-----------+---------------------+ +| host | idc | cpu_util | memory_util | disk_util | ts | ++-------+-------+----------+-------------+-----------+---------------------+ +| host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 | +| host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 | +| host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 | ++-------+-------+----------+-------------+-----------+---------------------+ +``` + +To sort the data in ascending order based on the "memory_util" column, the following SQL query can be used: + +```sql +SELECT * FROM system_metrics +ORDER BY memory_util ASC; +``` + +The result of the above query would be: + +```sql ++-------+-------+----------+-------------+-----------+---------------------+ +| host | idc | cpu_util | memory_util | disk_util | ts | ++-------+-------+----------+-------------+-----------+---------------------+ +| host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 | +| host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 | +| host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 | ++-------+-------+----------+-------------+-----------+---------------------+ +``` + +To sort the data in descending order based on the "disk_util" column, the following SQL query can be used: + +```sql +SELECT * FROM system_metrics +ORDER BY disk_util DESC; +``` + +The result of the above query would be: + +```sql ++-------+-------+----------+-------------+-----------+---------------------+ +| host | idc | cpu_util | memory_util | disk_util | ts | ++-------+-------+----------+-------------+-----------+---------------------+ +| host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 | +| host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 | +| host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 | +| host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 | ++-------+-------+----------+-------------+-----------+---------------------+ +``` diff --git a/versioned_docs/version-1.0/reference/sql/overview.md b/versioned_docs/version-1.0/reference/sql/overview.md new file mode 100644 index 0000000000..764c1340b1 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/overview.md @@ -0,0 +1,47 @@ +--- +keywords: [SQL syntax, SQL examples] +description: GreptimeDB SQL statements. +--- + +# SQL + +## Data Types +* [Data Types](data-types.md) + +## Statements and Clauses +* [ADMIN](./admin.md) +* [ALTER](./alter.md) +* [ANSI Compatibility](./compatibility.md) +* [CASE](./case.md) +* [CAST](./cast.md) +* [COPY](./copy.md) +* [CREATE](./create.md) +* [DELETE](./delete.md) +* [DESCRIBE TABLE](./describe_table.md) +* [DISTINCT](./distinct.md) +* [DROP](./drop.md) +* [EXPLAIN](./explain.md) +* [GROUP BY](./group_by.md) +* [HAVING](./having.md) +* [INSERT](./insert.md) +* [JOIN](./join.md) +* [LIMIT](./limit.md) +* [OFFSET](./offset.md) +* [ORDER BY](./order_by.md) +* [RANGE](./range.md) +* [REPLACE](./replace.md) +* [SELECT](./select.md) +* [SHOW](./show.md) +* [TQL](./tql.md) +* [TRUNCATE](./truncate.md) +* [WHERE](./where.md) +* [WITH](./with.md) + +## Functions +* [Functions](./functions/overview.md) + +## Information Schema +* [INFORMATION_SCHEMA](./information-schema/overview.md) + +## Greptime Private +* [Greptime Private](./greptime-private/overview.md) diff --git a/versioned_docs/version-1.0/reference/sql/range.md b/versioned_docs/version-1.0/reference/sql/range.md new file mode 100644 index 0000000000..555fd08338 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/range.md @@ -0,0 +1,740 @@ +--- +keywords: [range queries, time series data, SQL syntax, FILL options, TO options, BY options, ORDER BY, nested range expressions] +description: Explains range queries in SQL for time series data, including syntax, FILL options, TO options, BY options, ORDER BY in aggregate functions, and nested range expressions. +--- + +# RANGE QUERY + +Querying and aggregating data within a range of time is a common query pattern for time series data, such as the `Range selector` in `PromQL`. GreptimeDB supports Range queries in SQL, which is used to summarize time series data into time chunks and aggregate data on time chunks. As part of the `SELECT` statement, Range query can be flexibly combined with SQL to provide more powerful time series data query capabilities in SQL. + +## Syntax + +Range query uses `Time Index` column as the timeline basis for aggregation. A legal Range query syntax structure is as follows: + +```sql +SELECT + AGGR_FUNCTION(column1, column2,..) RANGE INTERVAL [FILL FILL_OPTION], + ... +FROM table_name + [ WHERE ] +ALIGN INTERVAL [ TO TO_OPTION ] [BY (columna, columnb,..)] [FILL FILL_OPTION] + [ ORDER BY ] +[ LIMIT ]; + +INTERVAL := TIME_INTERVAL | ( INTERVAL expr ) +``` + +- Keyword `ALIGN`, required field, followed by parameter `INTERVAL`, `ALIGN` specifies the step of Range query. + - Subkeyword `TO`, optional field, specifies the time point to which Range query is aligned. For legal `TO_OPTION` parameters, see [TO Option](#to-option). + - Subkeyword `BY`, optional field, followed by parameter `(columna, columnb,..)`, describes the aggregate key. For legal `BY_OPTION` parameters, see [BY Option](#by-option). +- The parameter `INTERVAL` is mainly used to give the length of a period of time. There are two parameter forms: + - Strings based on the `PromQL Time Durations` format (eg: `3h`, `1h30m`). Visit the [Prometheus documentation](https://prometheus.io/docs/prometheus/latest/querying/basics/#float-literals-and-time-durations) for a more detailed description of this format. + - `Interval` type. To use the `Interval` type, you need to carry parentheses, (for example: `('1 year 3 hours 20 minutes'::INTERVAL)`). Visit [Interval](./data-types.md#interval-type) for a more detailed description of this format. +- `AGGR_FUNCTION(column1, column2,..) RANGE INTERVAL [FILL FILL_OPTION]` is called a Range expression. + - `AGGR_FUNCTION(column1, column2,..)` is an aggregate function that represents the expression that needs to be aggregated. + - Keyword `RANGE`, required field, followed by parameter `INTERVAL` specifies the time range of each data aggregation. + - Keyword `FILL`, optional field, please see [`FILL` Option](#fill-option) for details. + - Range expressions can be combined with other operations to implement more complex queries. For details, see [Nested Range Expressions](#nested-range-expressions). +- `FILL` keyword after `ALIGN`, optional field. See [FILL Option](#fill-option) for details. + +## `FILL` Option + +The `FILL` option specifies the data filling method when there is no data in an aggregated time slot, or the value of the aggregate field is empty. + +The `FILL` keyword can be used after the `RANGE` keyword to indicate the filling method for the Range expression. +The `FILL` keyword can also be used after the `ALIGN` keyword to specify the default filling method for a Range expression +if no fill option is provided. + +For example, in the following SQL code, +the `max(val) RANGE '10s'` Range expression uses the fill option `LINEAR`, while the `min(val) RANGE '10s'` Range expression, +which does not specify a fill option, uses the fill option `PREV` specified after the `ALIGN` keyword. + +```sql +SELECT + ts, + host, + min(val) RANGE '10s', + max(val) RANGE '10s' FILL LINEAR +FROM host_val +ALIGN '5s' BY (host) FILL PREV; +``` + +`FILL` has the following filling methods: + +| FILL | DESCRIPTION | +| :------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| `NULL` | Fill directly with `NULL` | +| `PREV` | Fill with data from previous point | +| `LINEAR` | Use [linear interpolation](https://en.wikipedia.org/wiki/Linear_interpolation) to fill the data. If an integer type is filled with `LINEAR`, the variable type of the column will be implicitly converted to a floating point type during calculation | +| `X` | Fill in a constant, the data type of the constant must be consistent with the variable type of the Range expression | + +Take the following table as an example: + +```sql +DROP TABLE IF EXISTS host_val; +CREATE TABLE host_val ( + ts TIMESTAMP TIME INDEX, + host STRING, + val DOUBLE, + PRIMARY KEY (host) +); + +INSERT INTO host_val VALUES + ('1970-01-01 00:00:00', 'host1', 0), + ('1970-01-01 00:00:15', 'host1', 6), + ('1970-01-01 00:00:00', 'host2', 6), + ('1970-01-01 00:00:15', 'host2', 12); +``` + +```sql ++---------------------+-------+------+ +| ts | host | val | ++---------------------+-------+------+ +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:15 | host1 | 6 | +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:15 | host2 | 12 | ++---------------------+-------+------+ +``` + +The result of each `FILL` option is as follows: + + + + + +```sql +SELECT ts, host, min(val) RANGE '5s' FROM host_val ALIGN '5s'; +``` + +```sql ++---------------------+-------+----------------------------+ +| ts | host | min(host_val.val) RANGE 5s | ++---------------------+-------+----------------------------+ +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:15 | host1 | 6 | +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:15 | host2 | 12 | ++---------------------+-------+----------------------------+ +``` + + + + + +```sql +SELECT ts, host, min(val) RANGE '5s' FILL NULL FROM host_val ALIGN '5s'; +``` + +```sql ++---------------------+-------+--------------------------------------+ +| ts | host | min(host_val.val) RANGE 5s FILL NULL | ++---------------------+-------+--------------------------------------+ +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:05 | host2 | NULL | +| 1970-01-01 00:00:10 | host2 | NULL | +| 1970-01-01 00:00:15 | host2 | 12 | +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:05 | host1 | NULL | +| 1970-01-01 00:00:10 | host1 | NULL | +| 1970-01-01 00:00:15 | host1 | 6 | ++---------------------+-------+--------------------------------------+ + +``` + + + + + +```sql +SELECT ts, host, min(val) RANGE '5s' FILL PREV FROM host_val ALIGN '5s'; +``` + +```sql ++---------------------+-------+--------------------------------------+ +| ts | host | min(host_val.val) RANGE 5s FILL PREV | ++---------------------+-------+--------------------------------------+ +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:05 | host1 | 0 | +| 1970-01-01 00:00:10 | host1 | 0 | +| 1970-01-01 00:00:15 | host1 | 6 | +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:05 | host2 | 6 | +| 1970-01-01 00:00:10 | host2 | 6 | +| 1970-01-01 00:00:15 | host2 | 12 | ++---------------------+-------+--------------------------------------+ +``` + + + + + +```sql +SELECT ts, host, min(val) RANGE '5s' FILL LINEAR FROM host_val ALIGN '5s'; +``` + +```sql ++---------------------+-------+----------------------------------------+ +| ts | host | min(host_val.val) RANGE 5s FILL LINEAR | ++---------------------+-------+----------------------------------------+ +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:05 | host2 | 8 | +| 1970-01-01 00:00:10 | host2 | 10 | +| 1970-01-01 00:00:15 | host2 | 12 | +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:05 | host1 | 2 | +| 1970-01-01 00:00:10 | host1 | 4 | +| 1970-01-01 00:00:15 | host1 | 6 | ++---------------------+-------+----------------------------------------+ +``` + + + + + +```sql [FILL Constant Value 6.0] +SELECT ts, host, min(val) RANGE '5s' FILL 6 FROM host_val ALIGN '5s'; +``` + +```sql ++---------------------+-------+-----------------------------------+ +| ts | host | min(host_val.val) RANGE 5s FILL 6 | ++---------------------+-------+-----------------------------------+ +| 1970-01-01 00:00:00 | host2 | 6 | +| 1970-01-01 00:00:05 | host2 | 6 | +| 1970-01-01 00:00:10 | host2 | 6 | +| 1970-01-01 00:00:15 | host2 | 12 | +| 1970-01-01 00:00:00 | host1 | 0 | +| 1970-01-01 00:00:05 | host1 | 6 | +| 1970-01-01 00:00:10 | host1 | 6 | +| 1970-01-01 00:00:15 | host1 | 6 | ++---------------------+-------+-----------------------------------+ +``` + + + + + +If there are multiple Range expressions but only one of them specifies the `Fill` option, the other Range expressions will use the `FILL NULL` method to fill in the missing time slots. +The following two SQL statements are equivalent in output: + +```sql +SELECT + ts, + host, + min(val) RANGE '10s', + max(val) RANGE '10s' FILL LINEAR +FROM host_val +ALIGN '5s'; +``` + +```sql +SELECT + ts, + host, + min(val) RANGE '10s' FILL NULL, + max(val) RANGE '10s' FILL LINEAR +FROM host_val +ALIGN '5s'; +``` + +The result of the above SQL is as follows: + +```sql ++---------------------+-------+---------------------------------------+-----------------------------------------+ +| ts | host | min(host_val.val) RANGE 10s FILL NULL | max(host_val.val) RANGE 10s FILL LINEAR | ++---------------------+-------+---------------------------------------+-----------------------------------------+ +| 1969-12-31 23:59:55 | host1 | 0 | 0 | +| 1970-01-01 00:00:00 | host1 | 0 | 0 | +| 1970-01-01 00:00:05 | host1 | NULL | 2.9999999999999996 | +| 1970-01-01 00:00:10 | host1 | 6 | 6 | +| 1970-01-01 00:00:15 | host1 | 6 | 6 | +| 1969-12-31 23:59:55 | host2 | 6 | 6 | +| 1970-01-01 00:00:00 | host2 | 6 | 6 | +| 1970-01-01 00:00:05 | host2 | NULL | 9 | +| 1970-01-01 00:00:10 | host2 | 12 | 12 | +| 1970-01-01 00:00:15 | host2 | 12 | 12 | ++---------------------+-------+---------------------------------------+-----------------------------------------+ +``` + +## `TO` Option + +The `TO` keyword specifies the origin time point to which the range query is aligned. +`TO` option along with `RANGE` option and `ALIGN INTERVAL` determine the time range windows. +Please refer to [Time Range Window](/user-guide/query-data/sql.md#time-range-window) for details. + +The default value of the `TO` option is the current query client timezone. To set the timezone, +please refer to [MySQL client](/user-guide/protocols/mysql.md#time-zone) or [PostgreSQL client](/user-guide/protocols/postgresql.md#time-zone). +Other valid `TO` options are: + +| TO | DESCRIPTION | +| :---------: | :----------------------------------------------------------------------------------: | +| `NOW` | Align to current query time | +| `Timestamp` | Align to a user-specified timestamp, supports timestamp format `RFC3339` / `ISO8601` | + + +Suppose we have a table `host_val` with the following data: + +```sql +DROP TABLE IF EXISTS host_val; +CREATE TABLE host_val ( + ts TIMESTAMP TIME INDEX, + host STRING, + val DOUBLE, + PRIMARY KEY (host) +); + +INSERT INTO host_val VALUES + ('2023-01-01 23:00:00', 'host1', 0), + ('2023-01-02 01:00:00', 'host1', 1), + ('2023-01-01 23:00:00', 'host2', 2), + ('2023-01-02 01:00:00', 'host2', 3); +``` + +```sql ++---------------------+-------+------+ +| ts | host | val | ++---------------------+-------+------+ +| 2023-01-01 23:00:00 | host1 | 0 | +| 2023-01-02 01:00:00 | host1 | 1 | +| 2023-01-01 23:00:00 | host2 | 2 | +| 2023-01-02 01:00:00 | host2 | 3 | ++---------------------+-------+------+ +``` + +The query results by each `TO` options shown below: + + + + + +```sql +-- Querying the database timezone using the MySQL protocol, currently in the UTC timezone +SELECT @@time_zone; +``` + +```sql ++-------------+ +| @@time_zone | ++-------------+ +| UTC | ++-------------+ +``` + +```sql +-- If we do not specify the `TO` keyword, +-- the timezone will be used as the default origin alignment time. +SELECT ts, host, min(val) RANGE '1d' FROM host_val ALIGN '1d'; +``` + +```sql ++---------------------+-------+----------------------------+ +| ts | host | min(host_val.val) RANGE 1d | ++---------------------+-------+----------------------------+ +| 2023-01-01 00:00:00 | host1 | 0 | +| 2023-01-02 00:00:00 | host1 | 1 | +| 2023-01-01 00:00:00 | host2 | 2 | +| 2023-01-02 00:00:00 | host2 | 3 | ++---------------------+-------+----------------------------+ +``` + + + + + +```sql +-- If you want to align the origin time to the current time, +-- use the `NOW` keyword. +-- Assume that the current query time is `2023-01-02T09:16:40.503000`. +SELECT ts, host, min(val) RANGE '1d' FROM host_val ALIGN '1d' TO NOW; +``` + +```sql ++----------------------------+-------+----------------------------+ +| ts | host | min(host_val.val) RANGE 1d | ++----------------------------+-------+----------------------------+ +| 2023-01-01 09:54:55.456000 | host1 | 0 | +| 2023-01-01 09:54:55.456000 | host2 | 2 | ++----------------------------+-------+----------------------------+ + +``` + + + + + +```sql +-- If you want to align the origin time to a specific timestamp, +-- for example, "+08:00" Beijing time on December 1, 2023, +-- you can set the `TO` option to the specific timestamp '2023-01-01T00:00:00+08:00'. +SELECT ts, host, min(val) RANGE '1d' FROM host_val ALIGN '1d' TO '2023-01-01T00:00:00+08:00'; +``` + +```sql ++---------------------+-------+----------------------------+ +| ts | host | min(host_val.val) RANGE 1d | ++---------------------+-------+----------------------------+ +| 2023-01-01 16:00:00 | host1 | 0 | +| 2023-01-01 16:00:00 | host2 | 2 | ++---------------------+-------+----------------------------+ + +``` + + + + + +If you want to query data for a specific time range, you can specify the timestamp using the `TO` keyword. +For example, to query the daily minimum value of `val` between `00:45` and `06:45`, +you can use `2023-01-01T00:45:00` as the `TO` option along with a `6h` range. + +```sql +SELECT ts, host, min(val) RANGE '6h' FROM host_val ALIGN '1d' TO '2023-01-01T00:45:00'; +``` + +```sql ++---------------------+-------+----------------------------+ +| ts | host | min(host_val.val) RANGE 6h | ++---------------------+-------+----------------------------+ +| 2023-01-02 00:45:00 | host2 | 3 | +| 2023-01-02 00:45:00 | host1 | 1 | ++---------------------+-------+----------------------------+ +``` + +## `BY` Option + +`BY` option describes the aggregate key. If this field is not given, the primary key of the table is used as the aggregate key by default. If the table does not specify a primary key, the `BY` keyword cannot be omitted. + +Suppose we have a tale `host_val` with the following data: + +```sql +DROP TABLE IF EXISTS host_val; +CREATE TABLE host_val ( + ts TIMESTAMP TIME INDEX, + host STRING, + val DOUBLE, + PRIMARY KEY (host) +); + +INSERT INTO host_val VALUES + ('2023-01-01 23:00:00', 'host1', 0), + ('2023-01-02 01:00:00', 'host1', 1), + ('2023-01-01 23:00:00', 'host2', 2), + ('2023-01-02 01:00:00', 'host2', 3); +``` + +```sql ++---------------------+-------+------+ +| ts | host | val | ++---------------------+-------+------+ +| 2023-01-01 23:00:00 | host1 | 0 | +| 2023-01-02 01:00:00 | host1 | 1 | +| 2023-01-01 23:00:00 | host2 | 2 | +| 2023-01-02 01:00:00 | host2 | 3 | ++---------------------+-------+------+ +``` + +The following SQL uses `host` as the aggregate key: + +```sql +SELECT + ts, + host, + min(val) RANGE '10s' +FROM host_val ALIGN '5s' BY (host); +``` + +```sql ++---------------------+-------+-----------------------------+ +| ts | host | min(host_val.val) RANGE 10s | ++---------------------+-------+-----------------------------+ +| 2023-01-01 22:59:55 | host1 | 0 | +| 2023-01-01 23:00:00 | host1 | 0 | +| 2023-01-02 00:59:55 | host1 | 1 | +| 2023-01-02 01:00:00 | host1 | 1 | +| 2023-01-01 22:59:55 | host2 | 2 | +| 2023-01-01 23:00:00 | host2 | 2 | +| 2023-01-02 00:59:55 | host2 | 3 | +| 2023-01-02 01:00:00 | host2 | 3 | ++---------------------+-------+-----------------------------+ +``` + +You can also use the `BY` keyword to declare other columns as the basis for data aggregation. +For example, the following RANGE query uses the string length `length(host)` of the `host` column as the basis for data aggregation. + +```sql +SELECT + ts, + length(host), + min(val) RANGE '10s' +FROM host_val ALIGN '5s' BY (length(host)); +``` + +Get after running + +```sql ++---------------------+---------------------------------+-----------------------------+ +| ts | character_length(host_val.host) | min(host_val.val) RANGE 10s | ++---------------------+---------------------------------+-----------------------------+ +| 2023-01-01 22:59:55 | 5 | 0 | +| 2023-01-01 23:00:00 | 5 | 0 | +| 2023-01-02 00:59:55 | 5 | 1 | +| 2023-01-02 01:00:00 | 5 | 1 | ++---------------------+---------------------------------+-----------------------------+ +``` + +You can explicitly use `BY ()`, +which means you do not need to use aggregation keys and aggregate all data into a group. +**However, if you omit the `BY` keyword directly, it means using the primary key of the table as the aggregate key.** + +```sql +SELECT + ts, + min(val) RANGE '10s' +FROM host_val ALIGN '5s' BY (); +``` + +Get after running + +```sql ++---------------------+-----------------------------+ +| ts | min(host_val.val) RANGE 10s | ++---------------------+-----------------------------+ +| 2023-01-01 22:59:55 | 0 | +| 2023-01-01 23:00:00 | 0 | +| 2023-01-02 00:59:55 | 1 | +| 2023-01-02 01:00:00 | 1 | ++---------------------+-----------------------------+ +``` + +## `ORDER BY` option in aggregate functions + +Range queries support the use of `order by` expressions in the parameters of the `first_value` and `last_value` aggregate functions. By default, the data is sorted in ascending order based on the time index column. + +Take this table as an example: + +```sql +DROP TABLE IF EXISTS host_val; +CREATE TABLE host_val ( + ts TIMESTAMP TIME INDEX, + host STRING, + val DOUBLE, + addon DOUBLE, + PRIMARY KEY (host) +); + +INSERT INTO host_val VALUES + ('1970-01-01 00:00:00', 'host1', 0, 3), + ('1970-01-01 00:00:01', 'host1', 1, 2), + ('1970-01-01 00:00:02', 'host1', 2, 1); +``` + +```sql ++---------------------+-------+------+-------+ +| ts | host | val | addon | ++---------------------+-------+------+-------+ +| 1970-01-01 00:00:00 | host1 | 0 | 3 | +| 1970-01-01 00:00:01 | host1 | 1 | 2 | +| 1970-01-01 00:00:02 | host1 | 2 | 1 | ++---------------------+-------+------+-------+ +``` + +When the `order by` expression is not specified in the function parameter, the default behavior is to sort the data in ascending order based on the time index column. The following two SQL statements are equivalent: + +```sql +SELECT ts, first_value(val) RANGE '5s', last_value(val) RANGE '5s' FROM host_val ALIGN '5s'; +``` + +```sql +SELECT ts, first_value(val order by ts ASC) RANGE '5s', last_value(val order by ts ASC) RANGE '5s' FROM host_val ALIGN '5s'; +``` + +Get after query + +```sql ++---------------------+------------------------------------+-----------------------------------+ +| ts | first_value(host_val.val) RANGE 5s | last_value(host_val.val) RANGE 5s | ++---------------------+------------------------------------+-----------------------------------+ +| 1970-01-01 00:00:00 | 0 | 2 | ++---------------------+------------------------------------+-----------------------------------+ +``` + +You can specify your own sorting rules. For example, the following SQL sorts the data by the `addon` column in ascending order: + +```sql +SELECT ts, first_value(val ORDER BY addon ASC) RANGE '5s', last_value(val ORDER BY addon ASC) RANGE '5s' FROM host_val ALIGN '5s'; +``` + +Get after query + +```sql ++---------------------+-----------------------------------------------------------------------------+----------------------------------------------------------------------------+ +| ts | first_value(host_val.val) ORDER BY [host_val.addon ASC NULLS LAST] RANGE 5s | last_value(host_val.val) ORDER BY [host_val.addon ASC NULLS LAST] RANGE 5s | ++---------------------+-----------------------------------------------------------------------------+----------------------------------------------------------------------------+ +| 1970-01-01 00:00:00 | 2 | 0 | ++---------------------+-----------------------------------------------------------------------------+----------------------------------------------------------------------------+ +``` + +## Nested Range Expressions + +Range expressions support flexible nesting, and range expressions can be combined with various operations to provide more powerful query capabilities. + +Take the following table as an example: + +```sql +DROP TABLE IF EXISTS host_val; +CREATE TABLE host_val ( + ts TIMESTAMP TIME INDEX, + host STRING, + val DOUBLE, + PRIMARY KEY (host) +); + +INSERT INTO host_val VALUES + ('2023-01-01 08:00:00', 'host1', 1.1), + ('2023-01-01 08:00:05', 'host1', 2.2), + ('2023-01-01 08:00:00', 'host2', 3.3), + ('2023-01-01 08:00:05', 'host2', 4.4); +``` + +```sql ++---------------------+-------+------+ +| ts | host | val | ++---------------------+-------+------+ +| 2023-01-01 08:00:00 | host1 | 1.1 | +| 2023-01-01 08:00:05 | host1 | 2.2 | +| 2023-01-01 08:00:00 | host2 | 3.3 | +| 2023-01-01 08:00:05 | host2 | 4.4 | ++---------------------+-------+------+ +``` + +1. Aggregation functions support calculations both internally and externally: + +```sql +SELECT ts, host, 2.0 * min(val * 2.0) RANGE '10s' FROM host_val ALIGN '5s'; +``` + +Get after running + +```sql ++---------------------+-------+-------------------------------------------------------+ +| ts | host | Float64(2) * min(host_val.val * Float64(2)) RANGE 10s | ++---------------------+-------+-------------------------------------------------------+ +| 2023-01-01 07:59:55 | host1 | 4.4 | +| 2023-01-01 08:00:00 | host1 | 4.4 | +| 2023-01-01 08:00:05 | host1 | 8.8 | +| 2023-01-01 07:59:55 | host2 | 13.2 | +| 2023-01-01 08:00:00 | host2 | 13.2 | +| 2023-01-01 08:00:05 | host2 | 17.6 | ++---------------------+-------+-------------------------------------------------------+ +``` + + +2. Scalar functions are supported both inside and outside aggregate functions: + - `min(round(val)) RANGE '10s'` means that each value is rounded using the `round` function before aggregation + - `round(min(val) RANGE '10s')` means rounding the result of each aggregation using the `round` function + +```sql +SELECT ts, host, min(round(val)) RANGE '10s' FROM host_val ALIGN '5s'; +``` +Get after running + +```sql ++---------------------+-------+------------------------------------+ +| ts | host | min(round(host_val.val)) RANGE 10s | ++---------------------+-------+------------------------------------+ +| 2023-01-01 07:59:55 | host1 | 1 | +| 2023-01-01 08:00:00 | host1 | 1 | +| 2023-01-01 08:00:05 | host1 | 2 | +| 2023-01-01 07:59:55 | host2 | 3 | +| 2023-01-01 08:00:00 | host2 | 3 | +| 2023-01-01 08:00:05 | host2 | 4 | ++---------------------+-------+------------------------------------+ +``` + + +```sql +SELECT ts, host, round(min(val) RANGE '10s') FROM host_val ALIGN '5s'; +``` + +Get after running + +```sql ++---------------------+-------+------------------------------------+ +| ts | host | round(min(host_val.val) RANGE 10s) | ++---------------------+-------+------------------------------------+ +| 2023-01-01 07:59:55 | host2 | 3 | +| 2023-01-01 08:00:00 | host2 | 3 | +| 2023-01-01 08:00:05 | host2 | 4 | +| 2023-01-01 07:59:55 | host1 | 1 | +| 2023-01-01 08:00:00 | host1 | 1 | +| 2023-01-01 08:00:05 | host1 | 2 | ++---------------------+-------+------------------------------------+ +``` + +3. Multiple Range expressions can also evaluate together, and Range expressions support the distributive law. The following two Range query are legal and equivalent: + +```sql +SELECT ts, host, max(val) RANGE '10s' - min(val) RANGE '10s' FROM host_val ALIGN '5s'; +``` + +```sql +SELECT ts, host, (max(val) - min(val)) RANGE '10s' FROM host_val ALIGN '5s'; +``` + +Get after running + +```sql ++---------------------+-------+-----------------------------------------------------------+ +| ts | host | max(host_val.val) RANGE 10s - min(host_val.val) RANGE 10s | ++---------------------+-------+-----------------------------------------------------------+ +| 2023-01-01 07:59:55 | host2 | 0 | +| 2023-01-01 08:00:00 | host2 | 1.1000000000000005 | +| 2023-01-01 08:00:05 | host2 | 0 | +| 2023-01-01 07:59:55 | host1 | 0 | +| 2023-01-01 08:00:00 | host1 | 1.1 | +| 2023-01-01 08:00:05 | host1 | 0 | ++---------------------+-------+-----------------------------------------------------------+ +``` + +But note that the `RANGE` keyword apply to the expression before the `RANGE` keyword. The following Range query is illegal because the `RANGE` keyword apply to the expression `2.0`, not the expression `min(val * 2.0) * 2.0` + +```sql +SELECT ts, host, min(val * 2.0) * 2.0 RANGE '10s' FROM host_val ALIGN '5s'; +``` + +```sql +ERROR 1815 (HY000): sql parser error: Can't use the RANGE keyword in Expr 2.0 without function +``` + +Expressions can be bracketed, and the `RANGE` keyword is automatically applied to any aggregate functions contained within the brackets: + +```sql +SELECT ts, host, (min(val * 2.0) * 2.0) RANGE '10s' FROM host_val ALIGN '5s'; +``` + +After running, we get: + +```sql ++---------------------+-------+-------------------------------------------------------+ +| ts | host | min(host_val.val * Float64(2)) RANGE 10s * Float64(2) | ++---------------------+-------+-------------------------------------------------------+ +| 2023-01-01 07:59:55 | host2 | 13.2 | +| 2023-01-01 08:00:00 | host2 | 13.2 | +| 2023-01-01 08:00:05 | host2 | 17.6 | +| 2023-01-01 07:59:55 | host1 | 4.4 | +| 2023-01-01 08:00:00 | host1 | 4.4 | +| 2023-01-01 08:00:05 | host1 | 8.8 | ++---------------------+-------+-------------------------------------------------------+ +``` + +Nesting of Range expressions is not allowed. Nested Range queries are illegal: + +```sql +SELECT ts, host, max(min(val) RANGE '10s') RANGE '10s' FROM host_val ALIGN '5s'; +``` + +```sql +ERROR 1815 (HY000): Range Query: Nest Range Query is not allowed +``` + diff --git a/versioned_docs/version-1.0/reference/sql/replace.md b/versioned_docs/version-1.0/reference/sql/replace.md new file mode 100644 index 0000000000..fda484a1c7 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/replace.md @@ -0,0 +1,39 @@ +--- +keywords: [SQL REPLACE, SQL syntax, SQL examples, inserting records, SQL data manipulation] +description: Describes the SQL REPLACE statement for adding records to a table in GreptimeDB, including syntax, examples for inserting single and multiple records. +--- + +# REPLACE + +The `REPLACE` statement is used to insert new records into a table. In GreptimeDB, this statement is exactly the same as the `INSERT` statement. Please refer to [`INSERT`](/reference/sql/insert.md) for more details. + +## `REPLACE INTO` Statement + +### Syntax + +The syntax for the REPLACE INTO statement is as follows: + +```sql +REPLACE INTO table_name (column1, column2, column3, ...) +VALUES (value1, value2, value3, ...); +``` + +### Examples + +Here is an example of an `REPLACE INTO` statement that inserts a record into a table named `system_metrics`: + +```sql +REPLACE INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES + ("host1", "idc_b", 50.0, 66.7, 40.6, 1667446797462); +``` + +Here is an example of an `REPLACE INTO` statement that inserts multiple records into the `system_metrics` table: + +```sql +REPLACE INTO system_metrics (host, idc, cpu_util, memory_util, disk_util, ts) +VALUES + ("host1", "idc_a", 11.8, 10.3, 10.3, 1667446797460), + ("host2", "idc_a", 80.1, 70.3, 90.0, 1667446797461), + ("host1", "idc_c", 50.1, 66.8, 40.8, 1667446797463); +``` diff --git a/versioned_docs/version-1.0/reference/sql/select.md b/versioned_docs/version-1.0/reference/sql/select.md new file mode 100644 index 0000000000..ad9a026c83 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/select.md @@ -0,0 +1,214 @@ +--- +keywords: [SQL SELECT statement, data retrieval, filtering with WHERE, LIMIT clause, JOIN tables, GROUP BY clause] +description: Describes the SELECT statement in SQL for retrieving data from tables, including syntax, filtering with WHERE, limiting results with LIMIT, joining tables, and grouping results with GROUP BY. +--- + +# SELECT + +The `SELECT` statement is the foundation of data retrieval in SQL and GreptimeDB. It allows you to extract specific columns or expressions from one or more tables: + +## Basic Syntax + +The basic syntax for a `SELECT` statement is as follows: + +```sql +SELECT column1, column2, ... +FROM table_name +[WHERE condition] +[GROUP BY column] +[HAVING condition] +[ORDER BY column] +[LIMIT number] [OFFSET number] +``` + +Here, column1, column2, etc. refer to the names of the columns from which we want to retrieve data, +and table_name refers to the name of the table from which we want to retrieve the data. + +This statement selects all the columns from the table specified in the +`FROM` clause. If you want to select all columns from the table, you can use the asterisk (*) wildcard +character instead of listing individual columns. + +```sql +SELECT * +FROM table_name; +``` + +## Conditional Filtering (WHERE clause) + +The `WHERE` clause is used to filter the results of a `SELECT` statement based on a specified condition. The +syntax for using WHERE clause is as follows: + +```sql +SELECT column1, column2, ..., columnN +FROM table_name +WHERE condition; +``` + +Here, the condition is an expression that evaluates to either true or false. Only the rows that satisfy the condition will be included in the result set. + +Supported comparisons include: +* Logical operators: `AND`, `OR`, `NOT` +* Comparison operators: `=`, `!=`, `>`, `<`, `>=`, `<=` +* Pattern matching: `LIKE`, `IN`, `BETWEEN` + +For example: +```sql +-- Select all rows from the system_metrics table where idc is 'idc0' +SELECT * +FROM system_metrics +WHERE idc = 'idc0'; + +-- Select all rows from the system_metrics table where the idc is 'idc0' or 'idc0' +SELECT * +FROM system_metrics +WHERE idc IN ('idc0', 'idc1'); + +-- Select all rows from the system_metrics table where the idc is 'idc0' or 'idc0' and the cpu utilization is greater than 60% +SELECT * +FROM system_metrics +WHERE idc IN ('idc0', 'idc1') AND cpu_util > 0.6; +``` + +Please refer to [WHERE](where.md) for more information. + +## Order Results(ORDER BY clause) + +The `ORDER BY` clause is used to order the data in ascending or descending order based on one or more columns in the SELECT statement. + +For example: + +```sql +-- Sort the results by cpu_util in ascending order +SELECT * +FROM system_metrics ORDER BY cpu_util ASC; + +-- Sort the results by cpu_util in descending order +SELECT * +FROM system_metrics ORDER BY cpu_util DESC; +``` + +Please refer to [ORDER](order_by.md) for more information. + +## Limiting Results (LIMIT clause) + +The `LIMIT` clause is used to limit the number of rows returned by a SELECT statement. The syntax for using +`LIMIT` clause is as follows: + +```sql +SELECT column1, column2, ... +FROM table_name +LIMIT number_of_rows; +``` + +Here, the number_of_rows parameter specifies the maximum number of rows to return. + +Here are some examples of using the `LIMIT` clause: + +```sql +-- Select the top 10 high cpu rows from the system_metrics table +SELECT * +FROM system_metrics +ORDER BY cpu_util DESC +LIMIT 10; +``` + +## Pagination Results (LIMIT and OFFSET) + +The `OFFSET` clause specifies how many rows to skip before starting to return rows from the query. It's commonly used with LIMIT for paginating through large result sets. + +For example: +```sql +SELECT * +FROM system_metrics +ORDER BY cpu_util DESC +LIMIT 10 +OFFSET 10; +``` + +It selects all columns from rows ranked 11th to 20th (by descending `cpu_util`) from the `system_metrics` table. + +Although combining `OFFSET` and `LIMIT` with an `ORDER BY` clause can achieve pagination, this approach is not very efficient. We recommend recording the time index (timestamp) of the last record returned on each page and using this value to filter and limit the data for subsequent pages. Please refer to [OFFSET](offset.md) for more information. + +## Joining Tables (JOIN) + +The `JOIN` clause is used to combine rows from two or more tables based on a related column between them. The syntax for using `JOIN` clause is as follows: + +```sql +SELECT column1, column2, ... +FROM table1 +JOIN table2 +ON table1.column = table2.column; +``` + +Here, the table1 and table2 are the names of the tables to be joined. The column is the related column between the two tables. + +Please refer to [JOIN](join.md) for more information. + +## Grouping and Aggregation (GROUP BY and Aggregate Functions) + +Use `GROUP BY` to cluster data by one or more columns and perform calculations like counting or averaging within those groups. + +```sql +SELECT column1, column2, ..., aggregate_function(column) +FROM table_name +GROUP BY column1, column2, ...; +``` + +Common aggregate functions supported: +* COUNT +* SUM +* AVG +* MAX +* MIN + +For more functions, see [Aggregate Functions](/reference/sql/functions/df-functions.md#aggregate-functions) and [Window Functions](/reference/sql/functions/df-functions.md#window-functions). + +For example: +```sql +-- Select the total number of idc for each idc +SELECT idc, COUNT(host) as host_num +FROM system_metrics +GROUP BY idc; + +-- Select the idc's average cpu_util +SELECT idc, AVG(cpu_util) as cpu_avg +FROM system_metrics +GROUP BY idc; +``` + +Please refer to [GROUP BY](group_by.md) for more information. + +## Filtering Groups (HAVING clause) + +The `HAVING` clause allows you to filter grouped (aggregated) results—it works like `WHERE`, but after grouping has taken place. + +Example: +```sql +SELECT + DATE_TRUNC('day', event_time) AS log_date, + COUNT(*) AS error_count +FROM application_logs +WHERE log_level = 'ERROR' +GROUP BY log_date +HAVING error_count > 10; +``` + +Explanation: +* Groups logs by day and counts occurrences where the log level is `'ERROR'`. +* Only dates where the number of errors exceeds 10 are returned. + +Please refer to [HAVING](having.md) for more information. + +## RANGE query + +```sql +SELECT + ts, + host, + min(cpu) RANGE '10s', + max(cpu) RANGE '10s' FILL LINEAR +FROM host_cpu +ALIGN '5s' BY (host) FILL PREV; +``` + +Please refer to [RANGE QUERY](range.md) for more information. diff --git a/versioned_docs/version-1.0/reference/sql/show.md b/versioned_docs/version-1.0/reference/sql/show.md new file mode 100644 index 0000000000..f35a5c7ac7 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/show.md @@ -0,0 +1,444 @@ +--- +keywords: [SQL SHOW commands, database information, table details, SHOW DATABASES, SHOW TABLES, SHOW CREATE] +description: Provides information on the SHOW keyword in SQL for displaying database and table details, including various SHOW commands with syntax and examples. +--- + +# SHOW + +The `SHOW` keyword provides database and table information. + +## SHOW DATABASES + +Show all databases: + +```sql +SHOW [FULL] DATABASES; +``` + +```sql ++---------+ +| Schemas | ++---------+ +| public | ++---------+ +1 row in set (0.01 sec) +``` + +Show databases by `LIKE` pattern: + +```sql +SHOW DATABASES LIKE 'p%'; +``` + +Show databases by `where` expr: + +```sql +SHOW DATABASES WHERE Schemas='test_public_schema'; +``` + +Show all databases with options: + +```sql +CREATE DATABASE test WITH(ttl='7d'); +SHOW FULL DATABASES; +``` + +```sql ++--------------------+-------------+ +| Database | Options | ++--------------------+-------------+ +| greptime_private | | +| information_schema | | +| public | | +| test | ttl='7days' | ++--------------------+-------------+ +``` + +## SHOW CREATE DATABASE + +Shows the `CREATE DATABASE` statement that creates the named 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 + +Show all tables: + +```sql +SHOW TABLES; +``` + +```sql ++---------+ +| Tables | ++---------+ +| numbers | +| scripts | ++---------+ +2 rows in set (0.00 sec) +``` + +Show tables in the `test` database: + +```sql +SHOW TABLES FROM test; +``` + +Show tables by `like` pattern: + +```sql +SHOW TABLES like '%prometheus%'; +``` + +Show tables by `where` expr: + +```sql +SHOW TABLES FROM test WHERE Tables='numbers'; +``` + +## SHOW FULL TABLES + +```sql +SHOW FULL TABLES [IN | FROM] [DATABASE] [LIKE pattern] [WHERE query] +``` + +It will list all tables and table types in the database: + +```sql +SHOW FULL TABLES; +``` + +```sql ++---------+------------+ +| Tables | Table_type | ++---------+------------+ +| monitor | BASE TABLE | +| numbers | TEMPORARY | ++---------+------------+ +2 rows in set (0.00 sec) +``` + +* `Tables`: the table names. +* `Table_type`: the table types, such as `BASE_TABLE`, `TEMPORARY`, and `VIEW` etc. + +It supports `like` and `where` query too: + +```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 + +Shows the `CREATE TABLE` statement that creates the named table: + +```sql +SHOW CREATE TABLE [table] +``` + +For example: + +```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`: the table name. +* `Create Table`: The SQL to create the table. + +## SHOW CREATE FLOW + +Shows the `CREATE FLOW` statement that creates the flow task. + +For example: + +```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 + +Show all flows: + +```sql +public=> SHOW FLOWS; +``` + +```sql + Flows +---------------- + filter_numbers +(1 row) +``` +also support `LIKE` expression: +```sql +public=> show flows like "filter%"; +``` + +```sql + Flows +---------------- + filter_numbers +(1 row) +``` + +## SHOW CREATE VIEW + +To show the view's definition: + +```sql +SHOW CREATE VIEW cpu_monitor; +``` + +``` ++-------------+--------------------------------------------------------------+ +| View | Create View | ++-------------+--------------------------------------------------------------+ +| cpu_monitor | CREATE VIEW cpu_monitor AS SELECT cpu, host, ts FROM monitor | ++-------------+--------------------------------------------------------------+ +``` + +## SHOW VIEWS + +List all views: + +```sql +SHOW VIEWS; +``` + +```sql ++----------------+ +| Views | ++----------------+ +| cpu_monitor | +| memory_monitor | ++----------------+ +``` + +Of course, it supports `LIKE`: + +```sql +SHOW VIEWS LIKE 'cpu%'; +``` + +```sql ++-------------+ +| Views | ++-------------+ +| cpu_monitor | ++-------------+ +``` + +And `where`: + +```sql +SHOW VIEWS WHERE Views = 'memory_monitor'; +``` + +```sql ++----------------+ +| Views | ++----------------+ +| memory_monitor | ++----------------+ +``` + +## SHOW PROCESSLIST +List all currently running queries, essentially an alias for `SELECT id, catalog, query, elapsed_time FROM INFORMATION_SCHEMA.PROCESS_LIST`: + +```sql +SHOW PROCESSLIST; +``` + +Output: +``` ++-----------------------+----------+------------------+-----------------+ +| Id | Catalog | Query | Elapsed Time | ++-----------------------+----------+------------------+-----------------+ +| 192.168.50.164:4001/0 | greptime | SHOW PROCESSLIST | 00:00:00.002000 | ++-----------------------+----------+------------------+-----------------+ +1 row in set (0.00 sec) +``` + +At the same time, you can specify the `FULL` parameter to output all columns of the `INFORMATION_SCHEMA.PROCESS_LIST` table: +```sql +SHOW FULL PROCESSLIST; +``` + +Output: +```sql ++-----------------------+----------+--------------------+------------------------+---------------------+----------------------------+-----------------+-----------------------+ +| Id | Catalog | Schema | Client | Frontend | Start Time | Elapsed Time | Query | ++-----------------------+----------+--------------------+------------------------+---------------------+----------------------------+-----------------+-----------------------+ +| 192.168.50.164:4001/0 | greptime | information_schema | mysql[127.0.0.1:34692] | 192.168.50.164:4001 | 2025-06-30 07:17:46.423000 | 00:00:00.003000 | SHOW FULL PROCESSLIST | ++-----------------------+----------+--------------------+------------------------+---------------------+----------------------------+-----------------+-----------------------+ +``` + +## SHOW TRIGGERS + +Please refer to the [Trigger syntax](/reference/sql/trigger-syntax.md#show-triggers) documentation. + +## SHOW CREATE TRIGGER + +Please refer to the [Trigger syntax](/reference/sql/trigger-syntax.md#show-create-trigger) documentation. + +## Extensions to SHOW Statements + +Some extensions to `SHOW` statements accompany the implementation of [`INFORMATION_SCHEMA`](/reference/sql/information-schema/overview.md) just like MySQL, they also accept a `WHERE` clause that provides more flexibility in specifying which rows to display. + +GreptimeDB supports some extensions for MySQL compatibility, it's good for tools like [Navicat for MySQL](https://www.navicat.com/en/products/navicat-for-mysql) or [dbeaver](https://dbeaver.io/) to connect GreptimeDB. + +```sql +SHOW CHARACTER SET; +``` + +Output just like the `INFORMATION_SCHEMA.CHARACTER_SETS` table: + +```sql ++---------+---------------+-------------------+--------+ +| Charset | Description | Default collation | Maxlen | ++---------+---------------+-------------------+--------+ +| utf8 | UTF-8 Unicode | utf8_bin | 4 | ++---------+---------------+-------------------+--------+ +``` + +`SHOW COLLATION` for `INFORMATION_SCHEMA.COLLATIONS` table. + +```sql +SHOW INDEX FROM monitor; +``` + +To list all indexes in a table: + +```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 | ++---------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+----------------------------+---------+---------------+---------+------------+ +``` + +Which is the extension of `INFORMATION_SCHEMA.TABLE_CONSTRAINTS`. + +List all the columns in a table: + +```sql +SHOW COLUMNS FROM monitor; +``` + +Output just like `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 | ++--------+--------------+------+------------+---------------------+-------+----------------------+ +``` + +All these `SHOW` extensions accept `WHERE`: + +```sql +SHOW COLUMNS FROM monitor WHERE Field = 'cpu'; +``` + +```sql ++-------+--------+------+------+---------+-------+---------------+ +| Field | Type | Null | Key | Default | Extra | Greptime_type | ++-------+--------+------+------+---------+-------+---------------+ +| cpu | double | Yes | | 0 | | Float64 | ++-------+--------+------+------+---------+-------+---------------+ +``` + +To list all regions in a table: +```sql +SHOW REGION FROM monitor; +``` + +```sql ++----------------+---------------+------+--------+ +| Table | Region | Peer | Leader | ++----------------+---------------+------+--------+ +| monitor | 4398046511104 | 0 | Yes | ++----------------+---------------+------+--------+ +``` + +It is the extension of `INFORMATION_SCHEMA.REGION_PEERS` and supports `WHERE` too. + +The syntax is +```sql +SHOW REGION FROM [table] [IN database] [WHERE where] +``` + +Other `SHOW` statements: +* `SHOW STATUS` and `SHOW VARIABLES` are not supported, just return empty results. +* `SHOW TABLE STATUS` is the extension of `INFORMATION_SCHEMA.TABLES`. diff --git a/versioned_docs/version-1.0/reference/sql/tql.md b/versioned_docs/version-1.0/reference/sql/tql.md new file mode 100644 index 0000000000..635eedc808 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/tql.md @@ -0,0 +1,185 @@ +--- +keywords: [TQL, Time-Series Query Language, PromQL extension, EVAL command, EXPLAIN command, ANALYZE command] +description: Covers the TQL keyword for executing Time-Series Query Language in SQL, including EVAL, EXPLAIN, and ANALYZE commands with syntax and examples. +--- + +# TQL + +The `TQL` keyword executes TQL language in SQL. The TQL is Telemetry Query Language, which is an extension for Prometheus's [PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/) in GreptimeDB. + +## EVAL + +### Syntax + +```sql +TQL [EVAL | EVALUATE] (start, end, step, [lookback]) expr [AS alias] +``` + +The `start`, `end` and `step` are the query parameters just like [Prometheus Query API](https://prometheus.io/docs/prometheus/latest/querying/api/): + +- `start`: ``: The start timestamp of the query; the range is inclusive of this value. +- `end`: ``: The end timestamp of the query; the range is inclusive of this value. +- `step`: ``: The query resolution step, specified as a `duration` or a floating-point number of seconds. +- `lookback`: ``: The maximum lookback duration for evaluation, default is 5 minutes and optional. + +`expr` is the TQL (PromQL) query string. + +The optional `AS alias` clause allows you to specify a custom name for the value column in the result. This is useful for: +- Giving meaningful names to query results +- Using TQL results in SQL queries (e.g., CTEs, JOINs) +- Improving readability of complex queries + +**Note**: Value aliasing currently supports single-field results only. + +### Examples + +Return the per-second rate for all time series with the `http_requests_total` metric name, as measured over the last 5 minutes: + +```sql +TQL eval (1677057993, 1677058993, '1m') rate(prometheus_http_requests_total{job="prometheus"}[5m]); +``` + +will get a result just like other normal SQL queries. + +Using value aliasing to give a custom name to the result: + +```sql +TQL EVAL (0, 30, '10s') http_requests_total AS requests; +``` + +This will return results with the value column named `requests` instead of the default field name. + +Value aliasing with aggregation: + +```sql +TQL EVAL (0, 10, '5s') count by (k) (test) AS count_value; +``` + +This query counts values grouped by `k` and names the result column `count_value`. + +`start` and `end` can also be time expressions that evaluate to constants. For example, to query the past 3 hours: + +```sql +TQL EVAL (now() - interval '3' hours, now(), '1m') + sum by (namespace, pod) ( + increase(kube_pod_container_status_restarts_total[10m:30s]) + ); +``` + +To query data for the past day: + +```sql +TQL EVAL ( + date_trunc('day', now() - interval '1' day), + date_trunc('day', now()), + '1m' +) + sum by (namespace) ( + rate(http_requests_total[5m:30s]) + ); +``` + +### Using TQL in CTEs + +TQL `EVAL` can be used within Common Table Expressions (CTEs) to combine PromQL-style queries with SQL processing. For detailed examples and usage guidelines, see [Using TQL in CTEs](/user-guide/query-data/cte.md#using-tql-in-ctes). + +## EXPLAIN + +`EXPLAIN` displays both the logical plan and execution plan for a given PromQL query. The syntax is as follows: + +``` +TQL EXPLAIN [VERBOSE] [FORMAT format] [(start, end, step, [lookback])] expr [AS alias]; +``` + +For example, to explain the PromQL `sum by (instance) (rate(node_disk_written_bytes_total[2m])) > 50`, we can use + +``` +TQL EXPLAIN sum by (instance) (rate(node_disk_written_bytes_total[2m])) > 50; +``` + +Notice that since the given query won't be actually executed, the triple `(start, end, step, [lookback])` is not necessary. But you can still provide it like in `TQL EVAL`: + +``` +TQL EXPLAIN (0, 100, '10s') sum by (instance) (rate(node_disk_written_bytes_total[2m])) > 50; +``` + +You can also use value aliasing with EXPLAIN: + +``` +TQL EXPLAIN (0, 10, '5s') test AS series; +``` + +The result should be like the following: + +```txt ++---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Sort: node_disk_written_bytes_total.instance ASC NULLS LAST, node_disk_written_bytes_total.ts ASC NULLS LAST + Filter: SUM(prom_rate(ts_range,field,ts)) > Float64(50) + Aggregate: groupBy=[[node_disk_written_bytes_total.instance, node_disk_written_bytes_total.ts]], aggr=[[SUM(prom_rate(ts_range,field,ts))]] + Projection: node_disk_written_bytes_total.ts, prom_rate(ts_range, field, node_disk_written_bytes_total.ts) AS prom_rate(ts_range,field,ts), node_disk_written_bytes_total.instance + Filter: prom_rate(ts_range, field, node_disk_written_bytes_total.ts) IS NOT NULL + Projection: node_disk_written_bytes_total.ts, node_disk_written_bytes_total.instance, field, ts_range + PromRangeManipulate: req range=[0..0], interval=[300000], eval range=[120000], time index=[ts], values=["field"] + PromSeriesNormalize: offset=[0], time index=[ts], filter NaN: [true] + PromSeriesDivide: tags=["instance"] + Sort: node_disk_written_bytes_total.instance DESC NULLS LAST, node_disk_written_bytes_total.ts DESC NULLS LAST + TableScan: node_disk_written_bytes_total projection=[ts, instance, field], partial_filters=[ts >= TimestampMillisecond(-420000, None), ts <= TimestampMillisecond(300000, None)] | +| physical_plan | SortPreservingMergeExec: [instance@0 ASC NULLS LAST,ts@1 ASC NULLS LAST] + SortExec: expr=[instance@0 ASC NULLS LAST,ts@1 ASC NULLS LAST] + CoalesceBatchesExec: target_batch_size=8192 + FilterExec: SUM(prom_rate(ts_range,field,ts))@2 > 50 + AggregateExec: mode=FinalPartitioned, gby=[instance@0 as instance, ts@1 as ts], aggr=[SUM(prom_rate(ts_range,field,ts))] + CoalesceBatchesExec: target_batch_size=8192 + RepartitionExec: partitioning=Hash([Column { name: "instance", index: 0 }, Column { name: "ts", index: 1 }], 32), input_partitions=32 + AggregateExec: mode=Partial, gby=[instance@2 as instance, ts@0 as ts], aggr=[SUM(prom_rate(ts_range,field,ts))] + ProjectionExec: expr=[ts@0 as ts, prom_rate(ts_range@3, field@2, ts@0) as prom_rate(ts_range,field,ts), instance@1 as instance] + CoalesceBatchesExec: target_batch_size=8192 + FilterExec: prom_rate(ts_range@3, field@2, ts@0) IS NOT NULL + ProjectionExec: expr=[ts@0 as ts, instance@1 as instance, field@2 as field, ts_range@3 as ts_range] + PromInstantManipulateExec: req range=[0..0], interval=[300000], eval range=[120000], time index=[ts] + PromSeriesNormalizeExec: offset=[0], time index=[ts], filter NaN: [true] + PromSeriesDivideExec: tags=["instance"] + RepartitionExec: partitioning=RoundRobinBatch(32), input_partitions=1 + ExecutionPlan(PlaceHolder) + | ++---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## ANALYZE + +TQL also supports `ANALYZE` keyword to analyze the given PromQL query's execution. The syntax is as follows: + +``` +TQL ANALYZE [VERBOSE] [FORMAT format] (start, end, step, [lookback]) expr [AS alias]; +``` + +For example: + +``` +TQL ANALYZE (0, 10, '5s') test; +``` + +will get a result like + +``` ++-------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++-------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Plan with Metrics | CoalescePartitionsExec, metrics=[output_rows=0, elapsed_compute=14.99µs] + PromInstantManipulateExec: range=[0..10000], lookback=[300000], interval=[5000], time index=[j], metrics=[output_rows=0, elapsed_compute=1.08µs] + PromSeriesNormalizeExec: offset=[0], time index=[j], filter NaN: [false], metrics=[output_rows=0, elapsed_compute=1.11µs] + PromSeriesDivideExec: tags=["k"], metrics=[output_rows=0, elapsed_compute=1.3µs] + RepartitionExec: partitioning=RoundRobinBatch(32), input_partitions=32, metrics=[send_time=32ns, repart_time=32ns, fetch_time=11.578016ms] + RepartitionExec: partitioning=RoundRobinBatch(32), input_partitions=1, metrics=[send_time=1ns, repart_time=1ns, fetch_time=21.07µs] + ExecutionPlan(PlaceHolder), metrics=[] + | ++-------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +Using `TQL ANALYZE VERBOSE` will get a verbose result of the execution. + +``` +TQL ANALYZE VERBOSE (0, 10, '5s') test; +``` diff --git a/versioned_docs/version-1.0/reference/sql/trigger-syntax.md b/versioned_docs/version-1.0/reference/sql/trigger-syntax.md new file mode 100644 index 0000000000..782ee021a4 --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/trigger-syntax.md @@ -0,0 +1,192 @@ +--- +keywords: [Trigger, Alert, GreptimeDB Enterprise, Syntax] +description: This document provides more details about the GreptimeDB Trigger. +--- + +# Trigger Syntax + +:::tip NOTE + +This feature is only available in the GreptimeDB Enterprise database. + +::: + + +## CREATE TRIGGER + +The syntax for creating a Trigger: + +```sql +CREATE TRIGGER [IF NOT EXISTS] + ON () EVERY + [LABELS (=, ...)] + [ANNOTATIONS (=, ...)] + NOTIFY ( + WEBHOOK URL '' [WITH (=, ...)], + WEBHOOK URL '' [WITH (=, ...)] + ); +``` + +- Trigger name: the unique identifier of the Trigger at the catalog level. +- IF NOT EXISTS: prevent errors that would occur if the Trigger being created. + +### On clause + +#### Query expression + +The SQL query which be executed periodically. The notification will be fired +if query result is not empty. If query result has multiple rows, a notification +will be fired for each row. + +In addition, the Trigger will extract the `labels` and `annotations` from the +query result, and attach them to the notification message along with the key-value +pairs specified in the `LABELS` and `ANNOTATIONS` clauses. + +The extraction rules are as follows: + +- Extract columns whose name or alias starts with `label_` to `LABELS`. The key + of labels is the column name or alias without the `label_` prefix. +- Extract the other columns to `ANNOTATIONS`. The key of annotations is the + column name. + +For example, the query expression is as follows: + +```sql +SELECT collect as label_collector, host as label_host, val + FROM host_load1 + WHERE val > 10 and ts >= now() - '1 minutes'::INTERVAL +``` + +Assume the query result is not empty and looks like this: + +| label_collector | label_host | val | +|------------------|------------|-----| +| collector1 | host1 | 12 | +| collector2 | host2 | 15 | + +This will generate two notifications. + +The first notification will have the following labels and annotations: + +- Labels: + - collector: collector1 + - host: host1 + - the labels defined in the `LABELS` clause +- Annotations: + - val: 12 + - the annotations defined in the `ANNOTATIONS` clause + +The second notification will have the following labels and annotations: + +- Labels: + - collector: collector2 + - host: host2 + - the labels defined in the `LABELS` clause +- Annotations: + - val: 15 + - the annotations defined in the `ANNOTATIONS` clause + +#### Interval expression + +It indicates how often the query is executed. e.g., `'5 minute'::INTERVAL`, +`'1 hour'::INTERVAL` etc. + +- `Years` and `months` are **prohibited** in INTERVAL expressions. Because the + duration of a month or year is variable and depends on the specific month + or year, it is not suitable for defining fixed intervals. +- The minimum interval is 1 second. Any interval specified less than 1 second + will be automatically rounded up to 1 second. + +For more details about how to write INTERVAL time, see [interval-type](/reference/sql/data-types.md#interval-type). + +### Labels and Annotations clauses + +The LABELS and ANNOTATIONS clauses allow you to attach static key-value pairs +to the notification messages sent by Trigger. These can be used to provide +additional context or metadata about the Trigger. + +- LABELS: serve as labels for Alertmanager routing, grouping, and inhibition. +- ANNOTATIONS: typically for human-readable descriptions. + +### Notify clause + +The NOTIFY clause allows you to specify one or more notification channels. + +Currently, GreptimeDB supports the following notification channel: + +#### Webhook + +The webhook channel will send HTTP requests to a specified URL when the Trigger +fires. The payload of the http request is compatible with +[Prometheus Alertmanager](https://prometheus.io/docs/alerting/latest/alertmanager/), +which means you can use GreptimeDB's Trigger with Prometheus Alertmanager +without any extra glue code. + +The optional `WITH` clause allows you to specify additional parameters: + +- timeout: The timeout for the HTTP request, e.g., `timeout='1m'`. + +## SHOW TRIGGERS + +Show all triggers: + +```sql +SHOW TRIGGERS; +``` + +Show triggers by `like` pattern: + +```sql +SHOW TRIGGERS LIKE ''; +``` + +For example: + +```sql +SHOW TRIGGERS LIKE 'load%'; +``` + +Show triggers by `where` condition: + +```sql +SHOW TRIGGERS WHERE ; +``` + +For example: + +```sql +SHOW TRIGGERS WHERE name = 'load1_monitor'; +``` + +## SHOW CREATE TRIGGER + +To show the Trigger's definition: + +```sql +SHOW CREATE TRIGGER ; +``` + +For example: + +```sql +SHOW CREATE TRIGGER load1_monitor; +``` + +## DROP TRIGGER + +To delete a trigger, use the following `DROP TRIGGER` clause: + +```sql +DROP TRIGGER [IF EXISTS] ; +``` + +For example: + +```sql +DROP TRIGGER IF EXISTS load1_monitor; +``` + +## Example + +Please refer to the [Trigger](/enterprise/trigger.md) documentation in the enterprise user guide for examples. + diff --git a/versioned_docs/version-1.0/reference/sql/truncate.md b/versioned_docs/version-1.0/reference/sql/truncate.md new file mode 100644 index 0000000000..c119d7a88d --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/truncate.md @@ -0,0 +1,17 @@ +--- +keywords: [SQL TRUNCATE, delete all data, TRUNCATE TABLE, SQL syntax, efficient deletion] +description: Details the TRUNCATE TABLE statement in SQL, used for efficiently deleting all data from a table, with syntax and example. +--- + +# TRUNCATE + +The `TRUNCATE TABLE table` statement is used to delete all data from a table. It's much more efficient than `DELETE FROM table`. + +```sql +TRUNCATE TABLE monitor; +``` + +```sql +Query OK, 0 rows affected (0.02 sec) +``` + diff --git a/versioned_docs/version-1.0/reference/sql/where.md b/versioned_docs/version-1.0/reference/sql/where.md new file mode 100644 index 0000000000..3b76d2cf0f --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/where.md @@ -0,0 +1,80 @@ +--- +keywords: [SQL WHERE clause, filtering data, logical operators, comparison operators, list search] +description: Explains the WHERE clause in SQL for filtering data based on conditions, including syntax, examples with logical and comparison operators, and list search functionalities. +--- + +# WHERE + +`WHERE` clause allows to filter the data by specifying conditions. + +## Syntax + +```sql +SELECT * +FROM table_name +WHERE condition; +``` + +If there is a `WHERE` clause, it must contain an expression with the Boolean type. This is usually +an expression with comparison and logical operators. Rows where this expression evaluates to false are +excluded from further transformations or result. + +## Examples + +### Logical operators + +Supports `AND`, `OR` as logical operators and can assemble conditions using brackets (). + +```sql +SELECT * FROM system_metrics +WHERE idc = 'idc0' AND (host = 'host1' OR host = 'host2'); +``` + +### Numeric + +Supports `=`, `!=`, `>`, `>=`, `<`, `<=` as comparison operators. + +```sql +SELECT * FROM system_metrics WHERE cpu_util = 20.0; +SELECT * FROM system_metrics WHERE cpu_util != 20.0; +SELECT * FROM system_metrics WHERE cpu_util > 20.0; +SELECT * FROM system_metrics WHERE cpu_util >= 20.0; +SELECT * FROM system_metrics WHERE cpu_util < 20.0; +SELECT * FROM system_metrics WHERE cpu_util <= 20.0; +``` + +### List search + +Evaluates match or mismatch against a list of elements. + +### List match + +```sql +SELECT * FROM system_metrics WHERE idc IN ('idc_a', 'idc_b'); +``` + +### List mismatch + +```sql +SELECT * FROM system_metrics WHERE idc NOT IN ('idc_a', 'idc_b'); +``` + +### String + +For string columns, we can use the `LIKE` operator to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: +* The percent sign `%` represents zero, one, or multiple characters +* The underscore sign `_` represents a single character + +Select all records that the `host` column starts with the letter "a": +```sql +SELECT * FROM system_metrics WHERE host LIKE 'a%'; +``` + + Selects all records from the `go_info` table where the instance column matches the pattern `'localhost:____'`, meaning `'localhost:'` followed by exactly four characters. + +```sql +SELECT * FROM go_info +WHERE instance LIKE 'localhost:____'; +``` + +For searching terms in logs, please read [Fulltext Search](/user-guide/logs/fulltext-search.md). diff --git a/versioned_docs/version-1.0/reference/sql/with.md b/versioned_docs/version-1.0/reference/sql/with.md new file mode 100644 index 0000000000..9fb6106a6c --- /dev/null +++ b/versioned_docs/version-1.0/reference/sql/with.md @@ -0,0 +1,89 @@ +--- +keywords: [CTE, Common Table Expression, SQL WITH clause, non-recursive CTE, SQL syntax] +description: Describes the usage of the WITH clause to define Common Table Expressions (CTEs) in SQL, including syntax, examples of non-recursive CTEs, and notes on recursive CTEs. +--- + +# WITH + +Use `WITH` to specify a Common Table Expression. + +## What is a Common Table Expression (CTE)? + +A Common Table Expression (CTE) is a temporary result set that you can reference within a `SELECT`, `INSERT`, `UPDATE`, or `DELETE` statement. CTEs help to break down complex queries into more readable parts and can be referenced multiple times within the same query. + +## Basic syntax of CTE + +CTEs are typically defined using the `WITH` keyword. The basic syntax is as follows: + +```sql +WITH cte_name [(column1, column2, ...)] AS ( + QUERY +) +SELECT ... +FROM cte_name; +``` + +## Examples + +### Non-recursive 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 | ++--------+--------+ +``` + +If a parenthesized list of names follows the CTE name, those names are the column names: + +```sql +WITH cte (col1, col2) AS +( + SELECT 1, 2 + UNION ALL + SELECT 3, 4 +) +SELECT col1, col2 FROM cte; +``` + +The number of names in the list must be the same as the number of columns in the result set. + +```sql ++------+------+ +| col1 | col2 | ++------+------+ +| 1 | 2 | +| 3 | 4 | ++------+------+ +``` + +Join two CTEs: +```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 | ++------+------+ +``` + + +### Recursive CTE + +Recursive CTE is not implemented currently. \ No newline at end of file diff --git a/versioned_docs/version-1.0/reference/telemetry.md b/versioned_docs/version-1.0/reference/telemetry.md new file mode 100644 index 0000000000..6a45458490 --- /dev/null +++ b/versioned_docs/version-1.0/reference/telemetry.md @@ -0,0 +1,66 @@ +--- +keywords: [telemetry data, data collection, privacy, configuration, disable telemetry, enable telemetry] +description: Details on telemetry data collection in GreptimeDB, including what data is collected, how often, and how to enable or disable telemetry. +--- + +# Telemetry + +To enhance our service, GreptimeDB collects certain telemetry data. This includes information like the GreptimeDB version, the number of nodes, the operating system used, the environment's architecture, and similar technical details. However, we respect your privacy and make sure not to collect any user-specific data, which entails database names, table names, query content, and the like. + +This telemetry collection can easily be managed according to your preferences. You may choose to enable or disable it through the configurations. Your experience and privacy are our top priority. + +## What data will be collected? + +The usage details that get shared might change over time. These changes (if any) will be announced in release notes. + +When telemetry is enabled, GreptimeDB will collect the following information every 0.5 hours: + +- GreptimeDB version +- GreptimeDB build git hash +- The operating system of the machine on which GreptimeDB is running(Linux, macOS, etc.) +- Architecture of the machine on which GreptimeDB is running(x86_64, arm64, etc.) +- Mode in which GreptimeDB is running(standalone, distributed) +- A randomly generated installation ID +- The number of datanodes in the GreptimeDB cluster +- System uptime, not exact figures, only time ranges like `hours`, `weeks` with no numbers + + Sample telemetry data: +```json +{ + "os": "linux", + "version": "0.15.1", + "arch": "aarch64", + "mode": "Standalone", + "git_commit": "00d759e828f5e148ec18141904e20cb1cb7577b0", + "nodes": 1, + "uuid": "43717682-baa8-41e0-b126-67b797b66606", + "uptime": "hours" +} +``` + +## How to disable telemetry? + +Telemetry will be enabled by default starting from v0.4.0. You can disable it by configuring the settings. + +### Standalone mode + +Set `enable_telemetry` in the standalone config file to `false`: + +```toml +# Whether to enable greptimedb telemetry, true by default. +enable_telemetry = false +``` + +Or configure it by the environment variable `GREPTIMEDB_STANDALONE__ENABLE_TELEMETRY=false` on startup. + +### Distributed mode + +Set `enable_telemetry` in the metasrv config file to `false`: + +```toml +# metasrv config file +# Whether to enable greptimedb telemetry, true by default. +enable_telemetry = false +``` + +Or set the environment variable `GREPTIMEDB_METASRV__ENABLE_TELEMETRY=false` on startup. diff --git a/versioned_docs/version-1.0/reference/time-durations.md b/versioned_docs/version-1.0/reference/time-durations.md new file mode 100644 index 0000000000..70aea4888c --- /dev/null +++ b/versioned_docs/version-1.0/reference/time-durations.md @@ -0,0 +1,52 @@ +--- +keywords: [time durations, time spans, time units] +description: Learn how GreptimeDB utilizes time durations to represent time spans in SQL queries, configuration files, and API requests with supported suffixes and examples. +--- + +# Time Durations + +GreptimeDB utilizes time durations to represent time spans in various contexts, +including SQL queries, configuration files, and API requests. +For more information on using time durations, please refer to: + +- The TTL options and the `time_window` parameter of the TWCS compaction strategy in the [ALTER](/reference/sql/alter.md) statement. +- The TTL options in the [CREATE](/reference/sql/create.md) statement. + +A time duration is expressed as a string composed of concatenated time spans, +each represented by a sequence of decimal numbers followed by a unit suffix. +These suffixes are case-insensitive and support both singular and plural forms. For example, `1hour 12min 5s`. + +Each time span consists of an integer and a suffix. +The supported suffixes are: + +- `nsec`, `ns`: nanoseconds +- `usec`, `us`: microseconds +- `msec`, `ms`: milliseconds +- `seconds`, `second`, `sec`, `s` +- `minutes`, `minute`, `min`, `m` +- `hours`, `hour`, `hr`, `h` +- `days`, `day`, `d` +- `weeks`, `week`, `w` +- `months`, `month`, `M`: defined as 30.44 days +- `years`, `year`, `y`: defined as 365.25 days + +Appending a decimal integer with one of the above units represents the equivalent number of seconds as a bare float literal. +Examples: + +- `1s`: Equivalent to 1 second +- `2m`: Equivalent to 120 seconds +- `1ms`: Equivalent to 0.001 seconds +- `2h`: Equivalent to 7200 seconds + +The following examples are invalid: + +- `0xABm`: Hexadecimal numbers are not supported +- `1.5h`: Floating point numbers are not supported +- `+Infd`: `±Inf` or `NaN` values are not supported + + +The following are some valid time duration examples: + +- `1h`: one hour +- `1h30m`, `1h 30m`: one hour and thirty minutes +- `1h30m10s`, `1h 30m 10s`: one hour, thirty minutes, and ten seconds diff --git a/versioned_docs/version-1.0/tutorials/k8s-metrics-monitor.md b/versioned_docs/version-1.0/tutorials/k8s-metrics-monitor.md new file mode 100644 index 0000000000..7cb8ed5d91 --- /dev/null +++ b/versioned_docs/version-1.0/tutorials/k8s-metrics-monitor.md @@ -0,0 +1,319 @@ +--- +keywords: [Kubernetes, Prometheus, monitoring, metrics, observability, GreptimeDB, Prometheus Operator, Grafana] +description: Guide to monitoring Kubernetes metrics using Prometheus with GreptimeDB as the storage backend, including architecture overview, installation, and visualization with Grafana. +--- + +# Monitor Kubernetes Metrics with Prometheus and GreptimeDB + +This guide demonstrates how to set up a complete Kubernetes monitoring solution using Prometheus for metrics collection and GreptimeDB as the long-term storage backend. + +## What is Kubernetes Monitoring + +Kubernetes monitoring is the practice of collecting, analyzing, and acting on metrics and logs from a Kubernetes cluster. +It provides visibility into the health, performance, and resource utilization of your containerized applications and infrastructure. + +Key aspects of Kubernetes monitoring include: + +- **Resource Metrics**: CPU, memory, disk, and network usage for nodes, pods, and containers +- **Cluster Health**: Status of cluster components like kube-apiserver, etcd, and controller-manager +- **Application Metrics**: Custom metrics from your applications running in the cluster +- **Events and Logs**: Kubernetes events and container logs for troubleshooting + +Effective monitoring helps you: +- Detect and diagnose issues before they impact users +- Optimize resource utilization and reduce costs +- Plan capacity based on historical trends +- Ensure SLA compliance +- Troubleshoot performance bottlenecks + +## Architecture Overview + +The monitoring architecture consists of the following components: + +![Kubernetes Monitoring Architecture](/k8s-metrics-monitor-architecture.drawio.svg) + +**Components:** + +- **kube-state-metrics**: Exports cluster-level metrics about Kubernetes objects (deployments, pods, services, etc.) +- **Node Exporter**: Exports hardware and OS-level metrics from each Kubernetes node +- **Prometheus Operator**: Automates Prometheus deployment and configuration using Kubernetes custom resources +- **GreptimeDB**: Acts as the long-term storage backend for Prometheus metrics with high compression and query performance +- **Grafana**: Provides dashboards and visualizations for metrics stored in GreptimeDB + +## Prerequisites + +Before starting, ensure you have: + +- A running Kubernetes cluster (version >= 1.18) +- `kubectl` configured to access your cluster +- [Helm](https://helm.sh/docs/intro/install/) v3.0.0 or higher installed +- Sufficient cluster resources (at least 2 CPU cores and 4GB memory available) + +## Install GreptimeDB + +GreptimeDB serves as the long-term storage backend for Prometheus metrics. +For detailed installation steps, +please refer to the [Deploy GreptimeDB Cluster](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md) documentation. + +### Verify the GreptimeDB Installation + +After deploying GreptimeDB, verify that the cluster is running. +In this guide we assume the GreptimeDB cluster is deployed in the `greptime-cluster` namespace and named `greptimedb`. + +```bash +kubectl -n greptime-cluster get greptimedbclusters.greptime.io greptimedb +``` + +```bash +NAME FRONTEND DATANODE META FLOWNODE PHASE VERSION AGE +greptimedb 1 2 1 1 Running v0.17.2 33s +``` + +Check the pods: + +```bash +kubectl get pods -n greptime-cluster +``` + +```bash +NAME READY STATUS RESTARTS AGE +greptimedb-datanode-0 1/1 Running 0 71s +greptimedb-datanode-1 1/1 Running 0 97s +greptimedb-flownode-0 1/1 Running 0 64s +greptimedb-frontend-8bf9f558c-7wdmk 1/1 Running 0 90s +greptimedb-meta-fc4ddb78b-nv944 1/1 Running 0 87s +``` + +### Access GreptimeDB + +To interact with GreptimeDB directly, you can port-forward the frontend service to your local machine. +GreptimeDB supports multiple protocols, with MySQL protocol available on port `4002` by default. + +```bash +kubectl port-forward -n greptime-cluster svc/greptimedb-frontend 4002:4002 +``` + +Connect using any MySQL-compatible client: + +```bash +mysql -h 127.0.0.1 -P 4002 +``` + +### Storage Partitioning + +To improve query performance and reduce storage costs, +GreptimeDB automatically creates columns based on Prometheus metric labels and stores metrics in a physical table. +The default table name is `greptime_physical_table`. +Since we deployed a GreptimeDB cluster with [multiple datanodes](#verify-the-greptimedb-installation), +you can partition the table to distribute data across datanodes for better scalability and performance. + +In this Kubernetes monitoring scenario, we can use the `namespace` label as the partition key. +For example, with namespaces like `kube-public`, `kube-system`, `monitoring`, `default`, `greptime-cluster`, and `etcd-cluster`, +you can create a partitioning scheme based on the first letter of the namespace: + +```sql +CREATE TABLE greptime_physical_table ( + greptime_value DOUBLE NULL, + namespace STRING PRIMARY KEY, + greptime_timestamp TIMESTAMP TIME INDEX, +) +PARTITION ON COLUMNS (namespace) ( + namespace < 'f', + namespace >= 'f' AND namespace < 'g', + namespace >= 'g' AND namespace < 'k', + namespace >= 'k' +) +ENGINE = metric +WITH ( + "physical_metric_table" = "" +); +``` + +For more information about Prometheus metrics storage and query performance optimization, refer to the [Improve efficiency by using metric engine](/user-guide/ingest-data/for-observability/prometheus.md#improve-efficiency-by-using-metric-engine) guide. + +### Prometheus URLs in GreptimeDB + +GreptimeDB provides [Prometheus-compatible APIs](/user-guide/query-data/promql.md#prometheus-http-api) under the HTTP context `/v1/prometheus/`, +enabling seamless integration with existing Prometheus workflows. + +To integrate Prometheus with GreptimeDB, you need the GreptimeDB service address. +Since GreptimeDB runs inside the Kubernetes cluster, use the internal cluster address. + +The GreptimeDB frontend service address follows this pattern: +``` +-frontend..svc.cluster.local: +``` + +In this guide: +- GreptimeDB cluster name: `greptimedb` +- Namespace: `greptime-cluster` +- Frontend port: `4000` + +So the service address is: +```bash +greptimedb-frontend.greptime-cluster.svc.cluster.local:4000 +``` + +The complete [Remote Write URL](/user-guide/ingest-data/for-observability/prometheus.md#remote-write-configuration) for Prometheus is: + +```bash +http://greptimedb-frontend.greptime-cluster.svc.cluster.local:4000/v1/prometheus/write +``` + +This URL consists of: +- **Service endpoint**: `greptimedb-frontend.greptime-cluster.svc.cluster.local:4000` +- **API path**: `/v1/prometheus/write` + +## Install Prometheus + +Now that GreptimeDB is running, we'll install Prometheus to collect metrics and send them to GreptimeDB for long-term storage. + +### Add the Prometheus Community Helm Repository + +```bash +helm repo add prometheus-community https://prometheus-community.github.io/helm-charts +helm repo update +``` + +### Install the kube-prometheus-stack + +The [`kube-prometheus-stack`](https://github.com/prometheus-operator/kube-prometheus) is a comprehensive monitoring solution that includes +Prometheus, Grafana, kube-state-metrics, and node-exporter components. +This stack automatically discovers and monitors all Kubernetes namespaces, +collecting metrics from cluster components, nodes, and workloads. + +In this deployment, we'll configure Prometheus to use GreptimeDB as the remote write destination for long-term metric storage and configure Grafana's default Prometheus data source to use GreptimeDB. + +Create a `kube-prometheus-values.yaml` file with the following configuration: + +```yaml +# Configure Prometheus remote write to GreptimeDB +prometheus: + prometheusSpec: + remoteWrite: + - url: http://greptimedb-frontend.greptime-cluster.svc.cluster.local:4000/v1/prometheus/write + +# Configure Grafana to use GreptimeDB as the default Prometheus data source +grafana: + datasources: + datasources.yaml: + apiVersion: 1 + datasources: + - name: Prometheus + type: prometheus + url: http://greptimedb-frontend.greptime-cluster.svc.cluster.local:4000/v1/prometheus + access: proxy + editable: true +``` + +This configuration file specifies [the GreptimeDB service address](#prometheus-urls-in-greptimedb) for: +- **Prometheus remote write**: Sends collected metrics to GreptimeDB for long-term storage +- **Grafana data source**: Configures GreptimeDB as the default Prometheus data source for dashboard queries + +Install the `kube-prometheus-stack` using Helm with the custom values file: + +```bash +helm install kube-prometheus prometheus-community/kube-prometheus-stack \ + --namespace monitoring \ + --create-namespace \ + --values kube-prometheus-values.yaml +``` + +### Verify the Installation + +Check that all Prometheus components are running: + +```bash +kubectl get pods -n monitoring +``` + +```bash +NAME READY STATUS RESTARTS AGE +alertmanager-kube-prometheus-kube-prome-alertmanager-0 2/2 Running 0 60s +kube-prometheus-grafana-78ccf96696-sghx4 3/3 Running 0 78s +kube-prometheus-kube-prome-operator-775fdbfd75-w88n7 1/1 Running 0 78s +kube-prometheus-kube-state-metrics-5bd5747f46-d2sxs 1/1 Running 0 78s +kube-prometheus-prometheus-node-exporter-ts9nn 1/1 Running 0 78s +prometheus-kube-prometheus-kube-prome-prometheus-0 2/2 Running 0 60s +``` + +### Verify the Monitoring Status + +Use [MySQL protocol](#access-greptimedb) to query GreptimeDB and verify that Prometheus metrics are being written. + +```sql +SHOW TABLES; +``` + +You should see tables created for various Prometheus metrics. + +```sql ++---------------------------------------------------------------------------------+ +| Tables | ++---------------------------------------------------------------------------------+ +| :node_memory_MemAvailable_bytes:sum | +| ALERTS | +| ALERTS_FOR_STATE | +| aggregator_discovery_aggregation_count_total | +| aggregator_unavailable_apiservice | +| alertmanager_alerts | +| alertmanager_alerts_invalid_total | +| alertmanager_alerts_received_total | +| alertmanager_build_info | +| ...... | ++---------------------------------------------------------------------------------+ +1553 rows in set (0.18 sec) +``` + +## Use Grafana for Visualization + +Grafana is included in the kube-prometheus-stack and comes pre-configured with dashboards for comprehensive Kubernetes monitoring. + +### Access Grafana + +Port-forward the Grafana service to access the web interface: + +```bash +kubectl port-forward -n monitoring svc/kube-prometheus-grafana 3000:80 +``` + +### Get Admin Credentials + +Retrieve the admin password using kubectl: + +```bash +kubectl get secret --namespace monitoring kube-prometheus-grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo +``` + +### Login Grafana + +1. Open your browser and navigate to [http://localhost:3000](http://localhost:3000) +2. Login with: + - **Username**: `admin` + - **Password**: The password retrieved from the previous step + +### Explore Pre-configured Dashboards + +After logging in, navigate to **Dashboards** to explore the pre-configured Kubernetes monitoring dashboards: + +- **Kubernetes / Compute Resources / Cluster**: Overview of cluster-wide resource utilization +- **Kubernetes / Compute Resources / Namespace (Pods)**: Resource usage breakdown by namespace +- **Kubernetes / Compute Resources / Node (Pods)**: Node-level resource monitoring +- **Node Exporter / Nodes**: Detailed node hardware and OS metrics + +![Grafana Dashboard](/k8s-prom-monitor-grafana.jpg) + +## Conclusion + +You now have a complete Kubernetes monitoring solution with Prometheus collecting metrics and GreptimeDB providing efficient long-term storage. This setup enables you to: + +- Monitor cluster and application health in real-time +- Store metrics for historical analysis and capacity planning +- Create rich visualizations and dashboards with Grafana +- Query metrics using both PromQL and SQL + +For more information about GreptimeDB and Prometheus integration, see: + +- [Prometheus Integration](/user-guide/ingest-data/for-observability/prometheus.md) +- [Query Data in GreptimeDB](/user-guide/query-data/overview.md) + diff --git a/versioned_docs/version-1.0/user-guide/concepts/architecture.md b/versioned_docs/version-1.0/user-guide/concepts/architecture.md new file mode 100644 index 0000000000..823f80865d --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/concepts/architecture.md @@ -0,0 +1,54 @@ +--- +keywords: [architecture, Metasrv, Frontend, Datanodes, database cluster] +description: Outlines the architecture of GreptimeDB, including its main components Metasrv, Frontend, and Datanodes. It explains how these components work together to form a robust database cluster and provides links to detailed documentation for each component. +--- + +# Architecture + +![architecture](/architecture-3.png) + +## Components + +In order to form a robust database cluster and keep complexity at an acceptable +level, there are three main components in GreptimeDB architecture: Datanode, +Frontend and Metasrv. + +- [**Metasrv**](/contributor-guide/metasrv/overview.md) is the central command of + GreptimeDB cluster. In a typical cluster deployment, at least three nodes is required to + setup a reliable Metasrv mini-cluster. Metasrv manages database and table + information, including how data spread across the cluster and where to route + requests to. It also keeps monitoring availability and performance of Datanodes, + to ensure its routing table is valid and up-to-date. +- [**Frontend**](/contributor-guide/frontend/overview.md) is a stateless + component that can scale to as many as needed. It accepts incoming requests, + authenticates them, translates them from various protocols into GreptimeDB + internal gRPC, and forwards to certain Datanodes under guidance from Metasrv by table sharding. +- [**Datanodes**](/contributor-guide/datanode/overview.md) hold Regions of + tables in GreptimeDB cluster. It accepts read and write requests sent + from Frontend, executes them against its data, and returns the handle results. + +These three components will be combined in a single binary as GreptimeDB standalone mode, for local or embedded development. + +You can refer to [architecture](/contributor-guide/overview.md) in contributor guide to learn more details about how components work together. + +## How it works + +![Interactions between components](/how-it-works.png) + +- You can interact with the database via various protocols, such as ingesting data using + InfluxDB line protocol, then exploring the data using SQL or PromQL. The Frontend is the + component that clients connect to and operate, thus hide Datanode and Metasrv behind it. +- Assumes a user uses the HTTP API to insert data into the database, by sending a HTTP request to a + Frontend instance. When the Frontend receives the request, it then parses the request body using + corresponding protocol parser, and finds the table to write to from a catalog manager based on + Metasrv. +- The Frontend relies on a push-pull strategy to cache metadata from Metasrv, thus it knows which + Datanode, or more precisely, the Region a request should be sent to. A request may be split and + sent to multiple Regions, if its contents need to be stored in different Regions. +- When Datanode receives the request, it writes the data to the Region, and then sends response + back to the Frontend. Writing to the Region will then write to the underlying storage engine, + which will eventually put the data to persistent device. +- Once Frontend has received all responses from the target Datanodes, it then sends the result + back to the user. + + diff --git a/versioned_docs/version-1.0/user-guide/concepts/data-model.md b/versioned_docs/version-1.0/user-guide/concepts/data-model.md new file mode 100644 index 0000000000..bb38eeee85 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/concepts/data-model.md @@ -0,0 +1,111 @@ +--- +keywords: [data model, time-series tables, tags, timestamps, fields, schema management] +description: Describes the data model of GreptimeDB, focusing on time-series tables. It explains the organization of data into tables with tags, timestamps, and fields, and provides examples of metric and log tables. Design considerations and schema management are also discussed. +--- + +# Data Model + +## Model + +GreptimeDB uses the [time-series](https://en.wikipedia.org/wiki/Time_series) table to guide the organization, compression, and expiration management of data. +The data model is mainly based on the table model in relational databases while considering the characteristics of metrics, logs, and traces data. + +All data in GreptimeDB is organized into tables with names. Each data item in a table consists of three semantic types of columns: `Tag`, `Timestamp`, and `Field`. + +- Table names are often the same as the indicator names, log source names, or metric names. +- `Tag` columns uniquely identify the time-series. + Rows with the same `Tag` values belong to the same time-series. + Some TSDBs may also call them labels. +- `Timestamp` is the root of a metrics, logs, and traces database. + It represents the date and time when the data was generated. + A table can only have one column with the `Timestamp` semantic type, which is also called the `time index`. +- The other columns are `Field` columns. + Fields contain the data indicators or log contents that are collected. + These fields are generally numerical values or string values, + but may also be other types of data, such as geographic locations or timestamps. + +A table clusters rows of the same time-series and sorts rows of the same time-series by `Timestamp`. +The table can also deduplicate rows with the same `Tag` and `Timestamp` values, depending on the requirements of the application. +GreptimeDB stores and processes data by time-series. +Choosing the right schema is crucial for efficient data storage and retrieval; please refer to the [schema design guide](/user-guide/deployments-administration/performance-tuning/design-table.md) for more details. + +### Metrics + +Suppose we have a table called `system_metrics` that monitors the resource usage of machines in data centers: + +```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) +); +``` + +The data model for this table is as follows: + +![time-series-table-model](/time-series-data-model.svg) + +This is very similar to the table model everyone is familiar with. The difference lies in the `TIME INDEX` constraint, which is used to specify the `ts` column as the time index column of this table. + +- The table name here is `system_metrics`. +- The `PRIMARY KEY` constraint specifies the `Tag` columns of the table. + The `host` column represents the hostname of the collected standalone machine. + The `idc` column shows the data center where the machine is located. +- The `Timestamp` column `ts` represents the time when the data is collected. +- The `cpu_util`, `memory_util`, `disk_util`, and `load` columns in the `Field` columns represent + the CPU utilization, memory utilization, disk utilization, and load of the machine, respectively. + These columns contain the actual data. +- The table sorts and deduplicates rows by `host`, `idc`, `ts`. So `select count(*) from system_metrics` will scan all rows. + +### Logs + +Another example is creating a table for logs like web server access logs: + +```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, +) with ('append_mode'='true'); +``` + +- The time index column is `access_time`. +- There are no tags. +- `http_status`, `http_method`, `remote_addr`, `http_refer`, `user_agent` and `request` are fields. +- The table sorts rows by `access_time`. +- The table is an [append-only table](/reference/sql/create.md#create-an-append-only-table) for storing logs that do not support deletion or deduplication. +- Querying an append-only table is usually faster. For example, `select count(*) from access_logs` can use the statistics for result without considering deduplication. + + +To learn how to indicate `Tag`, `Timestamp`, and `Field` columns, please refer to [table management](/user-guide/deployments-administration/manage-data/basic-table-operations.md#create-a-table) and [CREATE statement](/reference/sql/create.md). + +### Traces + +GreptimeDB supports writing OpenTelemetry traces data directly via the OTLP/HTTP protocol, refer to the [OLTP traces data model](/user-guide/ingest-data/for-observability/opentelemetry.md#data-model-2) for detail. + +## Design Considerations + +GreptimeDB is designed on top of the table model for the following reasons: + +- The table model has a broad group of users and it's easy to learn; we have simply introduced the concept of time index to metrics, logs, and traces. +- Schema is metadata that describes data characteristics, and it's more convenient for users to manage and maintain. +- Schema brings enormous benefits for optimizing storage and computing with its information like types, lengths, etc., on which we can conduct targeted optimizations. +- When we have the table model, it's natural for us to introduce SQL and use it to process association analysis and aggregation queries between various tables, reducing the learning and usage costs for users. +- We use a multi-value model where a row of data can have multiple field columns, + instead of the single-value model adopted by OpenTSDB and Prometheus. + The multi-value model is used to model data sources where a metric can have multiple values represented by fields. + The advantage of the multi-value model is that it can write or read multiple values to the database at once, reducing transfer traffic and simplifying queries. In contrast, the single-value model requires splitting the data into multiple records. Read the [blog](https://greptime.com/blogs/2024-05-09-prometheus) for more detailed benefits of the multi-value mode. + + +GreptimeDB uses SQL to manage table schema. Please refer to [table management](/user-guide/deployments-administration/manage-data/basic-table-operations.md) for more information. +However, our definition of schema is not mandatory and leans towards a **schemaless** approach, similar to MongoDB. +For more details, see [Automatic Schema Generation](/user-guide/ingest-data/overview.md#automatic-schema-generation). diff --git a/versioned_docs/version-1.0/user-guide/concepts/features-that-you-concern.md b/versioned_docs/version-1.0/user-guide/concepts/features-that-you-concern.md new file mode 100644 index 0000000000..908d6b5697 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/concepts/features-that-you-concern.md @@ -0,0 +1,79 @@ +--- +keywords: [features, logs, events, traces, updates, deletions, TTL policies, compression rates, high cardinality, continuous aggregation, cloud storage, performance, disaster recovery, geospatial indexing, JSON support] +description: Answers common questions about GreptimeDB's features, including support for metrics,logs, traces, updates, deletions, TTL policies, compression rates, high cardinality, continuous aggregation, cloud storage, performance, disaster recovery, geospatial indexing, and JSON support. +--- + +# Features that You Concern + +## Does GreptimeDB support logs or events? + +Yes. Since v0.9.0, GreptimeDB treats metrics, logs and traces as contextual wide events with timestamps, and thus unifies the processing of metrics, logs, and traces. It supports analyzing metrics, logs, and traces with SQL, PromQL, and streaming with continuous aggregation. + +Please read the [log user guide](/user-guide/logs/overview.md). + +## Does GreptimeDB support updates? + +Sort of, Please refer to the [update data](/user-guide/manage-data/overview.md#update-data) for more information. + +## Does GreptimeDB support deletion? + +Yes, it does. Please refer to the [delete data](/user-guide/manage-data/overview.md#delete-data) for more information. + +## Can I set TTL or retention policy for different tables or measurements? + +Of course. Please refer to the document [on managing data retention with TTL policies](/user-guide/manage-data/overview.md#manage-data-retention-with-ttl-policies). + +## What are the compression rates of GreptimeDB? + +The answer is it depends. +GreptimeDB uses the columnar storage layout, and compresses data by best-in-class algorithms. +And it will select the most suitable compression algorithm based on the column data's statistics and distribution. +GreptimeDB will provide rollups that can compress data more compactly but lose accuracy. + +Therefore, the data compression rate of GreptimeDB may be between 2 and several hundred times, depending on the characteristics of your data and whether you can accept accuracy loss. + +## How does GreptimeDB address the high cardinality issue? + +GreptimeDB resolves this issue by: + +- **Sharding**: It distributes the data and index between different region servers. Read the [architecture](./architecture.md) of GreptimeDB. +- **Smart Indexing**: It doesn't create the inverted index for every tag mandatorily, but chooses a proper index type based on the tag column's statistics and query workload. Find more explanation in this [blog](https://greptime.com/blogs/2022-12-21-storage-engine-design#smart-indexing). +- **MPP**: Besides the indexing capability, the query engine will use the vectorize execution query engine to execute the query in parallel and distributed. + +## Does GreptimeDB support continuous aggregate or downsampling? + +Since 0.8, GreptimeDB added a new function called `Flow`, which is used for continuous aggregation. Please read the [user guide](/user-guide/flow-computation/overview.md). + +## Can I store data in object storage in the cloud? + +Yes, GreptimeDB's data access layer is based on [OpenDAL](https://github.com/apache/incubator-opendal), which supports most kinds of object storage services. +The data can be stored in cost-effective cloud storage services such as AWS S3 or Azure Blob Storage, please refer to storage configuration guide [here](/user-guide/deployments-administration/configuration.md#storage-options). + +GreptimeDB also offers a fully-managed cloud service [GreptimeCloud](https://greptime.com/product/cloud) to help you manage data in the cloud. + +## How is GreptimeDB's performance compared to other solutions? + +[GreptimeDB archives 1 billion cold run #1 in JSONBench!](https://greptime.com/blogs/2025-03-18-jsonbench-greptimedb-performance) + +Please read the performance benchmark reports: + +* [GreptimeDB vs. InfluxDB](https://greptime.com/blogs/2024-08-07-performance-benchmark) +* [GreptimeDB vs. Grafana Mimir](https://greptime.com/blogs/2024-08-02-datanode-benchmark) +* [GreptimeDB vs. ClickHouse vs. ElasticSearch](https://greptime.com/blogs/2025-03-10-log-benchmark-greptimedb) +* [GreptimeDB vs. SQLite](https://greptime.com/blogs/2024-08-30-sqlite) + +## Does GreptimeDB have disaster recovery solutions? + +Yes. Please refer to [disaster recovery](/user-guide/deployments-administration/disaster-recovery/overview.md). + +## Does GreptimeDB has geospatial index? + +Yes. We offer [built-in functions](/reference/sql/functions/geo.md) for Geohash, H3 and S2 index. + +## Any JSON support? + +See [JSON functions](/reference/sql/functions/overview.md#json-functions). + +## More Questions? + +For more comprehensive answers to frequently asked questions about GreptimeDB, including deployment options, migration guides, performance comparisons, and best practices, please visit our [FAQ page](/faq-and-others/faq.md). diff --git a/versioned_docs/version-1.0/user-guide/concepts/key-concepts.md b/versioned_docs/version-1.0/user-guide/concepts/key-concepts.md new file mode 100644 index 0000000000..7a9c49b4ff --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/concepts/key-concepts.md @@ -0,0 +1,60 @@ +--- +keywords: [key concepts, databases, time-series tables, table regions, data types] +description: Introduces the key concepts of GreptimeDB, including databases, time-series tables, table regions, data types, indexes, views, and flows. It explains how these components work together to manage and serve data in GreptimeDB. +--- + +# Key Concepts + +To understand how GreptimeDB manages and serves its data, you need to know about +these building blocks of GreptimeDB. + +## Database + +Similar to *database* in relational databases, a database is the minimal unit of +data container, within which data can be managed and computed. Users can use the database to achieve data isolation, creating a tenant-like effect. + +## Time-Series Table + +GreptimeDB designed time-series table to be the basic unit of data storage. +It is similar to a table in a traditional relational database, but requires a timestamp column(We call it **time index**). +The table holds a set of data that shares a common schema, it's a collection of rows and columns: + +* Column: a vertical set of values in a table, GreptimeDB distinguishes columns into time index, tag and field. +* Row: a horizontal set of values in a table. + +It can be created using SQL `CREATE TABLE`, or inferred from the input data structure using the auto-schema feature. +In a distributed deployment, a table can be split into multiple partitions that sit on different datanodes. + +For more information about the data model of the time-series table, please refer to [Data Model](./data-model.md). + +## Table Engine + +Table engines (also called storage engines) determine how data is stored, managed, and processed within the database. Each engine offers different features, performance characteristics, and trade-offs. GreptimeDB supports `mito` and `metric` engines etc., see [Table Engines](/reference/about-greptimedb-engines.md) for more information. + +## Table Region + +Each partition of distributed table is called a region. A region may contain a +sequence of continuous data, depending on the partition algorithm. Region +information is managed by Metasrv. It's completely transparent to users who send +write requests or queries. + +## Data Types + +Data in GreptimeDB is strongly typed. Auto-schema feature provides some +flexibility when creating a table. Once the table is created, data of the same +column must share common data type. + +Find all the supported data types in [Data Types](/reference/sql/data-types.md). + +## Index + +The `index` is a performance-tuning method that allows faster retrieval of records. GreptimeDB provides various kinds of [indexes](/user-guide/manage-data/data-index.md) to accelerate queries. + +## View + +The `view` is a virtual table that is derived from the result set of a SQL query. It contains rows and columns just like a real table, but it doesn’t store any data itself. +The data displayed in a view is retrieved dynamically from the underlying tables each time the view is queried. + +## Flow + +A `flow` in GreptimeDB refers to a [continuous aggregation](/user-guide/flow-computation/overview.md) process that continuously updates and materializes aggregated data based on incoming data. diff --git a/versioned_docs/version-1.0/user-guide/concepts/overview.md b/versioned_docs/version-1.0/user-guide/concepts/overview.md new file mode 100644 index 0000000000..3acd8d6fc8 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/concepts/overview.md @@ -0,0 +1,23 @@ +--- +keywords: [GreptimeDB, features, data model, architecture, storage locations, key concepts] +description: Provides an overview of GreptimeDB, including its features, data model, architecture, storage locations, key concepts, and notable features. +--- + +# Concepts + +- [Why GreptimeDB](./why-greptimedb.md): This document outlines the features and benefits of GreptimeDB, including its unified design for metrics, logs, and traces; Cloud-native and flexible architecture that allows for deployment in various environments, from embedded to cloud. GreptimeDB is also cost-effective, high-performance, and user-friendly. +- [Data Model](./data-model.md): This document describes the data model of GreptimeDB, including table schema, time index constraint, etc. +- [Architecture](./architecture.md): Get the cloud-native architecture of GreptimeDB. +- [Storage Location](./storage-location.md): This document describes the storage location of GreptimeDB, including local disk, HDFS, and cloud object storage such as S3, Azure Blob Storage, etc. +- [Key Concepts](./key-concepts.md): This document describes the key concepts of GreptimeDB, including table, time index, table region and data types. +- [Features that You Concern](./features-that-you-concern.md): Describes some features that may be concerned about a unified metrics, logs & events database. +- [Frequently Asked Questions](/faq-and-others/faq.md): Comprehensive FAQ covering common questions about GreptimeDB's capabilities, deployment, and usage. + +## Read More + +Get GreptimeDB roadmap and architecture design from blog posts: + +- [This Time, for Real - GreptimeDB is Now Open Source](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 Internal Design — Distributed, Cloud-native, and Enhanced Analytical Ability for Time Series](https://greptime.com/blogs/2022-12-08-GreptimeDB-internal-design) +- [GreptimeDB Storage Engine Design - Catering to Time Series Scenarios](https://greptime.com/blogs/2022-12-21-storage-engine-design) diff --git a/versioned_docs/version-1.0/user-guide/concepts/storage-location.md b/versioned_docs/version-1.0/user-guide/concepts/storage-location.md new file mode 100644 index 0000000000..a0df971b0a --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/concepts/storage-location.md @@ -0,0 +1,47 @@ +--- +keywords: [storage options, local file system, cloud storage, AWS S3, Azure Blob Storage] +description: Describes the storage options for GreptimeDB, including local file systems, cloud storage services like AWS S3, Azure Blob Storage, and more. It explains the local file structure and considerations for disaster recovery and multiple storage engines. +--- + +# Storage Location + +GreptimeDB supports storing data in local file system, AWS S3 and compatible services (including minio, digitalocean space, Tencent Cloud Object Storage(COS), Baidu Object Storage(BOS) and so on), Azure Blob Storage and Aliyun OSS. + +## Local File Structure + +The storage file structure of GreptimeDB includes of the following: + +```cmd +├── metadata + ├── raftlog + ├── rewrite + └── LOCK +├── data +│   ├── greptime +│   └── public +├── cache +├── logs +├── index_intermediate +│   └── staging +└── wal + ├── raftlog + ├── rewrite + └── LOCK +``` + +- `metadata`: The internal metadata directory that keeps catalog, database and table info, procedure states, etc. In cluster mode, this directory does not exist, because all those states including region route info are saved in `Metasrv`. +- `data`: The files in data directory store time series data and index files of GreptimeDB. To customize this path, please refer to [Storage option](/user-guide/deployments-administration/configuration.md#storage-options). The directory is organized in a two-level structure of catalog and schema. +- `cache`: The directory for internal caching, such as object storage cache, etc. +- `logs`: The log files contains all the logs of operations in GreptimeDB. +- `wal`: The wal directory contains the write-ahead log files. +- `index_intermediate`: the temporary intermediate data while indexing. + +## Cloud storage + +The `data` directory in the file structure can be stored in cloud storage. Please refer to [Storage option](/user-guide/deployments-administration/configuration.md#storage-options) for more details. + +Please note that only storing the data directory in object storage is not sufficient to ensure data reliability and disaster recovery. The `wal` and `metadata` also need to be considered for disaster recovery. Please refer to the [disaster recovery documentation](/user-guide/deployments-administration/disaster-recovery/overview.md). + +## Multiple storage engines + +Another powerful feature of GreptimeDB is that you can choose the storage engine for each table. For example, you can store some tables on the local disk, and some tables in Amazon S3 or Google Cloud Storage, see [create table](/reference/sql/create.md#create-table). diff --git a/versioned_docs/version-1.0/user-guide/concepts/why-greptimedb.md b/versioned_docs/version-1.0/user-guide/concepts/why-greptimedb.md new file mode 100644 index 0000000000..95cef834f2 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/concepts/why-greptimedb.md @@ -0,0 +1,98 @@ +--- +keywords: [cloud-native, observability database, high performance, cost-effective, unified design] +description: Explains the motivations and benefits of using GreptimeDB, including its unified design for metrics, logs, and traces, cloud-native architecture, cost-effectiveness, high performance, and ease of use. It highlights key features and deployment strategies. +--- + +# Why GreptimeDB + +GreptimeDB is an open-source observability database built for cloud-native environments. Our core developers have extensive experience building observability platforms, and GreptimeDB embodies their best practices in the following key areas: + +## Unified Processing for Observability Data + +GreptimeDB unifies the processing of metrics, logs, and traces through: +- A consistent [data model](./data-model.md) that treats all observability data as timestamped wide events with context +- Native support for both [SQL](/user-guide/query-data/sql.md) and [PromQL](/user-guide/query-data/promql.md) queries +- Built-in stream processing capabilities ([Flow](/user-guide/flow-computation/overview.md)) for real-time aggregation and analytics +- Seamless correlation analysis across different types of observability data (read the [SQL example](/getting-started/quick-start.md#correlate-metrics-and-logs) for detailed info) + +It replaces complex legacy data stacks with a high-performance single solution. + +

Replaces complex legacy data stacks with a high-performance single solution

+ +## Cost-Effective with Object Storage + +GreptimeDB leverages cloud object storage (like AWS S3 and Azure Blob Storage etc.) as its storage layer, dramatically reducing costs compared to traditional storage solutions. Its optimized columnar storage and advanced compression algorithms achieve up to 50x cost efficiency, while the pay-as-you-go model (via [GreptimeCloud](https://greptime.com/product/cloud)) ensures you only pay for what you use. + +## High Performance + +As for performance optimization, GreptimeDB utilizes different techniques such as LSM Tree, data sharding, and flexible WAL options (local disk or distributed services like Kafka), to handle large workloads of observability data ingestion. + +GreptimeDB is written in pure Rust for superior performance and reliability. The powerful and fast query engine is powered by vectorized execution and distributed parallel processing (thanks to [Apache DataFusion](https://datafusion.apache.org/)), and combined with [indexing capabilities](/user-guide/manage-data/data-index.md) such as inverted index, skipping index, and full-text index. GreptimeDB combines smart indexing and Massively Parallel Processing (MPP) to boost pruning and filtering. + +[GreptimeDB achieves 1 billion cold runs #1 in JSONBench!](https://greptime.com/blogs/2025-03-18-jsonbench-greptimedb-performance) Read more [benchmark reports](https://www.greptime.com/blogs/2024-09-09-report-summary). + +## Elastic Scaling with Kubernetes + +Built from the ground up for Kubernetes, GreptimeDB features a disaggregated storage and compute architecture that enables true elastic scaling: +- Independent scaling of storage and compute resources +- Unlimited horizontal scalability through Kubernetes +- Resource isolation between different workloads (ingestion, querying, compaction) +- Automatic failover and high availability + +![Storage/Compute Disaggregation, Compute/Compute separation](/storage-compute-disaggregation-compute-compute-separation.png) + +## Flexible Architecture: From Edge to Cloud + +![The architecture of GreptimeDB](/architecture-2.png) + +GreptimeDB’s modularized architecture allows different components to operate independently or in unison as needed. Its flexible design supports a wide variety of deployment scenarios, from edge devices to cloud environments, while still using consistent APIs for operations. For example: +- Frontend, datanode, and metasrv can be merged into a standalone binary +- Components like WAL or indexing can be enabled or disabled per table + +This flexibility ensures that GreptimeDB meets deployment requirements for edge-to-cloud solutions, like the [Edge-Cloud Integrated Solution](https://greptime.com/product/carcloud). + +From embedded and standalone deployments to cloud-native clusters, GreptimeDB adapts to various environments easily. + +## Easy to Use + +### Easy to Deploy and Maintain + +GreptimeDB simplifies deployment and maintenance with tools like: +- [K8s Operator](https://github.com/GreptimeTeam/greptimedb-operator) +- [Command-line Tool](https://github.com/GreptimeTeam/gtctl) +- Embedded [Dashboard](https://github.com/GreptimeTeam/dashboard) + +For an even simpler experience, check out the fully managed [GreptimeCloud](https://greptime.com/product/cloud). + +### Easy to Integrate + +GreptimeDB supports multiple data ingestion protocols, making integration with existing observability stacks seamless: +- **Database protocols**: MySQL, PostgreSQL +- **Time-series protocols**: InfluxDB, OpenTSDB, Prometheus RemoteStorage +- **Observability protocols**: OpenTelemetry, Loki, ElasticSearch +- **gRPC with SDKs**: Java, Go, Erlang, etc. + +For data querying, GreptimeDB provides: +- **SQL**: For real-time queries, analytics, and database management +- **PromQL**: Native support for real-time metrics querying and Grafana integration + +GreptimeDB integrates seamlessly with your observability stack while maintaining high performance and flexibility. + +![Greptime Ecosystem](/greptime-ecosystem.png) + +### Simple Data Model with Automatic Schema + +GreptimeDB introduces a new data model that combines time-series and relational models: +- Data is represented as a table with rows and columns +- Metrics, logs, and traces map to columns with a time index for timestamps +- Schema is created dynamically and new columns are added automatically as data is ingested + +![Time-Series Table](/time-series-table.png) + +However, our definition of schema is not mandatory, but rather leans towards the schema-less approach of databases like MongoDB. Tables will be created automatically and dynamically as data is written, and newly appearing columns (Tag and Field) will be added automatically. For a more detailed explanation, please read the [Data Model](./data-model.md). + + +For more details, explore our blogs: +- ["Observability 2.0 and the Database for It"](https://greptime.com/blogs/2025-04-25-greptimedb-observability2-new-database) +- ["This Time, for Real"](https://greptime.com/blogs/2022-11-15-this-time-for-real) +- ["Unified Storage for Observability - GreptimeDB's Approach"](https://greptime.com/blogs/2024-12-24-observability) diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/authentication/overview.md b/versioned_docs/version-1.0/user-guide/deployments-administration/authentication/overview.md new file mode 100644 index 0000000000..a7177c68fe --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/authentication/overview.md @@ -0,0 +1,15 @@ +--- +keywords: [authentication, user providers, static user provider, LDAP user provider] +description: Overview of authentication in GreptimeDB, including static user provider and LDAP user provider for authenticating users. +--- + +# Authentication + +Authentication occurs when a user attempts to connect to the database. In GreptimeDB, users are authenticated by "user +provider"s. There are various implementations of user providers in GreptimeDB: + +- [Static User Provider](./static.md): A simple built-in user provider implementation that finds users from a static + file. +- [LDAP User Provider](/enterprise/deployments-administration/authentication.md): **Enterprise feature.** A user provider implementation that authenticates users against an external LDAP + server. + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/authentication/static.md b/versioned_docs/version-1.0/user-guide/deployments-administration/authentication/static.md new file mode 100644 index 0000000000..15e77061c2 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/authentication/static.md @@ -0,0 +1,90 @@ +--- +keywords: [GreptimeDB, static user authentication, user credentials, configuration file, database authentication] +description: Instructions for setting up static user authentication in GreptimeDB using a configuration file with user credentials. +--- + +# Static User Provider + +GreptimeDB offers a simple built-in mechanism for authentication, allowing users to configure either a fixed account for convenient usage or an account file for multiple user accounts. By passing in a file, GreptimeDB loads all users listed within it. + +## Standalone Mode + +GreptimeDB reads the user configuration from a file where each line defines a user with their password and optional permission mode. + +### Basic Configuration + +The basic format uses `=` as a separator between username and password: + +``` +greptime_user=greptime_pwd +alice=aaa +bob=bbb +``` + +Users configured this way have full read-write access by default. + +### Permission Modes + +You can optionally specify permission modes to control user access levels. The format is: + +``` +username:permission_mode=password +``` + +Available permission modes: +- `rw` or `readwrite` - Full read and write access (default when not specified) +- `ro` or `readonly` - Read-only access +- `wo` or `writeonly` - Write-only access + +Example configuration with mixed permission modes: + +``` +admin=admin_pwd +alice:readonly=aaa +bob:writeonly=bbb +viewer:ro=viewer_pwd +editor:rw=editor_pwd +``` + +In this configuration: +- `admin` has full read-write access (default) +- `alice` has read-only access +- `bob` has write-only access +- `viewer` has read-only access +- `editor` has explicitly set read-write access + +### Starting the Server + +Start the server with the `--user-provider` parameter and set it to `static_user_provider:file:` (replace `` with the path to your user configuration file): + +```shell +./greptime standalone start --user-provider=static_user_provider:file: +``` + +The users and their permissions will be loaded into GreptimeDB's memory. You can create connections to GreptimeDB using these user accounts with their respective access levels enforced. + +:::tip Note +When using `static_user_provider:file`, the file’s contents are loaded at startup. Changes or additions to the file have no effect while the database is running. +::: + +### Dynamic File Reloading + +If you need to update user credentials without restarting the server, you can use the `watch_file_user_provider` instead of `static_user_provider:file`. This provider monitors the credential file for changes and automatically reloads it: + +```shell +./greptime standalone start --user-provider=watch_file_user_provider: +``` + +The watch file provider: +- Uses the same file format as the static file provider +- Automatically detects file modifications and reloads credentials +- Allows adding, removing, or modifying users without server restart +- If the file is temporarily unavailable or invalid, it keeps the last valid configuration + +This is particularly useful in production environments where you need to manage user access dynamically. + +## Kubernetes Cluster + +You can configure the authentication users in the `values.yaml` file. +For more details, please refer to the [Helm Chart Configuration](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md#authentication-configuration). + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/capacity-plan.md b/versioned_docs/version-1.0/user-guide/deployments-administration/capacity-plan.md new file mode 100644 index 0000000000..27024821a5 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/capacity-plan.md @@ -0,0 +1,72 @@ +--- +keywords: [GreptimeDB capacity planning, CPU requirements, memory requirements, storage requirements, data retention policy] +description: Provides guidelines for CPU, memory, and storage requirements for GreptimeDB based on data points processed per second, query requests per second, data volume, and data retention policy. Includes an example scenario. +--- + +# Capacity Plan + +This guide provides general advice on the CPU, memory, and storage requirements for GreptimeDB. + +GreptimeDB is designed to be lightweight upon startup, +which allows for the database to be initiated with minimal server resources. +However, when configuring your server capacity for a production environment, +there are several key considerations: + +- Data points processed per second +- Query requests per second +- Data volume +- Data retention policy +- Hardware costs + +To monitor the various metrics of GreptimeDB, please refer to [Monitoring](/user-guide/deployments-administration/monitoring/overview.md). + +## CPU + +Generally, applications that handle many concurrent queries, process large amounts of data, +or perform other compute-intensive operations will require more CPU cores. + +Here are some recommendations for CPU resource usage, +but the actual number of CPUs you should use depends on your workload. + +Consider allocating 30% of your CPU resources for data ingestion, +with the remaining 70% to querying and analytics. + +A recommended guideline for resource allocation is to maintain a CPU to memory ratio of 1:4 (for instance, 8 core to 32 GB). +However, if your workload consists primarily of data ingestion with few queries, +a ratio of 1:2 (8 core to 16 GB) can also be acceptable. + +## Memory + +In general, the more memory you have, the faster your queries will run. +For basic workloads, it's recommended to have at least 8 GB of memory, and 32 GB for more advanced ones. + +## Storage + +GreptimeDB features an efficient data compaction mechanism that reduces the original data size to about 1/8 to 1/10 of its initial volume. +This allows GreptimeDB to store large amounts of data in a significantly smaller space. + +Data can be stored either in a local file system or in cloud storage, such as AWS S3. +FOr more information on storage options, +please refer to the [storage configuration](/user-guide/deployments-administration/configuration.md#storage-options) documentation. + +Cloud storage is highly recommended for data storage due to its simplicity in managing storage. +With cloud storage, only about 200GB of local storage space is needed for query-related caches and Write-Ahead Log (WAL). + +In order to manage the storage costs effectively, +it is recommended setting a [retention policy](/user-guide/concepts/features-that-you-concern.md#can-i-set-ttl-or-retention-policy-for-different-tables-or-measurements). + +## Example + +Consider a scenario where your database handles a query rate of about 200 simple queries per second (QPS) and an ingestion rate of approximately 300k data points per second, using cloud storage for data. + +Given the high ingestion and query rates, +here's an example of how you might allocate resources: + +- CPU: 8 cores +- Memory: 32 GB +- Storage: 200 GB + +Such an allocation is designed to optimize performance, +ensuring smooth data ingestion and query processing without system overload. +However, remember these are just guidelines, +and actual requirements may vary based on specific workload characteristics and performance expectations. diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/configuration.md b/versioned_docs/version-1.0/user-guide/deployments-administration/configuration.md new file mode 100644 index 0000000000..692d6202c0 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/configuration.md @@ -0,0 +1,804 @@ +--- +keywords: [configuration, command line options, configuration file, environment variables, default values] +description: Detailed guide on configuring GreptimeDB, including command line options, configuration file options, environment variables, and default values for various components and features. +--- + +# Configuration + +GreptimeDB supports **layered configuration** with the following precedence order (where each item overrides the one below it): + +- Greptime command line options +- Configuration file options +- Environment variables +- Default values + +You only need to set up the configurations you require. +GreptimeDB will assign default values for any settings not configured. + +## How to set up configurations + +### Greptime command line options + +You can specify several configurations using command line arguments. +For example, to start GreptimeDB in standalone mode with a configured HTTP address: + +```shell +greptime standalone start --http-addr 127.0.0.1:4000 +``` + +For all the options supported by the Greptime command line, +refer to the [GreptimeDB Command Line Interface](/reference/command-lines/overview.md). + +### Configuration file options + +You can specify configurations in a TOML file. +For example, create a configuration file `standalone.example.toml` as shown below: + +```toml +[storage] +type = "File" +data_home = "greptimedb_data" +``` + +Then, specify the configuration file using the command line argument `-c [file_path]`. + +```sh +greptime [standalone | frontend | datanode | metasrv] start -c config/standalone.example.toml +``` + +For example, to start in standalone mode: + +```bash +greptime standalone start -c standalone.example.toml +``` + +#### Example files + +Below are example configuration files for each GreptimeDB component, +including all available configurations. +In actual scenarios, +you only need to configure the required options and do not need to configure all options as in the sample file. + +- [standalone](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/standalone.example.toml) +- [frontend](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/frontend.example.toml) +- [datanode](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/datanode.example.toml) +- [flownode](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/flownode.example.toml) +- [metasrv](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/metasrv.example.toml) + +### Helm Configurations + +When deploying GreptimeDB on Kubernetes using Helm charts, +you can configure certain settings directly in the Helm `values.yaml` file. +Please refer to the [Helm configuration documentation](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md) for all Helm-supported configurations. + +For configurations that are available only in the [options](#options) section of this document, +you can [inject complete TOML configuration files](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md#injecting-configuration-files) into your deployment. + + +### Environment variable + +Every item in the configuration file can be mapped to environment variables. +For example, to set the `data_home` configuration item for the datanode using an environment variable: + +```toml +# ... +[storage] +data_home = "/data/greptimedb" +# ... +``` + +Use the following shell command to set the environment variable in the following format: + +``` +export GREPTIMEDB_DATANODE__STORAGE__DATA_HOME=/data/greptimedb +``` + +#### Environment Variable Rules + +- Each environment variable should have the component prefix, for example: + + - `GREPTIMEDB_FRONTEND` + - `GREPTIMEDB_METASRV` + - `GREPTIMEDB_DATANODE` + - `GREPTIMEDB_STANDALONE` + +- Use **double underscore `__`** separators. For example, the data structure `storage.data_home` is transformed to `STORAGE__DATA_HOME`. + +The environment variable also accepts lists that are separated by commas `,`, for example: + +``` +GREPTIMEDB_METASRV__META_CLIENT__METASRV_ADDRS=127.0.0.1:3001,127.0.0.1:3002,127.0.0.1:3003 +``` + +## Options + +In this section, we will introduce some main configuration options. +For all options, refer to the [Configuration Reference](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/config.md) on Github. + +### Protocol options + +Protocol options are valid in `frontend` and `standalone` subcommands, +specifying protocol server addresses and other protocol-related options. + +:::tip NOTE +The HTTP protocol configuration is available for all GreptimeDB components: `frontend`, `datanode`, `flownode`, and `metasrv`. +::: + +Below is an example configuration with default values. +You can change the values or disable certain protocols in your configuration file. +For example, to disable OpenTSDB protocol support, set the `enable` parameter to `false`. +Note that HTTP and gRPC protocols cannot be disabled for the database to function correctly. + +```toml +[http] +addr = "127.0.0.1:4000" +timeout = "30s" +body_limit = "64MB" + +[grpc] +bind_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 = "" +watch = false + +[postgres] +enable = true +addr = "127.0.0.1:4003" +runtime_size = 2 + +[postgres.tls] +mode = "disable" +cert_path = "" +key_path = "" +watch = false + +[opentsdb] +enable = true + +[influxdb] +enable = true + +[prom_store] +enable = true +with_metric_engine = true +``` + +The following table describes the options in detail: + +| Option | Key | Type | Description | +| ---------- | -------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| http | | | HTTP server options | +| | addr | String | Server address, "127.0.0.1:4000" by default | +| | timeout | String | HTTP request timeout, "30s" by default | +| | body_limit | String | HTTP max body size, "64MB" by default | +| | prom_validation_mode | String | Whether to check if strings are valid UTF-8 strings in Prometheus remote write requests. Available options: `strict`(reject any request with invalid UTF-8 strings), `lossy`(replace invalid characters with [UTF-8 REPLACEMENT CHARACTER U+FFFD, which looks like �](https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-23/#G24272)), `unchecked`(do not validate strings). | +| grpc | | | gRPC server options | +| | bind_addr | String | The address to bind the gRPC server, "127.0.0.1:4001" by default | +| | runtime_size | Integer | The number of server worker threads, 8 by default | +| | max_connection_age | String | Maximum lifetime of a gRPC connection that the server keeps it. Refer to ["MAX_CONNECTION_AGE"](https://grpc.io/docs/guides/keepalive/) for details. Defaults to not set. Example: "1h" for 1 hour, "30m" for 30 minutes | +| | flight_compression | String | Compression mode for frontend side Arrow IPC service. Available options: `none`: disable all compression, `transport`: only enable gRPC transport compression (zstd), `arrow_ipc`: only enable Arrow IPC compression (lz4), `all`: enable all compression. Default value is `none`.| +| mysql | | | MySQL server options | +| | enable | Boolean | Whether to enable MySQL protocol, true by default | +| | addr | String | Server address, "127.0.0.1:4002" by default | +| | runtime_size | Integer | The number of server worker threads, 2 by default | +| influxdb | | | InfluxDB Protocol options | +| | enable | Boolean | Whether to enable InfluxDB protocol in HTTP API, true by default | +| opentsdb | | | OpenTSDB Protocol options | +| | enable | Boolean | Whether to enable OpenTSDB protocol in HTTP API, true by default | +| prom_store | | | Prometheus remote storage options | +| | enable | Boolean | Whether to enable Prometheus Remote Write and read in HTTP API, true by default | +| | with_metric_engine | Boolean | Whether to use the metric engine on Prometheus Remote Write, true by default | +| postgres | | | PostgresSQL server options | +| | enable | Boolean | Whether to enable PostgresSQL protocol, true by default | +| | addr | String | Server address, "127.0.0.1:4003" by default | +| | runtime_size | Integer | The number of server worker threads, 2 by default | + +For MySQL, Postgres and gRPC interface, TLS can be configured to enable transport +layer security. + +| Option | Key | Type | Description | +| ------------------------------------------| ----------- | ------- | ------------------------------------------------------------- | +| `mysql.tls`, `postgres.tls` or `grpc.tls` | | | TLS configuration for MySQL and Postgres | +| | `mode` | String | TLS mode, options are `disable`, `prefer` and `require` | +| | `cert_path` | String | File path for TLS certificate | +| | `key_path` | String | File path for TLS private key | +| | `watch` | Boolean | Watch file system changes and reload certificate and key file | + +### Query options + +The `query` options are valid in standalone, datanode and frontend modes, which controls the query engine's behavior. + +The following table describes the options in detail: + +| Option | Key | Type | Description | +| ----------- | ------- | ---- | ----------------------------------------------------------------------------------- | +| parallelism | Integer | `0` | Parallelism of the query engine. Default to 0, which means the number of CPU cores. | + +A sample configuration: + +```toml +[query] +parallelism = 0 +``` + +### Storage options + +The `storage` options are valid in datanode and standalone mode, which specify the database data directory and other storage-related options. + +GreptimeDB supports storing data in local file system, AWS S3 and compatible services (including MinIO, digitalocean space, Tencent Cloud Object Storage(COS), Baidu Object Storage(BOS) and so on), Azure Blob Storage and Aliyun OSS. + +| Option | Key | Type | Description | +| ------- | ------------------------- | ------- | -------------------------------------------------------------------------------- | +| storage | | | Storage options | +| | type | String | Storage type, supports "File", "S3" and "Oss" etc. | +| File | | | Local file storage options, valid when type="File" | +| | data_home | String | Database storage root directory, "./greptimedb_data" by default | +| S3 | | | AWS S3 storage options, valid when type="S3" | +| | name | String | The storage provider name, default is `S3` | +| | bucket | String | The S3 bucket name | +| | root | String | The root path in S3 bucket | +| | endpoint | String | The API endpoint of S3 | +| | region | String | The S3 region | +| | access_key_id | String | The S3 access key id | +| | secret_access_key | String | The S3 secret access key | +| | enable_virtual_host_style | Boolean | Send API requests in virtual host style instead of path style. Default is false. | +| Oss | | | Aliyun OSS storage options, valid when type="Oss" | +| | name | String | The storage provider name, default is `Oss` | +| | bucket | String | The OSS bucket name | +| | root | String | The root path in OSS bucket | +| | endpoint | String | The API endpoint of OSS | +| | access_key_id | String | The OSS AccessKey ID | +| | access_key_secret | String | The OSS AccessKey Secret | +| Azblob | | | Azure Blob Storage options, valid when type="Azblob" | +| | name | String | The storage provider name, default is `Azblob` | +| | container | String | The container name | +| | root | String | The root path in container | +| | endpoint | String | The API endpoint of Azure Blob Storage | +| | account_name | String | The account name of Azure Blob Storage | +| | account_key | String | The access key | +| | sas_token | String | The shared access signature | +| Gsc | | | Google Cloud Storage options, valid when type="Gsc" | +| | name | String | The storage provider name, default is `Gsc` | +| | root | String | The root path in Gsc bucket | +| | bucket | String | The Gsc bucket name | +| | scope | String | The Gsc service scope | +| | credential_path | String | The Gsc credentials path | +| | endpoint | String | The API endpoint of Gsc | + +A file storage sample configuration: + +```toml +[storage] +type = "File" +data_home = "./greptimedb_data/" +``` + +A S3 storage sample configuration: + +```toml +[storage] +type = "S3" +bucket = "test_greptimedb" +root = "/greptimedb" +access_key_id = "" +secret_access_key = "" +``` + +### Storage http client + +`[storage.http_client]` sets the options for the http client that is used to send requests to the storage service. + +Only applied for storage types "S3", "Oss", "Azblob" and "Gcs". + +| Key | Type | Default | Description | +| ------------------------ | ------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| `pool_max_idle_per_host` | Integer | 1024 | The maximum idle connection per host allowed in the pool. | +| `connect_timeout` | String | "30s" (30 seconds) | The timeout for only the connect phase of a http client. | +| `timeout` | String | "30s" (30 seconds) | The total request timeout, applied from when the request starts connecting until the response body has finished. Also considered a total deadline. | +| `pool_idle_timeout` | String | "90s" (90 seconds) | The timeout for idle sockets being kept-alive. | + +### Storage engine provider + +`[[storage.providers]]` setups the table storage engine providers. Based on these providers, you can create a table with a specified storage, see [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 = "" +``` + +All configured providers' names can be used as the `storage` option when creating tables. + +For storage from the same provider, if you want to use different S3 buckets as storage engines for different tables, you can set different `name` values and specify the `storage` option when creating the table. + +### Object storage cache + +When using remote storage services like AWS S3, Alibaba Cloud OSS, or Azure Blob Storage, fetching data during queries can be time-consuming. To address this, GreptimeDB provides a local cache mechanism to speed up repeated data access. + +GreptimeDB enables local file caching for remote object storage by default, with both read and write cache capacity set to `5GiB`. + + +Usually you don't have to configure the cache unless you want to specify the cache capacity. +```toml +[storage] +type = "S3" +bucket = "test_greptimedb" +root = "/greptimedb" +access_key_id = "" +secret_access_key = "" +cache_capacity = "10GiB" +# cache_path = "/path/to/cache/home" +``` + +The `cache_path` specifies the home directory for storing cache files, while `cache_capacity` determines the maximum total file size allowed in the cache directory in bytes. You can disable the read cache by setting `cache_path` to an empty string. The default cache path is under the `{data_home}`. We recommend that you don't set the `cache_path` because the database can choose it automatically. + +The write cache is no more experimental since `v0.12`. You can configure the cache size in the mito config if you don't want to use the default value. +```toml +[[region_engine]] +[region_engine.mito] + +write_cache_size = "10GiB" +``` + +Read [Performance Tuning Tips](/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md) for more detailed info. + +### WAL options + +GreptimeDB supports three WAL storage options—Local WAL, Remote WAL, and Noop WAL. See the [WAL Overview](/user-guide/deployments-administration/wal/overview.md) for a comparison of the options. For detailed configurations, refer to the [Local WAL](/user-guide/deployments-administration/wal/local-wal.md), [Remote WAL](/user-guide/deployments-administration/wal/remote-wal/configuration.md), and [Noop WAL](/user-guide/deployments-administration/wal/noop-wal.md) documentation. + + +### Logging options + +`frontend`, `metasrv`, `datanode` and `standalone` can all configure log and tracing related parameters in the `[logging]` section: + +```toml +[logging] +dir = "./greptimedb_data/logs" +level = "info" +enable_otlp_tracing = false +otlp_endpoint = "localhost:4317" +append_stdout = true +[logging.tracing_sample_ratio] +default_ratio = 1.0 +``` + +- `dir`: log output directory. +- `level`: output log level, available log level are `info`, `debug`, `error`, `warn`, the default level is `info`. +- `enable_otlp_tracing`: whether to turn on tracing, not turned on by default. +- `otlp_endpoint`: Export the target endpoint of tracing using gRPC-based OTLP protocol, the default value is `localhost:4317`. +- `append_stdout`: Whether to append logs to stdout. Defaults to `true`. +- `tracing_sample_ratio`: This field can configure the sampling rate of tracing. How to use `tracing_sample_ratio`, please refer to [How to configure tracing sampling rate](/user-guide/deployments-administration/monitoring/tracing.md#guide-how-to-configure-tracing-sampling-rate). + +How to use distributed tracing, please reference [Tracing](/user-guide/deployments-administration/monitoring/tracing.md#tutorial-use-jaeger-to-trace-greptimedb) + +### Region engine options + +The parameters corresponding to different storage engines can be configured for `datanode` and `standalone` in the `[region_engine]` section. Currently, only options for `mito` region engine is available. + +Frequently used options: + +```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.index] +aux_path = "" +staging_size = "2GB" +metadata_cache_size = "64MiB" +content_cache_size = "128MiB" +content_cache_page_size = "64KiB" + +[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" +``` + +The `mito` engine provides an experimental memtable which optimizes for write performance and memory efficiency under large amounts of time-series. Its read performance might not as fast as the default `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" +``` + +Available options: + +| Key | Type | Default | Descriptions | +| ---------------------------------------- | ------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `num_workers` | Integer | `8` | Number of region workers. | +| `manifest_checkpoint_distance` | Integer | `10` | Number of meta action updated to trigger a new checkpoint for the manifest. | +| `max_background_jobs` | Integer | `4` | Max number of running background jobs | +| `auto_flush_interval` | String | `1h` | Interval to auto flush a region if it has not flushed yet. | +| `global_write_buffer_size` | String | `1GB` | Global write buffer size for all regions. If not set, it's default to 1/8 of OS memory with a max limitation of 1GB. | +| `global_write_buffer_reject_size` | String | `2GB` | Global write buffer size threshold to reject write requests. If not set, it's default to 2 times of `global_write_buffer_size` | +| `sst_meta_cache_size` | String | `128MB` | Cache size for SST metadata. Setting it to 0 to disable the cache.
If not set, it's default to 1/32 of OS memory with a max limitation of 128MB. | +| `vector_cache_size` | String | `512MB` | Cache size for vectors and arrow arrays. Setting it to 0 to disable the cache.
If not set, it's default to 1/16 of OS memory with a max limitation of 512MB. | +| `page_cache_size` | String | `512MB` | Cache size for pages of SST row groups. Setting it to 0 to disable the cache.
If not set, it's default to 1/8 of OS memory. | +| `selector_result_cache_size` | String | `512MB` | Cache size for time series selector (e.g. `last_value()`). Setting it to 0 to disable the cache.
If not set, it's default to 1/8 of OS memory. | +| `sst_write_buffer_size` | String | `8MB` | Buffer size for SST writing. | +| `scan_parallelism` | Integer | `0` | Parallelism to scan a region (default: 1/4 of cpu cores).
- `0`: using the default value (1/4 of cpu cores).
- `1`: scan in current thread.
- `n`: scan in parallelism n. | +| `index` | -- | -- | The options for index in Mito engine. | +| `index.aux_path` | String | `""` | Auxiliary directory path for the index in the filesystem. This path is used to store intermediate files for creating the index and staging files for searching the index. It defaults to `{data_home}/index_intermediate`. The default name for this directory is `index_intermediate` for backward compatibility. This path contains two subdirectories: `__intm` for storing intermediate files used during index creation, and `staging` for storing staging files used during index searching. | +| `index.staging_size` | String | `2GB` | The maximum capacity of the staging directory. | +| `index.metadata_cache_size` | String | `64MiB` | Cache size for index metadata. | +| `index.content_cache_size` | String | `128MiB` | Cache size for index content. | +| `index.content_cache_page_size` | String | `64KiB` | Page size for index content cache. | +| `inverted_index` | -- | -- | The options for inverted index in Mito engine. | +| `inverted_index.create_on_flush` | String | `auto` | Whether to create the index on flush.
- `auto`: automatically
- `disable`: never | +| `inverted_index.create_on_compaction` | String | `auto` | Whether to create the index on compaction.
- `auto`: automatically
- `disable`: never | +| `inverted_index.apply_on_query` | String | `auto` | Whether to apply the index on query
- `auto`: automatically
- `disable`: never | +| `inverted_index.mem_threshold_on_create` | String | `64M` | Memory threshold for performing an external sort during index creation.
Setting to empty will disable external sorting, forcing all sorting operations to happen in memory. | +| `inverted_index.intermediate_path` | String | `""` | File system path to store intermediate files for external sorting (default `{data_home}/index_intermediate`). | +| `memtable.type` | String | `time_series` | Memtable type.
- `time_series`: time-series memtable
- `partition_tree`: partition tree memtable (experimental) | +| `memtable.index_max_keys_per_shard` | Integer | `8192` | The max number of keys in one shard.
Only available for `partition_tree` memtable. | +| `memtable.data_freeze_threshold` | Integer | `32768` | The max rows of data inside the actively writing buffer in one shard.
Only available for `partition_tree` memtable. | +| `memtable.fork_dictionary_bytes` | String | `1GiB` | Max dictionary bytes.
Only available for `partition_tree` memtable. | + +### Specify meta client + +The `meta_client` options are valid in `datanode` and `frontend` mode, which specify the Metasrv client information. + +```toml +metasrv_addrs = ["127.0.0.1:3002"] +timeout = "3s" +connect_timeout = "1s" +ddl_timeout = "10s" +tcp_nodelay = true +``` + +The `meta_client` configures the Metasrv client, including: + +- `metasrv_addrs`: The Metasrv address list. +- `timeout`: operation timeout, `3s` by default. +- `connect_timeout`, connect server timeout, `1s` by default. +- `ddl_timeout`, DDL execution timeout, `10s` by default. +- `tcp_nodelay`, `TCP_NODELAY` option for accepted connections, true by default. + +### Monitor metrics options + +These options are used to save system metrics to GreptimeDB itself. +For instructions on how to use this feature, please refer to the [Monitoring](/user-guide/deployments-administration/monitoring/overview.md) guide. + +```toml +[export_metrics] +# Whether to enable export_metrics +enable=true +# Export time interval +write_interval = "30s" +``` + +- `enable`: Whether to enable export_metrics, `false` by default. +- `write_interval`: Export time interval. + +#### `self_import` method + +If you are using `standalone`, you can use the `self_import` method to export metrics to GreptimeDB itself. + +```toml +[export_metrics] +# Whether to enable export_metrics +enable=true +# Export time interval +write_interval = "30s" +[export_metrics.self_import] +db = "information_schema" +``` + +- `db`: The default database used by `self_import` is `information_schema`. You can also create another database for saving system metrics. + +#### `remote_write` method + +The `remote_write` method is supported by `datanode`, `frontend`, `metasrv`, and `standalone`. +It sends metrics to a receiver compatible with the [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`: URL specified by Prometheus Remote-Write protocol. +- `headers`: Some optional HTTP parameters, such as authentication information. + +### Heartbeat configuration +Heartbeat configuration is available in `frontend` and `datanode`. +```toml +[heartbeat] +interval = "3s" +retry_interval = "3s" +``` + +| Key | Type | Default | Description | +| -------------------------- | ------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `heartbeat` | -- | -- | -- | +| `heartbeat.interval` | String | `3s` | Interval for sending heartbeat messages to the Metasrv. | +| `heartbeat.retry_interval` | String | `3s` | Interval for retrying to establish the heartbeat connection to the Metasrv. Note that this option is ignored in Datanode heartbeat implementation because the Datanode must renew its lease through heartbeat within the keep-alive mechanism's lease period. It has a special retry strategy and doesn't allow custom configuration. | + +### Default time zone configuration + +The `default_timezone` option is applicable in both `frontend` and `standalone` modes, with a default value of `UTC`. +It specifies the default client timezone for interactions with GreptimeDB. +If the time zone is [specified in the clients](/user-guide/timezone.md#specify-time-zone-in-clients), this option will be overridden for that client session. + +```toml +default_timezone = "UTC" +``` + +The `default_timezone` value can be any named time zone, such as `Europe/Berlin` or `Asia/Shanghai`. +For information on how the client time zone affects data ingestion and querying, +refer to the [Time Zone](/user-guide/timezone.md#impact-of-time-zone-on-sql-statements) guide. + +### Metasrv-only configuration + +```toml +# The working home directory. +data_home = "./greptimedb_data" +# Store server address default to etcd store. +# For postgres store, the format is: +# "password=password dbname=postgres user=postgres host=localhost port=5432" +# For mysql store, the format is: +# "mysql://user:password@ip:port/dbname" +# For etcd store, the format is: +# "127.0.0.1:2379" +store_addrs = ["127.0.0.1:2379"] +# If it's not empty, the metasrv will store all data with this key prefix. +store_key_prefix = "" +# The datastore for meta server. +# Available values: +# - `etcd_store` (default value) +# - `memory_store` +# - `postgres_store` +# - `mysql_store` +backend = "etcd_store" +# Table name in RDS to store metadata. Effect when using a RDS kvbackend. +# **Only used when backend is RDS kvbacken.** +meta_table_name = "greptime_metakv" +# Advisory lock id in PostgreSQL for election. Effect when using PostgreSQL as kvbackend +# Only used when backend is `postgres_store`. +meta_election_lock_id = 1 +# Datanode selector type. +# - `round_robin` (default value) +# - `lease_based` +# - `load_based` +# For details, please see "https://docs.greptime.com/developer-guide/metasrv/selector". +selector = "round_robin" +# Store data in memory, false by default. +use_memory_store = false +# Whether to enable region failover. +# This feature is only available on GreptimeDB running on cluster mode and +# - Using Remote WAL +# - Using shared storage (e.g., s3). +enable_region_failover = false +## The delay before starting region failure detection. +## This delay helps prevent Metasrv from triggering unnecessary region failovers before all Datanodes are fully started. +## Especially useful when the cluster is not deployed with GreptimeDB Operator and maintenance mode is not enabled. +region_failure_detector_initialization_delay = "10m" +# Whether to allow region failover on local WAL. +# **This option is not recommended to be set to true, +# because it may lead to data loss during failover.** +allow_region_failover_on_local_wal = false + +## Procedure storage options. +[procedure] + +## Procedure max retry time. +max_retry_times = 12 + +## Initial retry delay of procedures, increases exponentially +retry_delay = "500ms" + +## Max running procedures. +## The maximum number of procedures that can be running at the same time. +## If the number of running procedures exceeds this limit, the procedure will be rejected. +max_running_procedures = 128 + +# Failure detectors options. +# GreptimeDB uses the Phi Accrual Failure Detector algorithm to detect datanode failures. +[failure_detector] + +## Maximum acceptable φ before the peer is treated as failed. +## Lower values react faster but yield more false positives. +threshold = 8.0 + +## The minimum standard deviation of the heartbeat intervals. +## So tiny variations don't make φ explode. Prevents hypersensitivity when heartbeat intervals barely vary. +min_std_deviation = "100ms" + +## The acceptable pause duration between heartbeats. +## Additional extra grace period to the learned mean interval before φ rises, absorbing temporary network hiccups or GC pauses. +acceptable_heartbeat_pause = "10000ms" + +## Datanode options. +[datanode] + +## Datanode client options. +[datanode.client] + +## Operation timeout. +timeout = "10s" + +## Connect server timeout. +connect_timeout = "10s" + +## `TCP_NODELAY` option for accepted connections. +tcp_nodelay = true + +[wal] +# Available wal providers: +# - `raft_engine` (default): there're none raft-engine wal config since metasrv only involves in remote wal currently. +# - `kafka`: metasrv **have to be** configured with kafka wal config when using kafka wal provider in datanode. +provider = "raft_engine" + +# Kafka wal config. + +## The broker endpoints of the Kafka cluster. +broker_endpoints = ["127.0.0.1:9092"] + +## Automatically create topics for WAL. +## Set to `true` to automatically create topics for WAL. +## Otherwise, use topics named `topic_name_prefix_[0..num_topics)` +auto_create_topics = true + +## Number of topics. +num_topics = 64 + +## Topic selector type. +## Available selector types: +## - `round_robin` (default) +selector_type = "round_robin" + +## A Kafka topic is constructed by concatenating `topic_name_prefix` and `topic_id`. +topic_name_prefix = "greptimedb_wal_topic" + +## Expected number of replicas of each partition. +replication_factor = 1 + +## Above which a topic creation operation will be cancelled. +create_topic_timeout = "30s" + +# The Kafka SASL configuration. +# **It's only used when the provider is `kafka`**. +# Available SASL mechanisms: +# - `PLAIN` +# - `SCRAM-SHA-256` +# - `SCRAM-SHA-512` +# [wal.sasl] +# type = "SCRAM-SHA-512" +# username = "user_kafka" +# password = "secret" + +# The Kafka TLS configuration. +# **It's only used when the provider is `kafka`**. +# [wal.tls] +# server_ca_cert_path = "/path/to/server_cert" +# client_cert_path = "/path/to/client_cert" +# client_key_path = "/path/to/key" + +``` + +| Key | Type | Default | Descriptions | +| --------------------------------------------- | ------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data_home` | String | `./greptimedb_data/metasrv/` | The working home directory. | +| `bind_addr` | String | `127.0.0.1:3002` | The bind address of metasrv. | +| `server_addr` | String | `127.0.0.1:3002` | The communication server address for frontend and datanode to connect to metasrv, "127.0.0.1:3002" by default for localhost. | +| `store_addrs` | Array | `["127.0.0.1:2379"]` | Store server address. Configure the address based on your backend type, for example:
- Use `"127.0.0.1:2379"` to connect to etcd
- Use `"password=password dbname=postgres user=postgres host=localhost port=5432"` to connect to postgres
- Use `"mysql://user:password@ip:port/dbname"` to connect to mysql | +| `selector` | String | `lease_based` | Datanode selector type.
- `lease_based` (default value).
- `load_based`
For details, see [Selector](/contributor-guide/metasrv/selector.md) | +| `use_memory_store` | Bool | `false` | Store data in memory. | +| `enable_region_failover` | Bool | `false` | Whether to enable region failover.
This feature is only available on GreptimeDB running on cluster mode and
- Using Remote WAL
- Using shared storage (e.g., s3). | +| `region_failure_detector_initialization_delay` | String | `10m` | The delay before starting region failure detection. This delay helps prevent Metasrv from triggering unnecessary region failovers before all Datanodes are fully started. Especially useful when the cluster is not deployed with GreptimeDB Operator and maintenance mode is not enabled. | +| `allow_region_failover_on_local_wal` | Bool | `false` | Whether to allow region failover on local WAL.
**This option is not recommended to be set to true, because it may lead to data loss during failover.** | +| `backend` | String | `etcd_store` | The datastore for metasrv.
- `etcd_store` (default)
- `memory_store` (In memory metadata storage - only used for testing.)
- `postgres_store`
- `mysql_store` | +| `meta_table_name` | String | `greptime_metakv` | Table name in RDS to store metadata. Effect when using a RDS kvbackend.
**Only used when backend is `postgres_store` or `mysql_store`.** | +| `meta_election_lock_id` | Integer | `1` | Advisory lock id in PostgreSQL for election. Effect when using PostgreSQL as kvbackend
**Only used when backend is `postgres_store`.** | +| `procedure` | -- | -- | Procedure storage options. | +| `procedure.max_retry_times` | Integer | `12` | Procedure max retry time. | +| `procedure.retry_delay` | String | `500ms` | Initial retry delay of procedures, increases exponentially | +| `procedure.max_running_procedures` | Integer | `128` | The maximum number of procedures that can be running at the same time. If the number of running procedures exceeds this limit, the procedure will be rejected. | +| `failure_detector` | -- | -- | -- | +| `failure_detector.threshold` | Float | `8.0` | Maximum acceptable φ before the peer is treated as failed.
Lower values react faster but yield more false positives. | +| `failure_detector.min_std_deviation` | String | `100ms` | The minimum standard deviation of the heartbeat intervals.
So tiny variations don't make φ explode. Prevents hypersensitivity when heartbeat intervals barely vary. | +| `failure_detector.acceptable_heartbeat_pause` | String | `10000ms` | The acceptable pause duration between heartbeats.
Additional extra grace period to the learned mean interval before φ rises, absorbing temporary network hiccups or GC pauses. | +| `datanode` | -- | -- | Datanode options. | +| `datanode.client` | -- | -- | Datanode client options. | +| `datanode.client.timeout` | String | `10s` | Operation timeout. | +| `datanode.client.connect_timeout` | String | `10s` | Connect server timeout. | +| `datanode.client.tcp_nodelay` | Bool | `true` | `TCP_NODELAY` option for accepted connections. | +| `wal` | -- | -- | -- | +| `wal.provider` | String | `raft_engine` | -- | +| `wal.broker_endpoints` | Array | -- | The broker endpoints of the Kafka cluster. | +| `wal.auto_prune_interval` | String | `0s` | Interval of automatically WAL pruning.
Set to `0s` to disable automatically WAL pruning which delete unused remote WAL entries periodically. | +| `wal.trigger_flush_threshold` | Integer | `0` | The threshold to trigger a flush operation of a region in automatically WAL pruning.
Metasrv will send a flush request to flush the region when:
`trigger_flush_threshold` + `prunable_entry_id` < `max_prunable_entry_id`
where:
- `prunable_entry_id` is the maximum entry id that can be pruned of the region. Entries before `prunable_entry_id` are not used by this region.
- `max_prunable_entry_id` is the maximum prunable entry id among all regions in the same topic. Entries before `max_prunable_entry_id` are not used by any region.
Set to `0` to disable the flush operation. | +| `wal.auto_prune_parallelism` | Integer | `10` | Concurrent task limit for automatically WAL pruning. Each task is responsible for WAL pruning for a kafka topic. | +| `wal.num_topics` | Integer | `64` | Number of topics. | +| `wal.selector_type` | String | `round_robin` | Topic selector type.
Available selector types:
- `round_robin` (default) | +| `wal.topic_name_prefix` | String | `greptimedb_wal_topic` | A Kafka topic is constructed by concatenating `topic_name_prefix` and `topic_id`. | +| `wal.replication_factor` | Integer | `1` | Expected number of replicas of each partition. | +| `wal.create_topic_timeout` | String | `30s` | Above which a topic creation operation will be cancelled. | +| `wal.sasl` | String | -- | The Kafka SASL configuration. | +| `wal.sasl.type` | String | -- | The SASL mechanisms, available values: `PLAIN`, `SCRAM-SHA-256`, `SCRAM-SHA-512`. | +| `wal.sasl.username` | String | -- | The SASL username. | +| `wal.sasl.password` | String | -- | The SASL password. | +| `wal.tls` | String | -- | The Kafka TLS configuration. | +| `wal.tls.server_ca_cert_path` | String | -- | The path of trusted server ca certs. | +| `wal.tls.client_cert_path` | String | -- | The path of client cert (Used for enable mTLS). | +| `wal.tls.client_key_path` | String | -- | The path of client key (Used for enable mTLS). | + +### Datanode-only configuration + +```toml +node_id = 42 +[grpc] +bind_addr = "127.0.0.1:3001" +server_addr = "127.0.0.1:3001" +runtime_size = 8 +``` + +| Key | Type | Description | +| ----------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| node_id | Integer | The datanode identifier, should be unique. | +| grpc.bind_addr | String | The address to bind the gRPC server, `"127.0.0.1:3001"` by default. | +| grpc.server_addr | String | The address advertised to the metasrv, and used for connections from outside the host. If left empty or unset, the server will automatically use the IP address of the first network interface on the host, with the same port number as the one specified in `grpc.bind_addr`. | +| grpc.runtime_size | Integer | The number of gRPC server worker threads, 8 by default. | + +### Frontend-only configuration + +```toml +[datanode] +[datanode.client] +connect_timeout = "1s" +tcp_nodelay = true +``` + +| Key | Type | Default | Description | +| --------------------------------- | ------ | ------- | ---------------------------------------------- | +| `datanode` | -- | -- | Datanode options. | +| `datanode.client` | -- | -- | Datanode client options. | +| `datanode.client.connect_timeout` | String | `1s` | Connect server timeout. | +| `datanode.client.tcp_nodelay` | Bool | `true` | `TCP_NODELAY` option for accepted connections. | diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/_pre_kind_helm.mdx b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/_pre_kind_helm.mdx new file mode 100644 index 0000000000..757d2e5ee5 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/_pre_kind_helm.mdx @@ -0,0 +1,80 @@ +## Prerequisites + +- [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 + +## Create a test Kubernetes cluster + +:::warning +Using `kind` is not recommended for production environments or performance testing. For such use cases, we recommend using cloud-managed Kubernetes services such as [Amazon EKS](https://aws.amazon.com/eks/), [Google GKE](https://cloud.google.com/kubernetes-engine/), or [Azure AKS](https://azure.microsoft.com/en-us/services/kubernetes-service/), or deploying your own production-grade Kubernetes cluster. +::: + +There are many ways to create a Kubernetes cluster for testing purposes. In this guide, we will use [kind](https://kind.sigs.k8s.io/docs/user/quick-start/) to create a local Kubernetes cluster. You can skip this step if you want to use the existing Kubernetes cluster. + +Here is an example using `kind` v0.20.0: + +```bash +kind create cluster +``` + +
+ Expected Output +```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! 😊 +``` +
+ +Check the status of the cluster: + +```bash +kubectl cluster-info +``` + +
+ Expected Output +```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'. +``` +
+ +## Add the Greptime Helm repository + +We provide the [official Helm repository](https://github.com/GreptimeTeam/helm-charts) for the GreptimeDB Operator and GreptimeDB cluster. You can add the repository by running the following command: + +```bash +helm repo add greptime https://greptimeteam.github.io/helm-charts/ +helm repo update +``` + +Check the charts in the Greptime Helm repository: + +``` +helm search repo greptime +``` + +
+ Expected Output +```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 +``` +
diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md new file mode 100644 index 0000000000..e936f9a0ec --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md @@ -0,0 +1,594 @@ +--- +keywords: [Kubernetes, Deployment, Helm Chart, Configuration] +description: Common Helm Chart Configurations +--- + +# Common Helm Chart Configurations + +For each Helm Chart, you can create a `values.yaml` file for configuration. When you need to apply configurations, you can use the `helm upgrade` command: + +``` +helm upgrade --install ${release-name} ${chart-name} --namespace ${namespace} -f values.yaml +``` + +## GreptimeDB Cluster Chart + +For complete configuration options, please refer to [GreptimeDB Cluster Chart](https://github.com/GreptimeTeam/helm-charts/tree/main/charts/greptimedb-cluster/README.md). + +### GreptimeDB Image Configuration + +The top-level variable `image` is used to configure the global GreptimeDB image for the cluster, as shown below: + +```yaml +image: + # -- The image registry + registry: docker.io + # -- The image repository + repository: greptime/greptimedb + # -- The image tag + tag: "VAR::greptimedbVersion" + # -- The image pull secrets + pullSecrets: [] +``` + +If you want to configure different images for each role in the cluster, you can use the `${role}.podTemplate.main.image` field (where `role` can be `meta`, `frontend`, `datanode` and `flownode`). This field will **override** the top-level `image` configuration, as shown below: + +```yaml +image: + # -- The image registry + registry: docker.io + # -- The image repository + repository: greptime/greptimedb + # -- The image tag + tag: "VAR::greptimedbVersion" + # -- The image pull secrets + pullSecrets: [] + +frontend: + podTemplate: + main: + image: "greptime/greptimedb:latest" +``` + +In this case, the `frontend` image will be set to `greptime/greptimedb:latest`, while other components will use the top-level `image` configuration. + +### Service Ports Configuration + +You can configure service ports using the following fields: + +- `httpServicePort`: Configures the HTTP service port, default `4000` +- `grpcServicePort`: Configures the SQL service port, default `4001` +- `mysqlServicePort`: Configures the MySQL service port, default `4002` +- `postgresServicePort`: Configures the PostgreSQL service port, default `4003` + +### Datanode Storage Configuration + +You can configure Datanode storage through the `datanode.storage` field, as shown below: + +```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`: Configures the StorageClass, defaults to Kubernetes current default StorageClass +- `storageSize`: Configures the storage size, default `10Gi`. You can use common capacity units, such as `10Gi`, `10GB`, etc. +- `storageRetainPolicy`: Configures the storage retention policy, default `Retain`. If set to `Delete`, the storage will be deleted when the cluster is deleted +- `dataHome`: Configures the data directory, default `/data/greptimedb/` + +### Resource Configuration + +The top-level variable `base.podTemplate.main.resources` is used to globally configure resources for each role, as shown below: + +```yaml +base: + podTemplate: + main: + resources: + requests: + memory: "1Gi" + cpu: "1" + limits: + memory: "2Gi" + cpu: "2" +``` + +If you want to configure different resources for each role in the cluster, you can use the `${role}.podTemplate.main.resources` field (where `role` can be `meta`, `frontend`, `datanode`, etc.). This field will **override** the top-level `base.podTemplate.main.resources` configuration, as shown below: + +```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 Replicas Configuration + +For different roles, the number of replicas can be configured through the `${role}.replicas` field, as shown below: + +```yaml +frontend: + replicas: 3 + +datanode: + replicas: 3 +``` + +You can achieve horizontal scaling by configuring the number of replicas. + +### Environment Variable Configuration + +You can configure global environment variables through the `base.podTemplate.main.env` field, and configure different environment variables for each Role through the `${role}.podTemplate.main.env` field, as shown below: + +```yaml +base: + podTemplate: + main: + env: + - name: GLOBAL_ENV + value: "global_value" + +frontend: + podTemplate: + main: + env: + - name: FRONTEND_ENV + value: "frontend_value" +``` + +### Injecting Configuration Files + +For different Role services, youcan inject custom TOML configuration files through the `${role}.configData` field, as shown below: + +```yaml +datanode: + configData: | + [[region_engine]] + [region_engine.mito] + # Number of region workers + num_workers = 8 +``` + +You can learn about GreptimeDB configuration options through [config.md](https://github.com/GreptimeTeam/greptimedb/blob/main/config/config.md). + +In addition to using the `${role}.configData` field to inject configuration files, you can also specify corresponding files through `${role}.configFile`, as shown below: + +```yaml +frontend: + configFile: "configs/frontend.toml" +``` + +In this case, ensure that the configuration file path matches the directory where the `helm upgrade` command is executed. + +:::note +User-injected configuration files have lower priority by default than configuration items managed by GreptimeDB Operator. Some configuration items can only be configured through GreptimeDB Operator, and these items are exposed by default in `values.yaml`. + +The following default configurations are managed by GreptimeDB Operator: + +- Logging configuration; +- Datanode's Node ID; +::: + +### Authentication Configuration + +The Helm Chart does not enable User Provider mode authentication by default. You can enable User Provider mode authentication and configure user information through the `auth.enabled` field, as shown below: + +```yaml +auth: + enabled: true + users: + - username: "admin" + password: "admin" +``` + +### Logging Configuration + +The top-level variable `logging` is used to configure global logging levels, as shown below: + +```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: [] +``` + +Where: + +- `logging.level`: Configures the global log level, supports `debug`, `info`, `warn`, `error`. +- `logging.format`: Configures the global log format, supports `json` and `text`. +- `logging.logsDir`: Configures the global log directory, default `/data/greptimedb/logs`. +- `logging.onlyLogToStdout`: Configures whether to output only to stdout, disabled by default. +- `logging.persistentWithData`: Configures whether to persist logs with data storage, only applies to the `datanode` component, disabled by default. +- `logging.filters`: Configures global log filters, supports the syntax `target[span\{field=value\}]=level`. For example, if you want to enable `debug` level logging for certain components: + + ```yaml + logging: + level: "info" + format: "json" + filters: + - mito2=debug + ``` + +Each role's logging configuration can be configured through the `${role}.logging` field, with fields consistent with the top-level `logging` and will **override** the top-level `logging` configuration, for example: + +```yaml +frontend: + logging: + level: "debug" +``` + +### Enabling Flownode + +The Helm Chart does not enable Flownode by default. You can enable Flownode through the `flownode.enabled` field, as shown below: + +```yaml +flownode: + enabled: true +``` + +Other fields of `flownode` are configured similarly to other Roles, for example: + +```yaml +flownode: + enabled: true + replicas: 1 + podTemplate: + main: + resources: + requests: + memory: "1Gi" + cpu: "1" + limits: + memory: "2Gi" + cpu: "2" +``` + +### Object Storage Configuration + +The `objectStorage` field is used to configure cloud object storage (such as AWS S3 and Azure Blob Storage, etc.) as the GreptimeDB storage layer. + +#### AWS S3 + +```yaml +objectStorage: + credentials: + # AWS access key ID + accessKeyId: "" + # AWS secret access key + secretAccessKey: "" + s3: + # AWS S3 bucket name + bucket: "" + # AWS S3 region + region: "" + # The root path in bucket is 's3:////data/...' + root: "" + # The AWS S3 endpoint, see more detail: https://docs.aws.amazon.com/general/latest/gr/s3.html + endpoint: "" +``` + +#### Google Cloud Storage + +```yaml +objectStorage: + credentials: + # GCP serviceAccountKey JSON-formatted base64 value + serviceAccountKey: "" + gcs: + # Google Cloud Storage bucket name + bucket: "" + # Google Cloud OAuth 2.0 Scopes, example: "https://www.googleapis.com/auth/devstorage.read_write" + scope: "" + # The root path in bucket is 'gcs:////data/...' + root: "" + # Google Cloud Storage endpoint, example: "https://storage.googleapis.com" + endpoint: "" +``` + +#### Azure Blob + +```yaml +objectStorage: + credentials: + # Azure account name + accountName: "" + # Azure account key + accountKey: "" + azblob: + # Azure Blob container name + container: "" + # The root path in container is 'blob:////data/...' + root: "" + # Azure Blob endpoint, see: "https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-query-endpoint-srp?tabs=dotnet#query-for-the-blob-storage-endpoint" + endpoint: "" +``` + +#### AliCloud OSS + +```yaml +objectStorage: + credentials: + # AliCloud access key ID + accessKeyId: "" + # AliCloud access key secret + accessKeySecret: "" + oss: + # AliCloud OSS bucket name + bucket: "" + # AliCloud OSS region + region: "" + # The root path in bucket is 'oss:////data/...' + root: "" + # The AliCloud OSS endpoint + endpoint: "" +``` + +#### Volcengine TOS + +TOS ([Torch Object Storage](https://www.volcengine.com/docs/6349)) is a massive, secure, cost-effective, user-friendly, highly reliable, and highly available object storage service provided by [Volcengine](https://www.volcengine.com). + +```yaml +objectStorage: + credentials: + # Volcengine access key ID + accessKeyId: "" + # Volcengine secret access key + secretAccessKey: "" + s3: + # Volcengine TOS bucket name + bucket: "" + # Volcengine TOS region + region: "" + # The root path in bucket is 'tos:////data/...' + root: "" + # The Volcengine TOS endpoint, see more detail: https://www.volcengine.com/docs/6349/107356 + endpoint: "" + # Enable virtual host style so that OpenDAL will send API requests in virtual host style instead of path style. + enableVirtualHostStyle: true +``` + +### Prometheus Monitor Configuration + +If you have [prometheus-operator](https://github.com/prometheus-operator/prometheus-operator) installed, you can create Prometheus PodMonitor to monitor GreptimeDB through the `prometheusMonitor.enabled` field as follows: + +```yaml +prometheusMonitor: + # -- Create PodMonitor resource for scraping metrics using PrometheusOperator + enabled: false + # -- Interval at which metrics should be scraped + interval: "30s" + # -- Add labels to the PodMonitor + labels: + release: prometheus +``` + +### Debug Pod Configuration + +The debug pod has various tools installed (such as mysql-client, psql-client, etc.). You can exec into the debug pod for debugging. Create it with the `debugPod.enabled` field as follows: + +```yaml +debugPod: + # -- Enable debug pod + enabled: false + + # -- The debug pod image + image: + registry: docker.io + repository: greptime/greptime-tool + tag: "VAR::debugPodVersion" + + # -- The debug pod resource + resources: + requests: + memory: 64Mi + cpu: 50m + limits: + memory: 256Mi + cpu: 200m +``` + +### Configuring Metasrv Backend Storage + +#### Using MySQL and PostgreSQL as Backend Storage + +You can configure the backend storage for the metasrv through the `meta.backendStorage` field. + +Let's take MySQL as an example. + +```yaml +meta: + backendStorage: + mysql: + # -- MySQL host + host: "mysql.default.svc.cluster.local" + # -- MySQL port + port: 3306 + # -- MySQL database + database: "metasrv" + # -- MySQL table + table: "greptime_metakv" + # -- MySQL credentials + credentials: + # -- MySQL credentials secret name + secretName: "meta-mysql-credentials" + # -- MySQL credentials existing secret name + existingSecretName: "" + # -- MySQL credentials username + username: "root" + # -- MySQL credentials password + password: "test" +``` + +- `mysql.host`: The MySQL host. +- `mysql.port`: The MySQL port. +- `mysql.database`: The MySQL database. +- `mysql.table`: The MySQL table. +- `mysql.credentials.secretName`: The MySQL credentials secret name. +- `mysql.credentials.existingSecretName`: The MySQL credentials existing secret name. If you want to use an existing secret, you should make sure the secret contains the following keys: `username` and `password`. +- `mysql.credentials.username`: The MySQL credentials username. It will be ignored if `mysql.credentials.existingSecretName` is set. The `username` will be stored in the `username` key of the secret with `mysql.credentials.secretName`. +- `mysql.credentials.password`: The MySQL credentials password. It will be ignored if `mysql.credentials.existingSecretName` is set. The `password` will be stored in the `password` key of the secret with `mysql.credentials.secretName`. + +Most of the fields of `meta.backendStorage.postgresql` are the same as the fields of `meta.backendStorage.mysql`. For example: + +```yaml +meta: + backendStorage: + postgresql: + # -- PostgreSQL host + host: "postgres.default.svc.cluster.local" + # -- PostgreSQL port + port: 5432 + # -- PostgreSQL database + database: "metasrv" + # -- PostgreSQL table + table: "greptime_metakv" + # -- PostgreSQL Advisory lock id used for election, shouldn't be used in other clusters or applications. + electionLockID: 1 + # -- PostgreSQL credentials + credentials: + # -- PostgreSQL credentials secret name + secretName: "meta-postgresql-credentials" + # -- PostgreSQL credentials existing secret name + existingSecretName: "" + # -- PostgreSQL credentials username + username: "root" + # -- PostgreSQL credentials password + password: "root" +``` + +- `postgresql.host`: The PostgreSQL host. +- `postgresql.port`: The PostgreSQL port. +- `postgresql.database`: The PostgreSQL database. +- `postgresql.table`: The PostgreSQL table. +- `postgresql.electionLockID`: The Advisory lock id in PostgreSQL for election. +- `postgresql.credentials.secretName`: The PostgreSQL credentials secret name. +- `postgresql.credentials.existingSecretName`: The PostgreSQL credentials existing secret name. If you want to use an existing secret, you should make sure the secret contains the following keys: `username` and `password`. +- `postgresql.credentials.username`: The PostgreSQL credentials username. It will be ignored if `mysql.credentials.existingSecretName` is set. The `username` will be stored in the `username` key of the secret with `mysql.credentials.secretName`. +- `postgresql.credentials.password`: The PostgreSQL credentials password. It will be ignored if `mysql.credentials.existingSecretName` is set. The `password` will be stored in the `password` key of the secret with `mysql.credentials.secretName`. + +#### Using etcd as Backend Storage + +:::tip NOTE +The configuration structure has changed between chart versions: + +- In older version: `meta.etcdEndpoints` +- In newer version: `meta.backendStorage.etcd.endpoints` + +Always refer to the latest [values.yaml](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-cluster/values.yaml) in the Helm chart repository for the most up-to-date configuration structure. +::: + +The etcd backend storage can be configured through the `meta.backendStorage.etcd` field. + +```yaml +meta: + backendStorage: + etcd: + # -- Etcd endpoints + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + # -- Etcd store key prefix + storeKeyPrefix: "" +``` + +- `etcd.endpoints`: The etcd endpoints. +- `etcd.storeKeyPrefix`: The etcd store key prefix. All keys will be stored with this prefix. If you want to use one etcd cluster for multiple GreptimeDB clusters, you can configure different store key prefixes for each GreptimeDB cluster. It's only for testing and debugging purposes. + +### Enable Region Failover + +You can enable Region Failover through the `meta.enableRegionFailover` field. Before enabling Region Failover, ensure your deployment meets the prerequisites outlined in the [Region Failover](/user-guide/deployments-administration/manage-data/region-failover.md) documentation. If your configuration does not meet the prerequisites, the **Operator will fail to deploy the cluster components**. + +```yaml +meta: + enableRegionFailover: true +``` + +#### Enable Region Failover on Local WAL + +To enable Region Failover on local WAL, you need to set both `meta.enableRegionFailover: true` and add `allow_region_failover_on_local_wal = true` in the `meta.configData` field. + +:::warning WARNING +Enabling Region Failover on local WAL may lead to data loss during failover. Ensure your operator version is greater than or equal to v0.2.2. +::: + +```yaml +meta: + enableRegionFailover: true + configData: | + allow_region_failover_on_local_wal = true + +``` + +### Dedicated WAL Volume + +Configuring a dedicated WAL volume allows you to use a separate disk with a custom `StorageClass` for the WAL directory when deploying a GreptimeDB Datanode. + +```yaml +dedicatedWAL: + enabled: true + raftEngine: + fs: + storageClassName: io2 # Use aws ebs io2 storage class for WAL for better performance. + name: wal + storageSize: 20Gi + mountPath: /wal +``` + +### Enable Remote WAL + +To enable Remote WAL, both Metasrv and Datanode must be properly configured. Before proceeding, make sure to read the [Remote WAL Configuration](/user-guide/deployments-administration/wal/remote-wal/configuration.md) documentation for a complete overview of configuration options and important considerations. + +```yaml +remoteWal: + enabled: true + kafka: + brokerEndpoints: ["kafka.kafka-cluster.svc:9092"] +meta: + configData: | + [wal] + provider = "kafka" + replication_factor = 1 + auto_prune_interval = "30m" +datanode: + configData: | + [wal] + provider = "kafka" + overwrite_entry_start_id = true +``` diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-frontend-groups.md b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-frontend-groups.md new file mode 100644 index 0000000000..c358a1aea5 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-frontend-groups.md @@ -0,0 +1,109 @@ +--- +keywords: [Kubernetes, deployment, GreptimeDB, frontend groups, CRD, installation, verification] +description: Step-by-step guide to deploying a GreptimeDB cluster with frontend groups on Kubernetes, including prerequisites, configuration, installation, and verification. +--- + +# Deploying a GreptimeDB Cluster with Frontend Groups + +In this guide, you will learn how to deploy a GreptimeDB cluster on Kubernetes with a frontend group consisting of multiple frontend instances. + +## Prerequisites + +- [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 +- [GreptimeDB Operator](https://github.com/GrepTimeTeam/greptimedb-operator) >= v0.3.0 +- [ETCD](https://github.com/bitnami/charts/tree/main/bitnami/etcd) + +## Upgrade operator + +Install the GreptimeDB Operator, setting the image version to be greater than or equal to `v0.3.0`. +For detailed instructions on upgrading the operator, please refer to the [GreptimeDB Operator Management](/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md#upgrade) guide. + +## Frontend Groups Configuration + +:::tip NOTE +The configuration structure has changed between chart versions: + +- In older version: `meta.etcdEndpoints` +- In newer version: `meta.backendStorage.etcd.endpoints` + +Always refer to the latest [values.yaml](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-cluster/values.yaml) in the Helm chart repository for the most up-to-date configuration structure. +::: + +When configuring frontend groups, ensure that each group includes a `name` field. The following `values.yaml` example demonstrates how to define separate frontend groups for read and write operations: + +```yaml +frontend: + enabled: false # Disable default frontend group + +frontendGroups: + - name: read + replicas: 1 + config: | + default_timezone = "UTC" + [http] + timeout = "60s" + template: + main: + resources: + limits: + cpu: 2000m + memory: 2048Mi + - name: write + replicas: 1 + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: + - "etcd.etcd-cluster.svc.cluster.local:2379" + +datanode: + replicas: 1 +``` + +You can use the following command to apply the configuration: +``` +helm upgrade --install ${release-name} greptime/greptimedb-cluster --namespace ${namespace} -f values.yaml +``` + +## Validity + +When setting the frontend groups, the name must be set. + +```yaml +frontendGroups: + # - name: read #<=========The name must be set=============> + - replicas: 1 +``` + +## Verify the Installation + +Check the status of the pods: + +```bash +kubectl get pods -n default +NAME READY STATUS RESTARTS AGE +greptimedb-datanode-0 1/1 Running 0 27s +greptimedb-frontend-read-66bf68bd5c-8kg8g 1/1 Running 0 21s +greptimedb-frontend-read-66bf68bd5c-x752l 1/1 Running 0 21s +greptimedb-frontend-write-bdd944b97-pkf9d 1/1 Running 0 21s +greptimedb-meta-699f74cd9d-42w2c 1/1 Running 0 87s +``` + +To check the services: + +```bash +kubectl get service -n default +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +greptimedb-datanode ClusterIP None 4001/TCP,4000/TCP 102s +greptimedb-frontend-read ClusterIP 10.96.174.200 4001/TCP,4000/TCP,4002/TCP,4003/TCP 42s +greptimedb-frontend-write ClusterIP 10.96.223.1 4001/TCP,4000/TCP,4002/TCP,4003/TCP 42s +greptimedb-meta ClusterIP 10.96.195.163 3002/TCP,4000/TCP 3m4s +``` + +## Conclusion + +You have successfully deployed a GreptimeDB cluster with a frontend group consisting of read and write instances. You can now proceed to explore the functionality of your GreptimeDB cluster or integrate it with additional tools as needed. diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-remote-wal.md b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-remote-wal.md new file mode 100644 index 0000000000..e23cb6f13f --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/configure-remote-wal.md @@ -0,0 +1,83 @@ +--- +keywords: [Kubernetes, deployment, GreptimeDB, Remote WAL, Kafka, configuration] +description: Step-by-step guide to deploying GreptimeDB with Remote WAL on Kubernetes, including prerequisites, configuration, installation, and verification. +--- + +# Deploying GreptimeDB Cluster with Remote WAL + +In this guide, you will learn how to deploy GreptimeDB with Remote WAL on Kubernetes. Before you start, it's recommended to read the [Deploy GreptimeDB Cluster](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md) guide first. + +## Prerequisites + +- [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 + +## Dependencies + +Before deploying a GreptimeDB cluster with Remote WAL, ensure that the metadata storage and Kafka cluster are properly set up or that existing instances are available. + +- Metadata storage: you can refer to [Manage Metadata Overview](/user-guide/deployments-administration/manage-metadata/overview.md) for more details. In this example, we use etcd as the metadata storage. +- Kafka Cluster: you can refer to [Manage Kafka](/user-guide/deployments-administration/wal/remote-wal/manage-kafka.md) for more details. + +## Remote WAL Configuration + +:::tip NOTE +The configuration structure has changed between chart versions: + +- In older version: `meta.etcdEndpoints` +- In newer version: `meta.backendStorage.etcd.endpoints` + +Always refer to the latest [values.yaml](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-cluster/values.yaml) in the Helm chart repository for the most up-to-date configuration structure. +::: + +This example assumes you have a Kafka cluster running in the `kafka-cluster` namespace, and an etcd cluster running in the `etcd-cluster` namespace. The `values.yaml` file is as follows: + +```yaml +meta: + backendStorage: + etcd: + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + configData: | + [wal] + provider = "kafka" + replication_factor = 1 + topic_name_prefix = "gtp_greptimedb_wal_topic" + auto_prune_interval = "30m" +datanode: + configData: | + [wal] + provider = "kafka" + overwrite_entry_start_id = true +remoteWal: + enabled: true + kafka: + brokerEndpoints: ["kafka.kafka-cluster.svc.cluster.local:9092"] +``` + +## Deploy GreptimeDB Cluster + +You can deploy the GreptimeDB cluster with the following command: + +```bash +helm upgrade --install mycluster \ + --values values.yaml \ + greptime/greptimedb-cluster \ + -n default +``` + +## Best Practices + +- **Avoid switching WAL storage options in an existing cluster**. If you need to change the WAL storage backend (e.g., from local to remote), you must **tear down the entire cluster** and perform a clean redeployment. This includes deleting: + - All PersistentVolumeClaims (PVCs) used by the GreptimeDB cluster. + - The object storage directory used by the cluster. + - The metadata storage associated with the cluster. +- Use a **minimal viable setup (MVP) to verify the cluster is functioning correctly**. This includes basic operations such as creating tables and inserting data to ensure the database works as expected. + + +## Next Steps + +- Follow the [Deploy GreptimeDB Cluster](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md) guide to access your GreptimeDB cluster. +- Follow the [Quick Start](/getting-started/quick-start.md) guide to create tables and insert data. +- For more information about Remote WAL configuration, see [Remote WAL Configuration](/user-guide/deployments-administration/wal/remote-wal/configuration.md). + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md new file mode 100644 index 0000000000..4a09bf5e66 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md @@ -0,0 +1,402 @@ +--- +keywords: [Kubernetes, deployment, getting started, GreptimeDB Operator, prerequisites, cluster creation, installation, verification] +description: Step-by-step guide to deploying a GreptimeDB cluster on Kubernetes using the GreptimeDB Operator, including prerequisites, cluster creation, installation, and verification. +--- + +# Deploy GreptimeDB Cluster + +In this guide, you will learn how to deploy a GreptimeDB cluster on Kubernetes using the GreptimeDB Operator. + +:::note +The following output may have minor differences depending on the versions of the Helm charts and environment. +::: + +import PreKindHelm from './_pre_kind_helm.mdx'; + + + +## Install and verify the GreptimeDB Operator + +It's ready to use Helm to install the GreptimeDB Operator on the Kubernetes cluster. + +### Install the GreptimeDB Operator + +The [GreptimeDB Operator](https://github.com/GrepTimeTeam/greptimedb-operator) is a Kubernetes operator that manages the lifecycle of GreptimeDB cluster. + +Let's install the latest version of the GreptimeDB Operator in the `greptimedb-admin` namespace: + +```bash +helm install greptimedb-operator greptime/greptimedb-operator -n greptimedb-admin --create-namespace +``` + +
+ Expected Output +```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 +There is another way to install the GreptimeDB Operator by using `kubectl` and `bundle.yaml` from the latest release: + +```bash +kubectl apply -f \ + https://github.com/GreptimeTeam/greptimedb-operator/releases/latest/download/bundle.yaml \ + --server-side +``` + +This method is only suitable for quickly deploying GreptimeDB Operator in the test environments and is not recommended for production use. +::: + +### Verify the GreptimeDB Operator installation + +Check the status of the GreptimeDB Operator: + +```bash +kubectl get pods -n greptimedb-admin -l app.kubernetes.io/instance=greptimedb-operator +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +greptimedb-operator-68d684c6cf-qr4q4 1/1 Running 0 4m8s +``` +
+ +You also can check the CRD installation: + +```bash +kubectl get crds | grep greptime +``` + +
+ Expected Output +```bash +greptimedbclusters.greptime.io 2024-10-28T08:46:27Z +greptimedbstandalones.greptime.io 2024-10-28T08:46:27Z +``` +
+ +The GreptimeDB Operator will use `greptimedbclusters.greptime.io` and `greptimedbstandalones.greptime.io` CRDs to manage GreptimeDB cluster and standalone resources. + +## Install the etcd cluster + +The GreptimeDB cluster requires an etcd cluster for metadata storage. Let's install an etcd cluster using Bitnami's etcd Helm [chart](https://github.com/bitnami/charts/tree/main/bitnami/etcd). + +```bash +helm install etcd \ + oci://registry-1.docker.io/bitnamicharts/etcd \ + --version VAR::etcdChartVersion \ + --set replicaCount=3 \ + --set auth.rbac.create=false \ + --set auth.rbac.token.enabled=false \ + --create-namespace \ + --set global.security.allowInsecureImages=true \ + --set image.registry=docker.io \ + --set image.repository=greptime/etcd \ + --set image.tag=VAR::etcdImageVersion \ + -n etcd-cluster +``` + +
+ Expected Output +```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 greptime/etcd:VAR::etcdImageVersion --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/ +``` +
+ +Wait for the etcd cluster to be ready: + +```bash +kubectl get pods -n etcd-cluster -l app.kubernetes.io/instance=etcd +``` + +
+ Expected Output +```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 +``` +
+ +You can test the etcd cluster by running the following command: + +```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 +``` + +
+ Expected Output +```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 +``` +
+ +## Setup `values.yaml` + +The `values.yaml` file contains parameters and configurations for GreptimeDB and is the key to defining the Helm chart. +For example, a minimal GreptimeDB cluster configuration is as follows: + +```yaml +image: + registry: docker.io + # Image repository: + # Use `greptime/greptimedb` for OSS GreptimeDB, + # consult staff for Enterprise GreptimeDB + repository: + # Image tag: + # use database version for OSS GreptimeDB, for example, `VAR::greptimedbVersion` + # consult staff for Enterprise GreptimeDB + tag: + pullSecrets: [] + +initializer: + registry: docker.io + repository: greptime/greptimedb-initializer + +frontend: + replicas: 1 + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + +datanode: + replicas: 1 +``` + +The configuration above for the GreptimeDB cluster is not recommended for production use. +You should adjust the configuration according to your requirements. +You can refer to the [configuration documentation](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md) for the complete `values.yaml` configuration options. + + +## Install the GreptimeDB cluster + +Now that the GreptimeDB Operator and etcd cluster are installed, +and `values.yaml` is configured, +you can deploy a minimal GreptimeDB cluster: + +```bash +helm upgrade --install mycluster \ + greptime/greptimedb-cluster \ + --values /path/to/values.yaml \ + -n default +``` + +
+ Expected Output +```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. +``` +
+ +When starting the cluster installation, we can check the status of the GreptimeDB cluster with the following command. If you use a different cluster name and namespace, you can replace `mycluster` and `default` with your configuration: + +```bash +kubectl -n default get greptimedbclusters.greptime.io mycluster +``` + +
+ Expected Output +```bash +NAME FRONTEND DATANODE META FLOWNODE PHASE VERSION AGE +mycluster 1 1 1 0 Running v0.9.5 5m12s +``` +
+ +The above command will show the status of the GreptimeDB cluster. When the `PHASE` is `Running`, it means the GreptimeDB cluster has been successfully started. + +You also can check the Pods status of the GreptimeDB cluster: + +```bash +kubectl -n default get pods +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +mycluster-datanode-0 2/2 Running 0 77s +mycluster-frontend-6ffdd549b-9s7gx 2/2 Running 0 66s +mycluster-meta-58bc88b597-ppzvj 2/2 Running 0 86s +``` +
+ +As you can see, we have created a minimal GreptimeDB cluster consisting of 1 frontend, 1 datanode, and 1 metasrv by default. For information about the components of a complete GreptimeDB cluster, you can refer to [architecture](/user-guide/concepts/architecture.md). + +## Explore the GreptimeDB cluster + +:::warning +For production use, you should access the GreptimeDB cluster or Grafana inside the Kubernetes cluster or using the LoadBalancer type service. +::: + +### Access the GreptimeDB cluster + +You can access the GreptimeDB cluster by using `kubectl port-forward` the frontend service: + +```bash +kubectl -n default port-forward svc/mycluster-frontend 4000:4000 4001:4001 4002:4002 4003:4003 +``` + +
+ Expected Output +```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 +``` +
+ +Please note that when you use a different cluster name and namespace, you can use the following command, and replace `${cluster}` and `${namespace}` with your configuration: + +```bash +kubectl -n ${namespace} port-forward svc/${cluster}-frontend 4000:4000 4001:4001 4002:4002 4003:4003 +``` + +:::warning +If you want to expose the service to the public, you can use the `kubectl port-forward` command with the `--address` option: + +```bash +kubectl -n default port-forward --address 0.0.0.0 svc/mycluster-frontend 4000:4000 4001:4001 4002:4002 4003:4003 +``` + +Please make sure you have the proper security settings in place before exposing the service to the public. +::: + +Open the browser and navigate to `http://localhost:4000/dashboard` to access by the [GreptimeDB Dashboard](https://github.com/GrepTimeTeam/dashboard). + +If you want to use other tools like `mysql` or `psql` to connect to the GreptimeDB cluster, you can refer to the [Quick Start](/getting-started/quick-start.md). + +## Cleanup + +:::danger +The cleanup operation will remove the metadata and data of the GreptimeDB cluster. Please make sure you have backed up the data before proceeding. +::: + +### Stop the port-forwarding + +Stop the port-forwarding for the GreptimeDB cluster: + +```bash +pkill -f kubectl port-forward +``` + +### Uninstall the GreptimeDB cluster + +To uninstall the GreptimeDB cluster, you can use the following command: + +```bash +helm -n default uninstall mycluster +``` + +### Delete the PVCs + +The PVCs wouldn't be deleted by default for safety reasons. If you want to delete the PV data, you can use the following command: + +```bash +kubectl -n default delete pvc -l app.greptime.io/component=mycluster-datanode +``` + +### Cleanup the etcd cluster + +You can use the following command to clean up the etcd cluster: + +```bash +kubectl -n etcd-cluster exec etcd-0 -- etcdctl del "" --from-key=true +``` + +### Destroy the Kubernetes cluster + +If you are using `kind` to create the Kubernetes cluster, you can use the following command to destroy the cluster: + +```bash +kind delete cluster +``` + +## Next Steps + +If you want to deploy a GreptimeDB cluster with Remote WAL, you can refer to [Configure Remote WAL](/user-guide/deployments-administration/deploy-on-kubernetes/configure-remote-wal.md) for more details. + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-standalone.md b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-standalone.md new file mode 100644 index 0000000000..e310449250 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-standalone.md @@ -0,0 +1,204 @@ +--- +keywords: [Kubernetes, deployment, getting started, prerequisites, installation] +description: Step-by-step guide to deploying a GreptimeDB standalone on Kubernetes. +--- + +# Deploy GreptimeDB Standalone + +In this guide, you will learn how to deploy a GreptimeDB standalone on Kubernetes. + +:::note +The following output may have minor differences depending on the versions of the Helm charts and environment. +::: + +import PreKindHelm from './_pre_kind_helm.mdx'; + + + +## Install the GreptimeDB Standalone + +### Basic Installation + +For a quick start with default configuration: + +```bash +helm upgrade --install greptimedb-standalone greptime/greptimedb-standalone -n default +``` + +
+ Expected Output +```bash +Release "greptimedb-standalone" does not exist. Installing it now. +NAME: greptimedb-standalone +LAST DEPLOYED: Mon May 26 08:06:54 2025 +NAMESPACE: default +STATUS: deployed +REVISION: 1 +TEST SUITE: None +NOTES: +*********************************************************************** + Welcome to use greptimedb-standalone + Chart version: 0.1.53 + GreptimeDB Standalone version: 0.14.3 +*********************************************************************** + +Installed components: +* greptimedb-standalone + +The greptimedb-standalone is starting, use `kubectl get statefulset greptimedb-standalone -n default` to check its status. +``` +
+ +```bash +kubectl get pod -n default +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +greptimedb-standalone-0 1/1 Running 0 40s +``` +
+ +### Customized Installation + +For production or customized deployments, create a `values.yaml` file: + +```yaml +resources: + requests: + cpu: "2" + memory: "4Gi" + limits: + cpu: "4" + memory: "8Gi" +``` + +For more configuration options, please refer to the [documentation](https://github.com/GreptimeTeam/helm-charts/tree/main/charts/greptimedb-standalone). + +Then install with custom values: + +```bash +helm upgrade --install greptimedb-standalone greptime/greptimedb-standalone \ + --values values.yaml \ + --namespace default +``` + +
+ Expected Output +```bash +Release "greptimedb-standalone" has been upgraded. Happy Helming! +NAME: greptimedb-standalone +LAST DEPLOYED: Mon May 26 08:18:27 2025 +NAMESPACE: default +STATUS: deployed +REVISION: 2 +TEST SUITE: None +NOTES: +*********************************************************************** + Welcome to use greptimedb-standalone + Chart version: 0.1.53 + GreptimeDB Standalone version: 0.14.3 +*********************************************************************** + +Installed components: +* greptimedb-standalone + +The greptimedb-standalone is starting, use `kubectl get statefulset greptimedb-standalone -n default` to check its status. +``` +
+ +```bash +kubectl get pod -n default +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +greptimedb-standalone-0 1/1 Running 0 3s +``` +
+ +## Access GreptimeDB + +After installation, you can access GreptimeDB through: + +### MySQL Protocol + +```bash +kubectl port-forward svc/greptimedb-standalone 4002:4002 -n default > connections.out & +``` + +```bash +mysql -h 127.0.0.1 -P 4002 +``` + +
+ Expected Output +```bash +Welcome to the MariaDB monitor. Commands end with ; or \g. +Your MySQL connection id is 8 +Server version: 8.4.2 Greptime + +Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. + +Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. + +MySQL [(none)]> +``` +
+ +### PostgreSQL Protocol + +```bash +kubectl port-forward svc/greptimedb-standalone 4003:4003 -n default > connections.out & +``` + +```bash +psql -h 127.0.0.1 -p 4003 -d public +``` + +
+ Expected Output +```bash +psql (15.12, server 16.3-greptimedb-0.14.3) +WARNING: psql major version 15, server major version 16. + Some psql features might not work. +Type "help" for help. + +public=> +``` +
+ +### HTTP API + +```bash +kubectl port-forward svc/greptimedb-standalone 4000:4000 -n default > connections.out & +``` + +```bash +curl -X POST \ + -d 'sql=show tables' \ + http://localhost:4000/v1/sql +``` + +
+ Expected Output +```bash +{"output":[{"records":{"schema":{"column_schemas":[{"name":"Tables","data_type":"String"}]},"rows":[["numbers"]],"total_rows":1}}],"execution_time_ms":5}[root +``` +
+ +## Uninstallation + +To remove GreptimeDB standalone: + +```bash +helm uninstall greptimedb-standalone -n default +``` + +```bash +kubectl delete pvc -l app.kubernetes.io/instance=greptimedb-standalone -n default +``` diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md new file mode 100644 index 0000000000..dc674dbd5c --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management.md @@ -0,0 +1,225 @@ +--- +keywords: [Kubernetes, GreptimeDB Operator, management, installation, upgrade, configuration, Helm] +description: Guide to managing the GreptimeDB Operator on Kubernetes, including installation, upgrade, configuration, and uninstallation using Helm. +--- + +# GreptimeDB Operator Management + +The GreptimeDB Operator manages the [GreptimeDB](https://github.com/GrepTimeTeam/greptimedb) resources on [Kubernetes](https://kubernetes.io/) using the [Operator pattern](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/). + +It is like an autopilot that automates the deployment, provisioning, and orchestration of the GreptimeDB cluster and standalone. + +The GreptimeDB Operator includes, but is not limited to, the following features: + +- **Automated Provisioning**: Automates the deployment of the GreptimeDB cluster and standalone on Kubernetes by providing CRD `GreptimeDBCluster` and `GreptimeDBStandalone`. + +- **Multi-Cloud Support**: Users can deploy the GreptimeDB on any Kubernetes cluster, including on-premises and cloud environments(like AWS, GCP, Aliyun, etc.). + +- **Scaling**: Scale the GreptimeDB cluster as easily as changing the `replicas` field in the `GreptimeDBCluster` CR. + +- **Monitoring Bootstrap**: Bootstrap the GreptimeDB monitoring stack for the GreptimeDB cluster by providing the `monitoring` field in the `GreptimeDBCluster` CR. + +This document will show you how to install, upgrade, configure, and uninstall the GreptimeDB Operator on Kubernetes. + +:::note +The following output may have minor differences depending on the versions of the Helm charts and environment. +::: + +## Prerequisites + +- 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 + +## Production Deployment + +For production deployments, it's recommended to use Helm to install the GreptimeDB Operator. + +### Installation + +You can refer [Install and verify the GreptimeDB Operator](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md#install-and-verify-the-greptimedb-operator) for detailed instructions. + +:::note +If you are using [Argo CD](https://argo-cd.readthedocs.io/en/stable/) to deploy applications, please make sure that the `Application` has set the [`ServerSideApply=true`](https://argo-cd.readthedocs.io/en/latest/user-guide/sync-options/#server-side-apply) to enable the server-side apply (other GitOps tools may have similar settings). +::: + +### Upgrade + +We always publish the latest version of the GreptimeDB Operator as a Helm chart in our official Helm repository. + +When the new version of the GreptimeDB Operator is released, you can upgrade the GreptimeDB Operator by running the following commands. + +#### Update the Helm repository + +```bash +helm repo update greptime +``` + +
+Expected Output +```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!⎈ +``` +
+ +You can use the following command to search the latest version of the GreptimeDB Operator: + +```bash +helm search repo greptime/greptimedb-operator +``` + +
+Expected Output +```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. +``` +
+ +You also can use the following command to list all the available versions: + +```bash +helm search repo greptime/greptimedb-operator --versions +``` + +#### Upgrade the GreptimeDB Operator + +You can upgrade to the latest released version of the GreptimeDB Operator by running the following command: + +```bash +helm -n greptimedb-admin upgrade greptimedb-operator greptime/greptimedb-operator +``` + +
+Expected Output +```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. +``` +
+ +If you want to upgrade to a specific version, you can use the following command: + +```bash +helm -n greptimedb-admin upgrade greptimedb-operator greptime/greptimedb-operator --version +``` + +After the upgrade is complete, you can use the following command to verify the installation: + +```bash +helm list -n greptimedb-admin +``` + +
+Expected Output +```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 + +There are two kinds of CRD that are installed with the GreptimeDB Operator: `GreptimeDBCluster` and `GreptimeDBStandalone`. + +You can use the following command to verify the installation: + +```bash +kubectl get crd | grep greptime +``` + +
+ Expected Output +```bash +greptimedbclusters.greptime.io 2024-10-28T08:46:27Z +greptimedbstandalones.greptime.io 2024-10-28T08:46:27Z +``` +
+ +By default, the GreptimeDB Operator chart will manage the installation and upgrade of the CRDs and the users don't need to manage them manually. If you want to know the specific definitions of these two types of CRD, you can refer to the GreptimeDB Operator [API documentation](https://github.com/GreptimeTeam/greptimedb-operator/blob/main/docs/api-references/docs.md). + +### Configuration + +The GreptimeDB Operator chart provides a set of configuration options that allow you to customize the installation, you can refer to the [GreptimeDB Operator Helm Chart](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-operator/README.md##values) for more details. + +You can create a `values.yaml` to configure the GreptimeDB Operator chart (the complete configuration of `values.yaml` can be found in the [chart](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-operator/values.yaml)), for example: + +```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 +``` + +You can use the following command to install the GreptimeDB Operator with the custom configuration: + +```bash +helm -n greptimedb-admin install greptimedb-operator greptime/greptimedb-operator -f values.yaml +``` + +If you want to upgrade the GreptimeDB Operator with the custom configuration, you can use the following command: + +```bash +helm -n greptimedb-admin upgrade greptimedb-operator greptime/greptimedb-operator -f values.yaml +``` + +You also can use one command to install or upgrade the GreptimeDB Operator with the custom configuration: + +```bash +helm -n greptimedb-admin upgrade --install greptimedb-operator greptime/greptimedb-operator -f values.yaml +``` + +### Uninstallation + +You can use the `helm` command to uninstall the GreptimeDB Operator: + +```bash +helm -n greptimedb-admin uninstall greptimedb-operator +``` + +We don't delete the CRDs by default when you uninstall the GreptimeDB Operator. + +:::danger +If you really want to delete the CRDs, you can use the following command: + +```bash +kubectl delete crd greptimedbclusters.greptime.io greptimedbstandalones.greptime.io +``` + +The related resources will be removed after you delete the CRDs. +::: diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/overview.md b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/overview.md new file mode 100644 index 0000000000..befd0261a6 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/deploy-on-kubernetes/overview.md @@ -0,0 +1,44 @@ +--- +keywords: [Kubernetes, deployment, GreptimeDB Operator, setup, provisioning, management] +description: Overview of deploying GreptimeDB on Kubernetes using the GreptimeDB Operator, including setup, provisioning, and management of clusters and standalone instances. +--- + +# Deploy GreptimeDB on Kubernetes + +GreptimeDB is designed for cloud-native environments and supports Kubernetes deployment from day one. +You can deploy GreptimeDB on any cloud service provider, including AWS, Alibaba Cloud, or Google Cloud. + +## Deploy GreptimeDB Standalone + +For development, testing, or small-scale production use cases, you can [deploy a standalone GreptimeDB instance](deploy-greptimedb-standalone.md) on Kubernetes. +This provides a simple way to get started with GreptimeDB without the complexity of managing a full cluster. + +## Deploy GreptimeDB Cluster + +For production environments requiring high availability and scalability, +you can [deploy a GreptimeDB cluster](deploy-greptimedb-cluster.md) using the GreptimeDB Operator on Kubernetes. +This enables you to set up a distributed GreptimeDB cluster that scales horizontally and efficiently handles large volumes of data. + +## Configurations + +You can apply custom configurations to GreptimeDB by creating a `values.yaml` file +when deploying either GreptimeDB clusters or standalone instances. +For a complete list of available configuration options, see [Common Helm Chart Configurations](./common-helm-chart-configurations.md). + +## Manage GreptimeDB Operator + +The GreptimeDB Operator manages GreptimeDB deployments on Kubernetes, +automating the setup, provisioning, and management of GreptimeDB cluster instances. +This enables quick deployment and scaling of GreptimeDB in any Kubernetes environment, +whether on-premises or in the cloud. +Learn how to [manage the GreptimeDB Operator](./greptimedb-operator-management.md), +including installation and upgrades. + +## Advanced Deployments + +After familiarizing yourself with [the architecture and components of GreptimeDB](/user-guide/concepts/architecture.md), you can explore advanced deployment scenarios: + +- [Deploy GreptimeDB Cluster with Remote WAL](configure-remote-wal.md): Configure Kafka as a remote write-ahead log (WAL) for your GreptimeDB cluster to persistently record every data modification and ensure no loss of memory-cached data. +- [Use MySQL/PostgreSQL as Metadata Store](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md#configuring-metasrv-backend-storage): Integrate MySQL/PostgreSQL databases to provide robust metadata storage capabilities for enhanced reliability and performance. +- [Deploy Multi-Frontend GreptimeDB Cluster](configure-frontend-groups.md): Set up a GreptimeDB cluster on Kubernetes with a frontend group consisting of multiple frontend instances for improved load distribution and availability. + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md b/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md new file mode 100644 index 0000000000..3d4d6950af --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md @@ -0,0 +1,147 @@ +--- +keywords: [backup and restore, GreptimeDB, export tool, import tool, database backup, database restoration, command syntax, best practices] +description: Describes how to use GreptimeDB's Export and Import tools for database backup and restoration, including command syntax, options, usage scenarios, best practices, troubleshooting, and performance tips. +--- + +# Data Export & Import + +This guide describes how to use GreptimeDB's Export and Import tools for database data backup and restoration operations. + +For detailed command-line options and advanced configurations, please refer to [Data Export & Import](/reference/command-lines/utilities/data.md). + +## Overview + +## Export Operations + +### Full Databases Backup +Export all databases backup. This operation exports each database into a single directory, including all tables and their data. +```bash +# Export all databases backup +greptime cli data export \ + --addr localhost:4000 \ + --output-dir /tmp/backup/greptimedb +``` +The output directory structure is as follows: +``` +/ +└── greptime/ + └── / + ├── create_database.sql + ├── create_tables.sql + ├── copy_from.sql + └── +``` + +#### Export to S3 + +Export all databases backup to S3: +```bash +greptime cli data export \ + --addr localhost:4000 \ + --s3 \ + --s3-bucket \ + --s3-access-key \ + --s3-secret-key \ + --s3-region \ + --s3-root \ + --s3-endpoint +``` + +### Schema-Only Operations +Export only schemas without data. This operation exports `CREATE TABLE` statements into SQL files, allowing you to backup table structures without the actual data. +```bash +# Export only schemas +greptime cli data export \ + --addr localhost:4000 \ + --output-dir /tmp/backup/schemas \ + --target schema +``` + +### Time-Range Based Backup +```bash +# Export data within specific time range +greptime cli data 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" +``` + +### Specific Database Backup +```bash +# To export a specific database +greptime cli data export \ + --addr localhost:4000 \ + --output-dir /tmp/backup/greptimedb \ + --database '{my_database_name}' +``` + +## Import Operations + +### Full Databases Backup +Import all databases backup. +```bash +# Import all databases +greptime cli data import \ + --addr localhost:4000 \ + --input-dir /tmp/backup/greptimedb +``` + +### Schema-Only Operations +Import only schemas without data. This operation imports `CREATE TABLE` statements from SQL files, allowing you to restore table structures without the actual data. +```bash +# Import only schemas +greptime cli data import \ + --addr localhost:4000 \ + --input-dir /tmp/backup/schemas \ + --target schema +``` + +### Specific Database Backup +```bash +# The same applies to import tool +greptime cli data import \ + --addr localhost:4000 \ + --input-dir /tmp/backup/greptimedb \ + --database '{my_database_name}' +``` + +## Best Practices + +1. **Parallelism Configuration** + - Adjust `--export-jobs`/`--import-jobs` based on available system resources + - Start with a lower value and increase gradually + - Monitor system performance during operations + +2. **Backup Strategy** + - Incremental data backups using time ranges + - Periodic backups for disaster recovery + +3. **Error Handling** + - Use `--max-retry` for handling transient failures + - Keep logs for troubleshooting + +## Performance Tips + +1. **Export Performance** + - Use time ranges for large datasets + - Adjust parallel jobs based on CPU/Memory + - Consider network bandwidth limitations + +2. **Import Performance** + - Monitor database resources + +## Troubleshooting + +1. **Connection Errors** + - Verify server address and port + - Check network connectivity + - Ensure authentication credentials are correct + +2. **Permission Issues** + - Verify read/write permissions on output/input directories + +3. **Resource Constraints** + - Reduce parallel jobs + - Ensure sufficient disk space + - Monitor system resources during operations + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md b/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md new file mode 100644 index 0000000000..4f73186e16 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md @@ -0,0 +1,121 @@ +--- +keywords: [backup, restore, export tool, import tool, database metadata backup, medata restoration, command line tool, disaster recovery] +description: Learn how to use GreptimeDB's metadata export and import tools for backing up and restoring database metadata, including comprehensive examples and best practices +--- + +# Metadata Export & Import + +This guide describes how to use GreptimeDB's metadata export and import tools for metadata backup and restoration operations. + +For detailed command-line options and advanced configurations, please refer to [Metadata Export & Import](/reference/command-lines/utilities/metadata.md). + +## Overview + +## Export Operations + +### Export to S3 Cloud Storage + +Export metadata from PostgreSQL to S3 for cloud-based backup storage: + +```bash +greptime cli meta snapshot save \ + --store-addrs 'password=password dbname=postgres user=postgres host=localhost port=5432' \ + --backend postgres-store \ + --s3 \ + --s3-bucket your-bucket-name \ + --s3-region ap-southeast-1 \ + --s3-access-key \ + --s3-secret-key +``` + +**Output**: Creates `metadata_snapshot.metadata.fb` file in the specified S3 bucket. + +### Export to Local Directory + +#### From PostgreSQL Backend + +Export metadata from PostgreSQL to local directory: + +```bash +greptime cli meta snapshot save \ + --store-addrs 'password=password dbname=postgres user=postgres host=localhost port=5432' \ + --backend postgres-store +``` + +#### From MySQL Backend + +Export metadata from MySQL to local directory: + +```bash +greptime cli meta snapshot save \ + --store-addrs 'mysql://user:password@127.0.0.1:3306/database' \ + --backend mysql-store +``` + +#### From etcd Backend + +Export metadata from etcd to local directory: + +```bash +greptime cli meta snapshot save \ + --store-addrs 127.0.0.1:2379 \ + --backend etcd-store +``` + +**Output**: Creates `metadata_snapshot.metadata.fb` file in the current working directory. + +## Import Operations + +:::warning +**Important**: Before importing metadata, ensure the target backend is in a **clean state** (contains no existing data). Importing to a non-empty backend may result in data corruption or conflicts. + +If you need to import to a backend with existing data, use the `--force` flag to bypass this safety check. However, exercise extreme caution as this can lead to data loss or inconsistencies. + +::: + +### Import from S3 Cloud Storage + +Restore metadata from S3 backup to PostgreSQL storage backend: + +```bash +greptime cli meta snapshot restore \ + --store-addrs 'password=password dbname=postgres user=postgres host=localhost port=5432' \ + --backend postgres-store \ + --s3 \ + --s3-bucket your-bucket-name \ + --s3-region ap-southeast-1 \ + --s3-access-key \ + --s3-secret-key +``` + +### Import from Local File + +#### To PostgreSQL Backend + +Restore metadata from local backup file to PostgreSQL: + +```bash +greptime cli meta snapshot restore \ + --store-addrs 'password=password dbname=postgres user=postgres host=localhost port=5432' \ + --backend postgres-store +``` + +#### To MySQL Backend + +Restore metadata from local backup file to MySQL: + +```bash +greptime cli meta snapshot restore \ + --store-addrs 'mysql://user:password@127.0.0.1:3306/database' \ + --backend mysql-store +``` + +#### To etcd Backend + +Restore metadata from local backup file to etcd: + +```bash +greptime cli meta snapshot restore \ + --store-addrs 127.0.0.1:2379 \ + --backend etcd-store +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-based-on-cross-region-deployment-in-single-cluster.md b/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-based-on-cross-region-deployment-in-single-cluster.md new file mode 100644 index 0000000000..cb6fa4b10d --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-based-on-cross-region-deployment-in-single-cluster.md @@ -0,0 +1,126 @@ +--- +keywords: [disaster recovery, GreptimeDB, cross-region deployment, single cluster, high availability, metadata distribution, data distribution] +description: Explains the disaster recovery (DR) solution based on cross-region deployment in a single GreptimeDB cluster, detailing various configurations for metadata and data distribution across regions to achieve high availability and reliability. +--- + +# DR Solution Based on Cross-Region Deployment in a Single Cluster + +## How disaster recovery works in GreptimeDB +GreptimeDB is well-suited for cross-region disaster recovery. You may have varying regional characteristics and business needs, and GreptimeDB offers tailored solutions to meet these diverse requirements. + +GreptimeDB resource management involves the concept of Availability Zones (AZs). An AZ is a logical unit of disaster recovery. +It can be a Data Center (DC), a compartment of a DC. This depends on your specific DC conditions and deployment design. + +In the cross region disaster recovery solutions, a GreptimeDB region is a city. When two DC are in the same region and one DC becomes unavailable, the other DC can take over the services of the unavailable DC. This is a localization strategy. + +Before understanding the details of each DR solution, it is necessary to first understand the following knowledge: +1. The DR solution for the remote wal component is also very important. Essentially, it forms the foundation of the entire DR solution. Therefore, for each DR solution of GreptimeDB, we will let the remote wal component in the diagram. Currently, GreptimeDB's default remote wal component is implemented based on Kafka, and other implementations will be provided in the future; however, there won't be significant differences in deployment. +2. The table of GreptimeDB: Each table can be divided into multiple partitions according to a certain range, and each partition may be distributed on different datanodes. When writing or querying, the specified node will be called according to the corresponding rules. A table's partitions might look like this: + +``` +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 +``` + + +### Metadata across 2 regions, data in the same region + +![DR-across-2dc-1region](/DR-across-2dc-1region.png) + +In this solution, the data is in one region (2 DCs), while the metadata across 2 regions. + +DC1 and DC2 are used together to handle read and write services, while DC3 (located in region2) is a replica used to meet the majority protocol. This architecture is also called the "2-2-1" solution. + +Both DC1 and DC2 must be able to handle all requests in extreme situations, so please ensure that sufficient resources are allocated. + +Latencies: +- 2ms latency in the same region +- 30ms latency in two regions + +Supports High Availability: +- A single AZ is unavailable with the same performance +- A single DC is unavailable with almost the same performance + + +If you want a regional-level disaster recovery solution, you can take it a step further by providing read and write services on DC3. So, the next solution is: + +### Data across 2 regions + +![DR-across-3dc-2region](/DR-across-3dc-2region.png) + +In this solution, the data across 2 regions. + +Each DC must be able to handle all requests in extreme situations, so please ensure that sufficient resources are allocated. + +Latencies: +- 2ms latency in the same region +- 30ms latency in two regions + +Supports High Availability: +- A single AZ is unavailable with the same performance +- A single DC is unavailable with degraded performance + +If you can't tolerate performance degradation from a single DC failure, consider upgrading to the five-DC and three-region solution. + +### Metadata across 3 regions, data across 2 regions + +![DR-across-5dc-2region](/DR-across-5dc-2region.png) + +In this solution, the data across 2 regions, while the metadata across 3 regions. + +Region1 and region2 are used together to handle read and write services, while region3 is a replica used to meet the majority protocol. This architecture is also called the "2-2-1" solution. + +Each of the two adjacent regions must be able to handle all requests in extreme situations, so please ensure that sufficient resources are allocated. + +Latencies: +- 2ms latency in the same region +- 7ms latency in two adjacent regions +- 30ms latency in two distant regions + +Supports High Availability: +- A single AZ is unavailable with the same performance +- A single DC is unavailable with the same performance +- A single region(city) is unavailable with slightly degraded performance + +You can take it a step further by providing read and write services on both 3 regions. So, the next solution is: +(This solution may have higher latency, so if that's unacceptable, it's not recommended.) + +### Data across 3 regions + +![DR-across-5dc-3region](/DR-across-5dc-3region.png) + +In this solution, the data across 3 regions. + +In the event of a failure in one region, the other two regions must be able to handle all requests, so please ensure sufficient resources are allocated. + +Latencies: +- 2ms latency in the same region +- 7ms latency in two adjacent regions +- 30ms latency in two distant regions + +Supports High Availability: +- A single AZ is unavailable with the same performance +- A single DC is unavailable with the same performance +- A single region(city) is unavailable with degraded performance + +## Solution Comparison +The goal of the above solutions is to meet the high requirements for availability and reliability in medium to large-scale scenarios. However, in specific implementations, the cost and effectiveness of each solution may vary. The table below compares each solution to help you choose the final plan based on your specific scenario, needs, and costs. + +Here is the content formatted into a table: + +| Solution | Latencies | High Availability | +| --- | --- | --- | +| Metadata across 2 regions, data in the same region | - 2ms latency in the same region
- 30ms latency in two regions | - A single AZ is unavailable with the same performance
- A single DC is unavailable with almost the same performance | +| Data across 2 regions | - 2ms latency in the same region
- 30ms latency in two regions | - A single AZ is unavailable with the same performance
- A single DC is unavailable with degraded performance | +| Metadata across 3 regions, data across 2 regions | - 2ms latency in the same region
- 7ms latency in two adjacent regions
- 30ms latency in two distant regions | - A single AZ is unavailable with the same performance
- A single DC is unavailable with the same performance
- A single region(city) is unavailable with slightly degraded performance | +| Data across 3 regions | - 2ms latency in the same region
- 7ms latency in two adjacent regions
- 30ms latency in two distant regions | - A single AZ is unavailable with the same performance
- A single DC is unavailable with the same performance
- A single region(city) is unavailable with degraded performance | diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-for-standalone.md b/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-for-standalone.md new file mode 100644 index 0000000000..fd96fa452f --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/dr-solution-for-standalone.md @@ -0,0 +1,6 @@ +--- +keywords: [disaster recovery, GreptimeDB, standalone, DR solution, backup and restore, remote WAL, object storage] +description: DR solution for GreptimeDB Standalone. +--- + +# DR solution for GreptimeDB Standalone diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/overview.md b/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/overview.md new file mode 100644 index 0000000000..04ca07f126 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/disaster-recovery/overview.md @@ -0,0 +1,130 @@ +--- +keywords: [disaster recovery, GreptimeDB, DR solutions, backup and restore, active-active failover, cross-region deployment, RTO, RPO] +description: Overview of disaster recovery (DR) solutions in GreptimeDB, including basic concepts, component architecture, and various DR solutions such as standalone, active-active failover, cross-region deployment, and backup & restore. +--- + +# Disaster Recovery + +GreptimeDB is a distributed database designed to withstand disasters. It provides different solutions for disaster recovery (DR). + +This document contains: +* Basic concepts in DR. +* The deployment architecture of GreptimeDB and Backup & Restore (BR). +* GreptimeDB provides the DR solutions. +* Compares these DR solutions. + +## Basic Concepts + +* **Recovery Time Objective (RTO)**: refers to the maximum acceptable amount of time that a business process can be down after a disaster occurs before it negatively impacts the organization. +* **Recovery Point Objective (RPO)**: refers to the maximum acceptable amount of time since the last data recovery point. This determines what is considered an acceptable loss of data between the last recovery point and the interruption of service. + +The following figure illustrates these two concepts: + +![RTO-RPO-explain](/RTO-RPO-explain.png) + +* **Write-Ahead Logging (WAL)**: persistently records every data modification to ensure data integrity and consistency. + +GreptimeDB storage engine is a typical [LSM Tree](https://en.wikipedia.org/wiki/Log-structured_merge-tree) : +![LSM-tree-explain](/LSM-tree-explain.png) + +The data written is going firstly persisted into WAL, then applied into Memtable in memory. Under specific conditions (e.g., exceeding the memory threshold), the Memtable will be flushed and persisted as an SSTable. So the DR of WAL and SSTable is key to the DR of GreptimeDB. + +* **Region**: a contiguous segment of a table, and also could be regarded as a partition in some relational databases. Read [Table Sharding](/contributor-guide/frontend/table-sharding.md#region) for more details. + +## Component architecture + +### GreptimeDB + +Before digging into the specific DR solution, let's explain the architecture of GreptimeDB components in the perspective of DR: +![Component-architecture](/Component-architecture.png) + +GreptimeDB is designed with a cloud-native architecture based on storage-compute separation: +* **Frontend**: the ingestion and query service layer, which forwards requests to Datanode and processes, and merges responses from Datanode. +* **Datanode**: the storage layer of GreptimeDB, and is an LSM storage engine. Region is the basic unit for storing and scheduling data in Datanode. A region is a table partition, a collection of data rows. The data in region is saved into Object Storage (such as AWS S3). Unflushed Memtable data is written into WAL and can be recovered in DR. +* **WAL**: persists the unflushed Memtable data in memory. It will be truncated when the Memtable is flushed into SSTable files. It can be local disk-based (local WAL) or Kafka cluster-based (remote WAL). +* **Object Storage**: persists the SSTable data and index. + +The GreptimeDB stores data in object storage such as [AWS S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/DataDurability.html) or its compatible services, which is designed to provide 99.999999999% durability and 99.99% availability of objects over a given year. And services such as S3 provide [replications in Single-Region or Cross-Region](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html), which is naturally capable of DR. + +At the same time, the WAL component is pluggable, e.g. using Kafka as the WAL service that offers a mature [DR solution](https://www.confluent.io/blog/disaster-recovery-multi-datacenter-apache-kafka-deployments/). + +### Backup and restore + +![BR-explain](/BR-explain.png) + +The Backup & Restore (BR) tool can perform a full snapshot backup of databases or tables at a specific time and supports incremental backup. +When a cluster encounters a disaster, you can restore the cluster from backup data. Generally speaking, BR is the last resort for disaster recovery. + +## Solutions introduction + +### DR solution for GreptimeDB Standalone + +If the Standalone is running on the local disk for WAL and data, then: +* RPO: depends on backup frequency. +* RTO: doesn't make sense in standalone mode, mostly depends on the size of the data to be restored, your failure response time, and the operational infrastructure. + +A good start is to deploy GreptimeDB Standalone into an IaaS platform that has a backup and recovery solution. For example, Amazon EC2 with EBS volumes provides a comprehensive [Backup and Recovery solution](https://docs.aws.amazon.com/prescriptive-guidance/latest/backup-recovery/backup-recovery-ec2-ebs.html). + +But if running the Standalone with remote WAL and object storage, there is a better DR solution: +![DR-Standalone](/DR-Standalone.png) + +Write the WAL to the Kafka cluster and store the data in object storage, so the database itself is stateless. In the event of a disaster affecting the standalone database, you can restore it using the remote WAL and object storage. This solution can achieve **RPO=0** and **RTO in minutes**. + +For more information about this solution, see [DR solution for Standalone](./dr-solution-for-standalone.md). + +### DR solution based on Active-Active Failover + +![Active-active failover](/active-active-failover.png) + +In some edge or small-to-medium scale scenarios, or if you lack the resources to deploy remote WAL or object storage, Active-Active Failover offers a better solution compared to Standalone DR. By replicating requests synchronously between two actively serving standalone nodes, high availability is ensured. The failure of any single node will not lead to data loss or a decrease in service availability even when using local disk-based WAL and data storage. + +Deploying nodes in different regions can also meet region-level DR requirements, but the scalability is limited. + +:::tip NOTE + +**Active-Active Failover is only available in GreptimeDB Enterprise.** + +::: + +For more information about this solution, see [DR solution based on Active-Active Failover](/enterprise/deployments-administration/disaster-recovery/dr-solution-based-on-active-active-failover.md). + +### DR solution based on cross-region deployment in a single cluster + +![Cross-region-single-cluster](/Cross-region-single-cluster.png) + +For medium-to-large scale scenarios requiring zero RPO, this solution is highly recommended. In this deployment architecture, the entire cluster spans across three regions, with each region capable of handling both read and write requests. Data replication is achieved using remote WAL and object storage, both of which must have cross-region DR enabled. +If Region 1 becomes completely unavailable due to a disaster, the table regions within it will be opened and recovered in the other regions. +In the event that Region 1 becomes completely unavailable due to a disaster, the table regions within it will be opened and recovered in the other regions. Region 3 serves as a replica to adhere to the majority protocol of Metasrv. + +This solution provides region-level error tolerance, scalable write capability, zero RPO, and minute-level RTO or even lower. For more information about this solution, see [DR solution based on cross-region deployment in a single cluster](./dr-solution-based-on-cross-region-deployment-in-single-cluster.md). + +### DR solution based on BR + +![/BR-DR](/BR-DR.png) + +In this architecture, GreptimeDB Cluster 1 is deployed in region 1. The BR process continuously and regularly backs up the data from Cluster 1 to region 2. If region 1 experiences a disaster rendering Cluster 1 unrecoverable, you can use the backup data to restore a new cluster (Cluster 2) in region 2 to resume services. + +The DR solution based on BR provides an RPO depending on the backup frequency and an RTO that varies with the size of the data to be restored. + +Read [Backup & restore data](./back-up-&-restore-data.md) for details, and we plan to provide a BR tool in-house for this solution. + +### Solution Comparison + +By comparing these DR solutions, you can decide on the final option based on their specific scenarios, requirements, and cost. + + +| DR solution | Error Tolerance Objective | RPO | RTO | TCO | Scenarios | Remote WAL & Object Storage | Notes | +| ------------- | ------------------------- | ----- | ----- | ----- | ---------------- | --------- | --------| +| DR solution for Standalone| Single-Region | Backup Interval | Minute or Hour level | Low | Low requirements for availability and reliability in small scenarios | Optional | | +| DR solution based on Active-Active Failover | Cross-Region | 0 | Minute level | Low | High requirements for availability and reliability in small-to-medium scenarios | Optional | Commercial feature | +| DR solution based on cross-region deployment in a single cluster| Multi-Regions | 0 | Minute level | High | High requirements for availability and reliability in medium-to-large scenarios | Required | | +| DR solution based on BR | Single-Region | Backup Interval | Minute or Hour level | Low | Acceptable requirements for availability and reliability | Optional | | + + +## References + +* [Backup & restore data](./back-up-&-restore-data.md) +* [DR solution for GreptimeDB Standalone](./dr-solution-for-standalone.md) +* [DR solution based on Active-Active Failover ](/enterprise/deployments-administration/disaster-recovery/dr-solution-based-on-active-active-failover.md) +* [DR solution based on cross-region deployment in a single cluster](./dr-solution-based-on-cross-region-deployment-in-single-cluster.md) +* [S3 Replicating objects overview](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html) \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/maintenance-mode.md b/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/maintenance-mode.md new file mode 100644 index 0000000000..c60e18ec59 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/maintenance-mode.md @@ -0,0 +1,115 @@ +--- +keywords: [GreptimeDB, maintenance mode, metasrv, cluster management, region scheduling, auto balancing, failover, upgrade, maintenance] +description: Guide for managing GreptimeDB cluster maintenance mode to safely perform operations like upgrades and maintenance while preventing automatic region scheduling and failover. +--- + +# Cluster Maintenance Mode + +Maintenance mode is a safety feature in GreptimeDB that temporarily disables automatic cluster management operations. + +This mode is particularly useful during: +- Cluster deployment +- Cluster upgrades +- Planned downtime +- Any operation that might temporarily affect cluster stability + + +## When to Use Maintenance Mode + +### With GreptimeDB Operator +If you are upgrading a cluster using GreptimeDB Operator, you don't need to enable the maintenance mode manually. The operator handles this automatically. + +### Without GreptimeDB Operator +When upgrading a cluster without using GreptimeDB Operator, **you must manually enable Metasrv's maintenance mode before**: +1. Deploying a new cluster (maintenance mode should be enabled after metasrv nodes are ready) +2. Rolling upgrades of Datanode nodes +3. Metasrv nodes upgrades +4. Frontend nodes upgrades +5. Any operation that might cause temporary node unavailability + +After the cluster is deployed/upgraded, you can disable the maintenance mode. + +## Impact of Maintenance Mode + +When maintenance mode is enabled: +- Auto Balancing (if enabled) will be paused +- Region Failover (if enabled) will be paused +- Manual region operations are still possible +- Read and write operations continue to work normally +- Monitoring and metrics collection continue to function + +## Managing Maintenance Mode +The maintenance mode can be enabled and disabled through Metasrv's HTTP interface at: `http://{METASRV}:{HTTP_PORT}/admin/maintenance/enable` and `http://{METASRV}:{HTTP_PORT}/admin/maintenance/disable`. Note that this interface listens on Metasrv's `HTTP_PORT`, which defaults to `4000`. + +### Enable Maintenance Mode + +:::danger +After calling the maintenance mode interface, +ensure you check that the HTTP status code returned is 200 and confirm that the response content meets expectations. +If there are any exceptions or the interface behavior does not meet expectations, +proceed with caution and avoid continuing with high-risk operations such as cluster upgrades. +::: + +Enable maintenance mode by sending a POST request to the `/admin/maintenance/enable` endpoint. + +```bash +curl -X POST 'http://localhost:4000/admin/maintenance/enable' +``` + +The expected output is: +```bash +{"enabled":true} +``` + +If you encounter any issues or unexpected behavior, do not proceed with maintenance operations. + +### Disable Maintenance Mode + +:::danger +Before disabling maintenance mode, +you must confirm that **all components have returned to normal status**. +::: + +Disable maintenance mode by sending a POST request to the `/admin/maintenance/disable` endpoint. + +Before disabling maintenance mode: +1. Ensure all components are healthy and operational +2. Verify that all nodes are properly joined to the cluster + +```bash +curl -X POST 'http://localhost:4000/admin/maintenance/disable' +``` + +The expected output is: +```bash +{"enabled":false} +``` + +### Check Maintenance Mode Status + +Check maintenance mode status by sending a GET request to the `/admin/maintenance` endpoint. + +```bash +curl -X GET http://localhost:4000/admin/maintenance/status +``` + +The expected output is: +```bash +{"enabled":false} +``` + +## Troubleshooting + +### Common Issues + +1. **Maintenance mode cannot be enabled** + - Verify Metasrv is running and accessible + - Check if you have the correct permissions + - Ensure the RPC port is correct + +### Best Practices + +1. Always verify the maintenance mode status before and after operations +2. Have a rollback plan ready +3. Monitor cluster health during maintenance +4. Document all changes made during maintenance diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/prevent-metadata-changes.md b/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/prevent-metadata-changes.md new file mode 100644 index 0000000000..351c13d096 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/prevent-metadata-changes.md @@ -0,0 +1,70 @@ +--- +keywords: [GreptimeDB, GreptimeDB cluster, maintenance, pause metadata changes, maintenance mode] +description: Guide for managing GreptimeDB pause metadata changes to safely perform operations like metadata backup. +--- + +# Prevent Metadata Changes + +To prevent metadata changes, you can pause the Procedure Manager. This mechanism rejects all new procedures (i.e., new metadata-changing operations) while allowing existing procedures to continue running. +Once enabled, the Metasrv will reject the following procedures (including but not limited to): + +**DDL procedures:** +- Create table +- Drop table +- Alter table +- Create database +- Drop database +- Create view +- Create flow +- Drop flow + +**Region procedures:** +- Region Migration +- Region Failover (if enabled) +- Auto Balancing (if enabled) + +You may see error messages if you or Metasrv try to perform these procedures after metadata changes are paused. For region procedures, you can enable [Cluster Maintenance Mode](/user-guide/deployments-administration/maintenance/maintenance-mode.md) to temporarily disable them. + +## Managing Procedure Manager +The Procedure Manager can be paused and resumed through Metasrv's HTTP interface at: `http://{METASRV}:{HTTP_PORT}/admin/procedure-manager/pause` and `http://{METASRV}:{HTTP_PORT}/admin/procedure-manager/resume`. Note that this interface listens on Metasrv's `HTTP_PORT`, which defaults to `4000`. + +### Pause Procedure Manager + +Pause Procedure Manager by sending a POST request to the `/admin/procedure-manager/pause` endpoint. + +```bash +curl -X POST 'http://localhost:4000/admin/procedure-manager/pause' +``` + +The expected output is: +```bash +{"status":"paused"} +``` + +### Resume Procedure Manager + +Resume Procedure Manager by sending a POST request to the `/admin/procedure-manager/resume` endpoint. + +```bash +curl -X POST 'http://localhost:4000/admin/procedure-manager/resume' +``` + +The expected output is: +```bash +{"status":"running"} +``` + +### Check Procedure Manager Status + +Check Procedure Manager status by sending a GET request to the `/admin/procedure-manager/status` endpoint. + +```bash +curl -X GET 'http://localhost:4000/admin/procedure-manager/status' +``` + +The expected output is: +```bash +{"status":"running"} +``` + + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/recovery-mode.md b/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/recovery-mode.md new file mode 100644 index 0000000000..c016c407fe --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/recovery-mode.md @@ -0,0 +1,58 @@ +--- +keywords: [GreptimeDB, recovery mode, metasrv, maintenance] +description: Guide for using GreptimeDB cluster recovery mode to address datanode startup failures and recover from region data loss or corruption. +--- + +# Cluster Recovery Mode + +Recovery mode is a safety feature in GreptimeDB that allows developers to manually recover the cluster from a failed state. + +## When to Use Recovery Mode + +Recovery mode is particularly useful when the Datanode fails to start due to an "Empty region directory" error, often caused by: +- Data corruption (Missing region data directory) +- Recover the cluster from a metadata snapshot. + +## Recovery Mode Management + +Recovery mode can be enabled and disabled through Metasrv's HTTP interface at: `http://{METASRV}:{HTTP_PORT}/admin/recovery/enable` and `http://{METASRV}:{HTTP_PORT}/admin/recovery/disable`. Note that this interface listens on Metasrv's `HTTP_PORT`, which defaults to `4000`. + +### Enable Recovery Mode + +Enable recovery mode by sending a POST request to the `/admin/recovery/enable` endpoint. + + +```bash +curl -X POST 'http://localhost:4000/admin/recovery/enable' +``` + +The expected output is: +```bash +{"enabled":true} +``` + +### Disable Recovery Mode + +Disable recovery mode by sending a POST request to the `/admin/recovery/disable` endpoint. + +```bash +curl -X POST 'http://localhost:4000/admin/recovery/disable' +``` + +The expected output is: +```bash +{"enabled":false} +``` + +### Check Recovery Mode Status + +Check recovery mode status by sending a GET request to the `/admin/recovery/status` endpoint. + +```bash +curl -X GET 'http://localhost:4000/admin/recovery/status' +``` + +The expected output is: +```bash +{"enabled":false} +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/sequence-management.md b/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/sequence-management.md new file mode 100644 index 0000000000..0cbe1d0509 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/sequence-management.md @@ -0,0 +1,66 @@ +--- +keywords: [GreptimeDB, resource ID maintenance, metasrv, metadata, maintenance, next table ID, table ID] +description: Guide for maintaining and updating resource IDs in GreptimeDB clusters, including resetting next table ID after metadata restoration. +--- +# Resource ID Management + +Resource ID management is primarily used to manually set resource identifiers (such as table IDs) when restoring a cluster from a [Metadata Backup](/user-guide/deployments-administration/manage-metadata/restore-backup.md). This is because the backup file may not contain the latest `next table ID` value, which could lead to resource conflicts or data inconsistencies if not properly reset. + +### Understanding the Relationship Between Table ID and Next Table ID + +In GreptimeDB: +- **Table ID**: Each table has a unique numeric identifier used internally by the database to identify and manage tables +- **Next Table ID**: The system-reserved next available table ID value. When creating a new table, the system automatically assigns this ID to the new table and then increments the `next table ID` + +**Example:** +- Suppose the current cluster has tables with IDs 1001, 1002, and 1003 +- The `next table ID` should be 1004 +- When creating a new table, the system assigns ID 1004 to the new table and updates the `next table ID` to 1005 +- If during backup restoration, the `next table ID` is still 1002, it would conflict with existing table IDs 1002 and 1003 (you would encounter the error `Region 1024 is corrupted, reason: ` when starting the Datanode) + + +Under normal circumstances, resource IDs are automatically maintained by the database and require no manual intervention. However, in certain special scenarios (such as restoring a cluster from metadata backup where new tables were created after the backup), the `next table ID` in the backup may lag behind the actual cluster state, requiring manual adjustment. + +**How to determine if manual `next table ID` setting is needed:** +1. Query all table IDs in the current cluster: `SELECT TABLE_ID FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_ID DESC LIMIT 1;` +2. Get the current `next table ID` via API (see interface description below) +3. If the maximum existing table ID is greater than or equal to the current `next table ID`, you need to manually set the `next table ID` to a larger value, typically the maximum existing table ID plus 1. + + + +You can get or set the `next table ID` using Metasrv's HTTP interface at the following endpoints: `http://{METASRV}:{HTTP_PORT}/admin/sequence/table/next-id` (to get) and `http://{METASRV}:{HTTP_PORT}/admin/sequence/table/set-next-id` (to set). This interface listens on Metasrv's `HTTP_PORT`, which defaults to `4000`. + +### Set next table ID + +To safely update the `next table ID`, follow this step-by-step process: + +1. **Enable cluster recovery mode** - This prevents new table creation during the update process. See [Cluster Recovery Mode](/user-guide/deployments-administration/maintenance/recovery-mode.md) for more details. +2. **Set the next table ID** - Use the HTTP interface to set the `next table ID`. +3. **Restart metasrv nodes** - This ensures the new `next table ID` is properly applied. +4. **Disable cluster recovery mode** - Resume normal cluster operations. + +Set the `next table ID` by sending a POST request to the `/admin/sequence/table/set-next-id` endpoint: + +```bash +curl -X POST 'http://localhost:4000/admin/sequence/table/set-next-id' \ + -H 'Content-Type: application/json' \ + -d '{"next_table_id": 2048}' +``` + +The expected output is (the `next_table_id` may be different): + +```bash +{"next_table_id":2048} +``` + +### Get next table ID + +```bash +curl -X GET 'http://localhost:4000/admin/sequence/table/next-id' +``` + +The expected output is (the `next_table_id` may be different): + +```bash +{"next_table_id":1254} +``` diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/table-reconciliation.md b/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/table-reconciliation.md new file mode 100644 index 0000000000..a5a48218d6 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/maintenance/table-reconciliation.md @@ -0,0 +1,103 @@ +--- +keywords: [GreptimeDB, table reconciliation, metadata consistency, Metasrv, Datanode, table metadata repair] +description: Guide for understanding GreptimeDB's table reconciliation mechanism that detects and repairs metadata inconsistencies between Metasrv and Datanode. +--- + +# Table Reconciliation + +## Overview + +GreptimeDB uses a layered metadata management architecture in distributed environments: +- **Metasrv**: Acts as the metadata management layer, responsible for maintaining metadata information for all tables in the cluster +- **Datanode**: Handles actual data storage and query execution, while also persisting some table metadata + +Under ideal conditions, table metadata between Metasrv and Datanode should remain perfectly consistent. However, in real production environments, restore from a [metadata backup](/user-guide/deployments-administration/manage-metadata/restore-backup.md) may cause metadata inconsistencies. + +**Table Reconciliation** is a table metadata repair mechanism provided by GreptimeDB that: +- Detects metadata differences between Metasrv and Datanode +- Repairs inconsistency issues according to predefined strategies +- Ensures the system can recover from abnormal states to a consistent, available state + +## Before starting +Before starting the table reconciliation process, you need to: +1. Restore the cluster from a specific [metadata backup](/user-guide/deployments-administration/manage-metadata/restore-backup.md) +2. Set the [Next Table ID](/user-guide/deployments-administration/maintenance/sequence-management.md) to the original cluster's next table ID + +## Repair Scenarios + +### `Table not found` Error + +After a cluster is restored from specific metadata, write and query operations may encounter `Table not found` errors. + +- **Scenario 1**: The original cluster created new tables after the metadata backup, causing the new table metadata to not be included in the backup. This results in `Table not found` errors when querying these new tables. In this case, the new created table will be lost, and you must to manually set the [Next Table ID](/user-guide/deployments-administration/maintenance/sequence-management.md) to ensure that the restored cluster won't fail to create tables due to table ID conflicts when creating new tables. + +- **Scenario 2**: The original cluster renamed existing tables after the metadata backup. In this case, the new table names will be lost. + +### `Empty region directory` Error + +After a cluster is restored from specific metadata, starting the Datanode may result in an `Empty region directory` error. This usually occurs because the original cluster deleted tables (executed `DROP TABLE`) after the metadata backup, causing the deleted table metadata to not be included in the backup, resulting in this error when starting the Datanode. For this situation, you need to enable [Recovery Mode](/user-guide/deployments-administration/maintenance/recovery-mode.md) after starting Metasrv when starting the cluster to ensure the Datanode can start normally. + +- **Mito Engine tables**: Table metadata cannot be repaired, you need to manually execute the `DROP TABLE` command to delete the non-existent table. +- **Metric Engine tables**: Table metadata can be repaired, you need to manually execute the `ADMIN reconcile_table(table_name)` command to repair the table metadata. + +### `No field named` Error + +After a cluster is restored from specific metadata, write and query operations may encounter `No field named` errors. This usually occurs because the original cluster deleted columns (executed `DROP COLUMN`) after the metadata backup, causing the deleted column metadata to not be included in the backup, resulting in this error when querying these deleted columns. For this situation, you need to manually execute the `ADMIN reconcile_table(table_name)` command to repair the table metadata. + +### `schema has a different type` Error + +After a cluster is restored from specific metadata, write and query operations may encounter `schema has a different type` errors. This usually occurs because the original cluster modified column types (executed `MODIFY COLUMN [column_name] [type]`) after the metadata backup, causing the modified column type metadata to not be included in the backup, resulting in this error when querying these modified columns. For this situation, you need to manually execute the `ADMIN reconcile_table(table_name)` command to repair the table metadata. + +### Missing Specific Columns + +After a cluster is restored from specific metadata, write and query operations may run normally but not include some columns. This occurs because the original cluster added columns (executed `ADD COLUMN`) after the metadata backup, causing the new column metadata to not be included in the backup, making these columns unavailable during queries. For this situation, you need to manually execute the `ADMIN reconcile_table(table_name)` command to repair the table metadata. + +### Missing Column Indexes + +After a cluster is restored from specific metadata, write and query operations may run normally, but `SHOW CREATE TABLE`/`SHOW INDEX FROM [table_name]` shows that certain columns don't include expected indexes. This occurs because the original cluster modified indexes (executed `MODIFY INDEX [column_name] SET [index_type] INDEX`) after the metadata backup, causing the index change metadata to not be included in the backup. For this situation, you need to manually execute the `ADMIN reconcile_table(table_name)` command to repair the table metadata. + +## Repair operations + +GreptimeDB provides the following Admin functions to trigger table metadata repair: + +### Repair All Tables + +Repair the metadata inconsistency of all tables in the entire cluster: + +```sql +ADMIN reconcile_catalog() +``` + +### Repair a Specific Database + +Repair the metadata inconsistency of all tables in a specific database: + +```sql +ADMIN reconcile_database(database_name) +``` + +### Repair a Specific Table + +Repair the metadata inconsistency of a single table: + +```sql +ADMIN reconcile_table(table_name) +``` + +### View Repair Progress + +After the Admin function is executed, it will return a `ProcedureID`, you can use the following command to view the progress of the repair task: + +```sql +ADMIN procedure_state(procedure_id) +``` + +When `procedure_state` returns Done, it indicates that the repair task has completed. + +## Important Notes + +When performing table metadata repair operations, please note the following: + +- Repair operations are executed asynchronously, and you can check the execution progress through the `procedure_id` +- It is recommended to perform repair operations during low-traffic periods to reduce the impact on system performance +- For large-scale repair operations (such as `reconcile_catalog()`), it is recommended to validate in a test environment first diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/basic-table-operations.md b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/basic-table-operations.md new file mode 100644 index 0000000000..c8fc0853bd --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/basic-table-operations.md @@ -0,0 +1,364 @@ +--- +keywords: [pg, pgsql, GreptimeDB, SQL table operations, create table, alter table, drop table, describe table, show tables, HTTP API, time zone] +description: Covers basic table operations in GreptimeDB, including creating, describing, showing, altering, and dropping tables, as well as executing SQL statements through the HTTP API and understanding time zone effects. +--- + +# Basic Table Operations + +[Data Model](/user-guide/concepts/data-model.md) should be read before this guide. + +GreptimeDB provides table management functionalities via SQL. The following guide +uses [MySQL Command-Line Client](https://dev.mysql.com/doc/refman/8.0/en/mysql.html) to demonstrate it. + +For more explanations of the `SQL` syntax, please see the [SQL reference](/reference/sql/overview.md). + +## Create a database + +The default database is `public`. You can create a database manually. + +```sql +CREATE DATABASE test; +``` + +```sql +Query OK, 1 row affected (0.05 sec) +``` + +Create a database with a `TTL` (Time-To-Live) of seven days, which means all the tables in this database will inherit this option if they don't have their own `TTL` setting: + +```sql +CREATE DATABASE test with(ttl='7d'); +``` + +You can list all the existing databases. + +```sql +SHOW DATABASES; +``` + +```sql ++---------+ +| Schemas | ++---------+ +| test | +| public | ++---------+ +2 rows in set (0.00 sec) +``` + +Using `like` syntax: + +```sql +SHOW DATABASES LIKE 'p%'; +``` + +```sql ++---------+ +| Schemas | ++---------+ +| public | ++---------+ +1 row in set (0.00 sec) +``` + +Then change the database: + +```sql +USE test; +``` + +Change back to `public` database: + +```sql +USE public; +``` + +## Create a table + +:::tip NOTE +GreptimeDB offers a schemaless approach to writing data that eliminates the need to manually create tables using additional protocols. See [Automatic Schema Generation](/user-guide/ingest-data/overview.md#automatic-schema-generation). +::: + +You can still create a table manually via SQL if you have specific requirements. +Suppose we want to create a table named monitor with the following data model: + +- `host` is the hostname of the collected standalone machine, which should be a `Tag` that used to filter data when querying. +- `ts` is the time when the data is collected, which should be the `Timestamp`. It can also used as a filter when querying data with a time range. +- `cpu` and `memory` are the CPU utilization and memory utilization of the machine, which should be `Field` columns that contain the actual data and are not indexed. + +The SQL code for creating the table is shown below. In SQL, we use the primary key to specify `Tag`s and the `TIME INDEX` to specify the `Timestamp` column. The remaining columns are `Field`s. + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64 DEFAULT 0, + memory FLOAT64, + PRIMARY KEY(host)); +``` + +```sql +Query OK, 0 row affected (0.03 sec) +``` + +Create the table with a `TTL` (Time-To-Live) of seven days: + +```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 does not currently support changing the TIME INDEX after a table has been created. +Therefore, it is important to carefully choose your TIME INDEX column before creating tables. +::: + +### `CREATE TABLE` syntax + +- Timestamp column: GreptimeDB is a time-series database system, a timestamp column must + be explicitly specified by `TIME INDEX` keyword when creating tables. The data type of + the timestamp column must be `TIMESTAMP`type. +- Primary key: The columns in primary key are similar to tags in other other time-series systems like [InfluxDB][1]. The primary key columns with the time index column are used to uniquely define a series of data, which is similar + to time series like [InfluxDB][2]. +- Table options: when creating a table, you can specify a set of table options, click [here](/reference/sql/create.md#table-options) for more details. + +### Table name constraints + +GreptimeDB supports a limited set of special characters in table names, but they must adhere to the following constraints: +- A valid GreptimeDB table name must start with a letter (either lowercase or uppercase) or `-` / `_` / `:`. +- The rest part of table name can be alphanumeric or special characters within: `-` / `_` / `:` / `@` / `#`. +- Any table name containing special characters must be quoted with backquotes. +- Any table name containing uppercase letters must be quoted with backquotes. + +Here are some examples: +```sql +-- ✅ Ok +create table a (ts timestamp time index); + +-- ✅ Ok +create table a0 (ts timestamp time index); + +-- 🚫 Invalid table name +create table 0a (ts timestamp time index); + +-- 🚫 Invalid table name +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 +[2]: https://docs.influxdata.com/influxdb/v1/concepts/glossary/#series + +## Describe a table + +Show table information in detail: + +```sql +DESC TABLE monitor; +``` + +```sql ++--------+----------------------+------+------+---------------------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------+----------------------+------+------+---------------------+---------------+ +| host | String | PRI | YES | | TAG | +| ts | TimestampMillisecond | PRI | NO | current_timestamp() | TIMESTAMP | +| cpu | Float64 | | YES | 0 | FIELD | +| memory | Float64 | | YES | | FIELD | ++--------+----------------------+------+------+---------------------+---------------+ +4 rows in set (0.01 sec) +``` + +The Semantic Type column describes the data model of the table. The `host` is a `Tag` column, `ts` is a `Timestamp` column, and cpu and memory are `Field` columns. + +## Show Table Definition and Indexes + +Use `SHOW CREATE TABLE table_name` to get the statement when creating the table: + +```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 + | ++---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +List all indexes in a table: + +```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 | ++---------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+----------------------------+---------+---------------+---------+------------+ +``` + +For more info about `SHOW` statement, please read the [SHOW reference](/reference/sql/show.md#show). + +## List Existing Tables + +You can use `show tables` statement to list existing tables + +```sql +SHOW TABLES; +``` + +```sql ++------------+ +| Tables | ++------------+ +| monitor | +| scripts | ++------------+ +3 rows in set (0.00 sec) +``` + +Notice: `scripts` table is a built-in table that holds User-Defined Functions (UDFs). +Currently only table name filtering is supported. You can filter existing tables by their names. + +```sql +SHOW TABLES LIKE monitor; +``` + +```sql ++---------+ +| Tables | ++---------+ +| monitor | ++---------+ +1 row in set (0.00 sec) +``` + +List tables in other databases: + +```sql +SHOW TABLES FROM test; +``` + +```sql ++---------+ +| Tables | ++---------+ +| monitor | ++---------+ +1 row in set (0.01 sec) +``` + +## Alter a table + +You can alter the schema of existing tables just like in MySQL database + +```sql +ALTER TABLE monitor ADD COLUMN label VARCHAR; +``` + +```sql +Query OK, 0 rows affected (0.03 sec) +``` + +```sql +ALTER TABLE monitor DROP COLUMN label; +``` + +```sql +Query OK, 0 rows affected (0.03 sec) +``` + +The `ALTER TABLE` statement also supports adding, removing, and renaming columns, as well as modifying the column datatype, etc. Please refer to the [ALTER reference](/reference/sql/alter.md) for more information. + +## Drop a table + +:::danger danger +`DROP TABLE` cannot be undone. Use it with care! +::: + +`DROP TABLE [db.]table` is used to drop the table in `db` or the current database in-use.Drop the table `test` in the current database: + +```sql +DROP TABLE monitor; +``` + +```sql +Query OK, 1 row affected (0.01 sec) +``` + +## Drop a database + +:::danger danger +`DROP DATABASE` cannot be undone. Use it with care! +::: + +You can use `DROP DATABASE` to drop a database. +For example, to drop the `test` database: + +```sql +DROP DATABASE test; +``` + +Please refer to the [DROP](/reference/sql/drop.md#drop-database) document for more details. + +## HTTP API + +You can execute the SQL statements through the HTTP API. +For example, +using the following code to create a table through POST method: + +```shell +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))' \ +http://localhost:4000/v1/sql?db=public +``` + +```json +{ "code": 0, "output": [{ "affectedrows": 1 }], "execution_time_ms": 10 } +``` + +For more information about SQL HTTP request, please refer to [API document](/user-guide/protocols/http.md#post-sql-statements). + +## Time zone + +The specified time zone in the SQL client session will affect the default timestamp value when creating or altering a table. +If you set the default value of a timestamp column to a string without a time zone, +the client's time zone information will be automatically added. + +For more information about the effect of the client time zone, please refer to the [time zone](/user-guide/ingest-data/for-iot/sql.md#time-zone) section in the write data document. + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/compaction.md b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/compaction.md new file mode 100644 index 0000000000..ff2a3df727 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/compaction.md @@ -0,0 +1,160 @@ +--- +keywords: [compaction, GreptimeDB, SST files, time windows, sorted runs, levels, TWCS, SWCS, database performance] +description: Explanation of the compaction process in GreptimeDB, including concepts like SST files, time windows, sorted runs, and levels, as well as the Time Windowed Compaction Strategy (TWCS) and Strict Window Compaction Strategy (SWCS). +--- + +# Compaction + +For databases based on the LSM Tree, compaction is extremely critical. It merges overlapping fragmented SST files into a single ordered file, discards deleted data while significantly improves query performance. + +Until v0.9.1, GreptimeDB provides compaction strategies to control how SST files are compacted: Time Windowed Compaction Strategy (TWCS) and Strict Window Compaction Strategy (SWCS). + + +## Concepts + +Let us start with those core concepts of compaction in GreptimeDB. + +### SST files + +SSTs are sorted files generated when memtables are flushed to persistent storage, such as disks and object stores. + +In GreptimeDB, data rows in SST files are organized by [tags](/user-guide/concepts/data-model.md) and timestamps, as illustrated below. Each SST file covers a specific time range. When a query specifies a time range, GreptimeDB retrieves only the relevant SST files that may contain data within that range, rather than loading all persisted files. + +![SST layout](/compaction-sst-file-layout.jpg) + +Typically, the time ranges of SST files do not overlap during real-time writing workloads. However, due to factors like row deletions and out-of-order writes, SST files may have overlapping time ranges, which can affect query performance. + +### Time window + +Time-series workloads present prominent "windowed" pattern in that most recently inserted rows are more possible to be read. Thus GreptimeDB logically partitioned the time axis into different time windows and we are more interested in compacting those SST files fall into the same time window. + +Time window for some specific table is usually inferred from the most-recently flushed SST files or users may manually specify the time window if TWCS is chosen. + +GreptimeDB has a preset collection of window sizes that are: +- 1 hour +- 2 hours +- 12 hours +- 1 day +- 1 week + +If time window is not specified, GreptimeDB will use `1hour` as the initial time window size and split all inserted rows to those time windows and will infer a proper time window size when the first compaction happens by selecting the minimum time window size for the above collection that can cover the whole time span of all files to be compacted. + +For example, during the first compaction, the time span for all SST files is 4 hours, then GreptimeDB will choose 12 hours as the time window for that table and persist it for later compactions. + + +### Sorted runs +Sorted runs is a collection of SST files that have sorted and non-overlapping time ranges. + +For example, a table contains 5 SSTs with following time ranges (all inclusive): `[0, 10]`, `[12, 23]`, `[22, 25]`,`[24, 30]`,`[26,33]` and we can find 2 sorted runs: + +![num-of-sorted-runs](/compaction-num-sorted-runs.jpg) + + +The number of sorted runs indicates the orderliness of SST files. More sorted runs typically lead to worse query performance. The main goal of compactions is to reduce the number of sorted runs. + +### Levels + +Databases based on LSM trees may also have levels, keys are merged level by level. GreptimeDB only has 2 levels which are 0 (uncompacted) and 1 (compacted). + +## Compaction strategies +GreptimeDB provides two compaction strategies as mentioned above, but only Time Windowed Compaction Strategy (TWCS) can be chosen when creating tables. Strict Window Compaction Strategy (SWCS) is only available when executing manual compactions. + +## Time Windowed Compaction Strategy (TWCS) + +TWCS primarily aims to reduce read/write amplification during compaction. + +It assigns files to be compacted into different time windows. For each window, TWCS identifies the sorted runs. If there are more than 1 sorted runs, TWCS finds a solution to merge the overlapping files in those runs with merging penalties taken into consideration. If there's only 1 sorted run, TWCS checks for excessive file fragmentation and merges fragmented files if necessary since SST file count also impacts query performance. + +For window assignment, SST files may span multiple time windows. TWCS assigns SSTs based on their maximum timestamps to ensure they are not affected by stale data. In time-series workloads, out-of-order writes are infrequent, and even when they occur, recent data's query performance is more critical than that of stale data. + + +TWCS provides 2 parameters: +- `trigger_file_num`: number of files in a specific time window to trigger a compaction (default 4). +- `max_output_file_size`: max allowed compaction output file size (no limit by default). + + +Following diagrams show how files in a window get compacted when `trigger_file_num = 3`: +- In A, there're two SST files `[0, 3]` and `[5, 6, 9]` but there's only one sorted run since those two files have disjoint time ranges. +- In B, a new SST file `[1, 4]` is flushed therefore forms two sorted runs that exceeds the threshold. Then `[0, 3]` and `[1, 4]` are merged to `[0, 1, 3, 4]`. +- In C, a new SST file `[9, 10]` is flushed, and it will be merged with `[5, 6, 10]` to create `[5, 6, 9, 10]`, and after compaction the files will be like D. +- In E, a new file `[11, 12]` is flushed. Though there's still only one sorted run, but the number of files reaches `trigger_file_num`(3), so `[5, 6, 9, 10]` will be merged with `[11, 12]` to form `[5, 6, 9, 10, 11, 12]`. + +![compaction-trigger-file-num.png](/compaction-trigger-file-num.png) + +### Specifying TWCS parameters +You can specify TWCS parameters mentioned above while creating tables, for example: + +```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.trigger_file_num'='8', + 'compaction.twcs.max_output_file_size'='500MB' + ); +``` + +## Strict Window Compaction Strategy (SWCS) and manual compaction + +Unlike TWCS, which assigns one window per SST file based on their maximum timestamps, SWCS assigns SST files to **all** overlapping windows. Consequently, a single SST file may be included in multiple compaction outputs, as its name suggests. Due to its high read amplification during compaction, SWCS is not the default compaction strategy. However, it is useful when you need to manually trigger compaction to reorganize the layout of SST files—especially if an individual SST file spans a large time range that significantly slows down queries. GreptimeDB offers a simple SQL function for triggering compaction: + +```sql +ADMIN COMPACT_TABLE( + , + , + [] +); +``` + +The `` parameter can be either `twcs` or `swcs` (case insensitive) which refer to Time Windowed Compaction Strategy and Strict Window Compaction Strategy respectively. +For the `swcs` strategy, the `` can specify: +- The window size (in seconds) for splitting SST files +- The `parallelism` parameter to control the level of parallelism for compaction (defaults to 1) + +For example, to trigger compaction with a 1-hour window: + +```sql +ADMIN COMPACT_TABLE( + "monitor", + "swcs", + "3600" +); + ++--------------------------------------------------------------------+ +| ADMIN compact_table(Utf8("monitor"),Utf8("swcs"),Utf8("3600")) | ++--------------------------------------------------------------------+ +| 0 | ++--------------------------------------------------------------------+ +1 row in set (0.01 sec) +``` + +When executing this statement, GreptimeDB will split each SST file into segments with a time span of 1 hour (3600 seconds) and merge these segments into a single output, ensuring no overlapping files remain. + +You can also specify the `parallelism` parameter to speed up compaction by processing multiple files concurrently: + +```sql +-- SWCS compaction with default time window and parallelism set to 2 +ADMIN COMPACT_TABLE("monitor", "swcs", "parallelism=2"); + +-- SWCS compaction with custom time window and parallelism +ADMIN COMPACT_TABLE("monitor", "swcs", "window=1800,parallelism=2"); +``` + +The `parallelism` parameter is also available for regular compaction: + +```sql +-- Regular compaction with parallelism set to 2 +ADMIN COMPACT_TABLE("monitor", "regular", "parallelism=2"); +``` + +The following diagram shows the process of strict window compression: + +In Figure A, there are 3 overlapping SST files: `[0, 3]` (which includes timestamps 0, 1, 2, and 3), `[3, 8]`, and `[8, 10]`. +The strict window compaction strategy will assign the file `[3, 8]` that covers windows 0, 4, and 8 to three separate windows respectively. This allows it to merge with `[0, 3]` and `[8, 10]` separately. +Figure B shows the final compaction result with three files: `[0, 3]`, `[4, 7]`, and `[8, 10]`. These files do not overlap with each other. + +![compaction-strict-window.jpg](/compaction-strict-window.jpg) \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/overview.md b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/overview.md new file mode 100644 index 0000000000..d19efb2484 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/overview.md @@ -0,0 +1,10 @@ +--- +keywords: [GreptimeDB, data management, storage location, SQL table operations, data updates, TTL policies, table sharding, region migration, region failover, compaction] +description: Overview of managing data in GreptimeDB, including storage location, basic SQL table operations, data updates, TTL policies, table sharding, region migration, region failover, and compaction. +--- + +import DocCardList from '@theme/DocCardList'; + +# Manage Data + + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/region-failover.md b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/region-failover.md new file mode 100644 index 0000000000..4f5e00b004 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/region-failover.md @@ -0,0 +1,83 @@ +--- +keywords: [region failover, GreptimeDB, data recovery, Kafka WAL, read amplification, distributed mode, region migration, recovery time, shared storage, configuration] +description: Covers enabling and understanding region failover in GreptimeDB, which allows for the recovery of regions from failures without data loss, and discusses the impact of read amplification on recovery time. +--- + +# Region Failover + +Region Failover provides the ability to recover regions from region failures without losing data. This is implemented via [Region Migration](/user-guide/deployments-administration/manage-data/region-migration.md). + +## Enable the Region Failover + +This feature is only available on GreptimeDB running on distributed mode and + +- Using Kafka WAL (Remote WAL) or Local WAL (Enable region failover on local WAL may lead to data loss during failover) +- Using [shared storage](/user-guide/deployments-administration/configuration.md#storage-options) (e.g., AWS S3) + +If you want to enable region failover on local WAL, you need to set `allow_region_failover_on_local_wal=true` in [metasrv](/user-guide/deployments-administration/configuration.md#metasrv-only-configuration) configuration file. It's not recommended to enable this option, because it may lead to data loss. + +### Via configuration file +Set `enable_region_failover=true` in the [metasrv](/user-guide/deployments-administration/configuration.md#metasrv-only-configuration) configuration file. Additionally, set `region_failure_detector_initialization_delay` to a larger value and enable [Cluster Maintenance Mode](/user-guide/deployments-administration/maintenance/maintenance-mode.md) within the `region_failure_detector_initialization_delay` period to avoid triggering unnecessary Region Failover during datanode startup or upgrades. + +### Via GreptimeDB Operator + +To enable region failover via GreptimeDB Operator, you can refer to [Common Helm Chart Configurations](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md#enable-region-failover) for more details. + +## The recovery time of Region Failover + +The recovery time of Region Failover depends on: + +- number of regions per Topic. +- the Kafka cluster read throughput performance. + +### The read amplification + +In best practices, [the number of topics/partitions supported by a Kafka cluster is limited](https://docs.aws.amazon.com/msk/latest/developerguide/bestpractices.html) (exceeding this number can degrade Kafka cluster performance). +Therefore, we allow multiple regions to share a single topic as the WAL. +However, this may cause to the read amplification issue. + +The data belonging to a specific region consists of data files plus data in the WAL (typically `WAL[LastCheckpoint...Latest]`). The failover of a specific region only requires reading the region's WAL data to reconstruct the memory state, which is called region replaying. However, If multiple regions share a single topic, replaying data for a specific region from the topic requires filtering out unrelated data (i.e., data from other regions). This means replaying data for a specific region from the topic requires reading more data than the actual size of the region's data in the topic, a phenomenon known as read amplification. + +Although multiple regions share the same topic, allowing the Datanode to support more regions, the cost of this approach is read amplification during WAL replay. + +For example, configure 128 topics for [metasrv](/user-guide/deployments-administration/configuration.md#metasrv-only-configuration), and if the whole cluster holds 1024 regions (physical regions), every 8 regions will share one topic. + +![Read Amplification](/remote-wal-read-amplification.png) + +

(Figure1: recovery Region 3 need to read redundant data 7 times larger than the actual size)

+ + +A simple model to estimate the read amplification factor (replay data size/actual data size): + +- For a single topic, if we try to replay all regions that belong to the topic, then the amplification factor would be 7+6+...+1 = 28 times. (The Region WAL data distribution is shown in the Figure 1. Replaying Region 3 will read 7 times redundant data larger than the actual size; Region 6 will read 6 times, and so on) +- When recovering 100 regions (requiring about 13 topics), the amplification factor is approximately 28 \* 13 = 364 times. + +Assuming we have 100 regions to recover, and the actual data size of all regions is 0.5GB, the following table shows the replay data size based on the number of regions per topic. + +| Number of regions per Topic | Number of topics required for 100 Regions | Single topic read amplification factor | Total reading amplification factor | Replay data size (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 | + + +The following table shows the recovery time of 100 regions under different read throughput conditions of the Kafka cluster. For example, when providing a read throughput of 300MB/s, recovering 100 regions requires approximately 10 minutes (182.5GB/0.3GB = 10m). + +| Number of regions per Topic | Replay data size (GB) | Kafka throughput 300MB/s- Recovery time (secs) | Kafka throughput 1000MB/s- Recovery time (secs) | +| --------------------------- | ---------------- | --------------------------------------------- | ---------------------------------------------- | +| 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 | + + +### Suggestions for improving recovery time + +In the above example, we calculated the recovery time based on the number of Regions contained in each Topic for reference. +We have calculated the recovery time under different Number of regions per Topic configuration for reference. +In actual scenarios, the read amplification may be larger than this model. +If you are very sensitive to recovery time, we recommend that each region have its topic(i.e., Number of regions per Topic is 1). + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/region-migration.md b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/region-migration.md new file mode 100644 index 0000000000..61c073d25f --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/region-migration.md @@ -0,0 +1,83 @@ +--- +keywords: [region migration, GreptimeDB, data migration, distributed mode, Kafka WAL, shared storage, SQL] +description: Explanation of how to perform region migration in GreptimeDB, including querying region distribution, selecting a migration destination, executing migration requests, and querying migration states. +--- + +# Region Migration + +Region Migration allows users to move regions between the Datanode. + +:::warning Warning +This feature is only available on GreptimeDB running on distributed mode and +- Using [shared storage](/user-guide/deployments-administration/configuration.md#storage-options) (e.g., AWS S3) + +Otherwise, you can't perform a region migration. +::: + + +## Figure out the region distribution of the table. +You need to first query the region distribution of the table, i.e., find out on which Datanode the Regions in the table are located. + +```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='migration_target' order by datanode_id asc; +``` + +For example, have the following region distribution: + +```sql ++-------------+---------------+ +| datanode_id | region_id | ++-------------+---------------+ +| 1 | 4398046511104 | ++-------------+---------------+ +1 row in set (0.01 sec) +``` + + +For more info about the `region_peers` table, please read the [REGION-PEERS](/reference/sql/information-schema/region-peers.md). + +## Select a Datanode as the migration destination. +:::warning Warning +The region migration won't be performed if the `from_peer_id` equals the `to_peer_id`. +::: + +Remember, if you deploy the cluster via the GreptimeDB operator, the `peer_id` of Datanode always starts from 0. For example, if you have a 3 Datanode GreptimeDB cluster, the available `peer_id` will be 0,1,2. + +Finally, you can do a Region migration request via the following SQL: + +```sql +ADMIN migrate_region(4398046511104, 1, 2, 60); +``` + +The parameters of `migrate_region`: + +```sql +ADMIN migrate_region(region_id, from_peer_id, to_peer_id, replay_timeout); +``` + +| Option | Description | Required | | +| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | --- | +| `region_id` | The region id. | **Required** | | +| `from_peer_id` | The peer id of the migration source(Datanode). | **Required** | | +| `to_peer_id` | The peer id of the migration destination(Datanode). | **Required** | | +| `replay_timeout` | The timeout(secs) of replay data. If the new Region fails to replay the data within the specified timeout, the migration will fail, however the data in the old Region will not be lost. | Optional | | + +## Query the migration state + +The `migrate_region` function returns the procedure id that executes the migration, queries the procedure state by it: + +```sql +ADMIN procedure_state('538b7476-9f79-4e50-aa9c-b1de90710839') +``` + +If it's done, outputs the state in JSON: + +```json + {"status":"Done"} +``` + +Of course, you can confirm the region distribution by querying from `region_peers` and `partitions` in `information_schema`. + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/table-sharding.md b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/table-sharding.md new file mode 100644 index 0000000000..155f1b295e --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-data/table-sharding.md @@ -0,0 +1,193 @@ +--- +keywords: [table sharding, GreptimeDB, partitioning methods, distributed tables, data management, SQL, query performance] +description: Explains table sharding in GreptimeDB, including when to shard a table, partitioning methods, creating distributed tables, inserting data, querying data, and inspecting sharded tables. +--- + +# Table Sharding + +Table sharding is a technique used to distribute a large table into multiple smaller tables. +This practice is commonly employed to enhance the performance of database systems. + +In GreptimeDB, data is logically sharded into partitions. +Since GreptimeDB uses "tables" to group data and SQL to query them, +we adopt the term "partition," a concept frequently used in OLTP databases. + +## When to shard a table + +Inside GreptimeDB, both data management and scheduling are based on the region level, +and each region is corresponding to a table partition. +Thus when you have a table that is too large to fit into a single node, +or the table is too hot to be served by a single node, +you should consider sharding it. + +A region in GreptimeDB has a relative fixed throughput capacity, +and the number of regions in a table determines the total throughput capacity of the table. +If you want to increase the throughput capacity of a table, +you can increase the number of regions in the table. +Ideally the overall throughput of a table should be proportional to the number of regions. + +As for which specific partition column to use or how many regions to create, +it depends on the data distribution and the query pattern. +A general goal is to make the data distribution among regions as even as possible. +And the query pattern should be considered when designing the partition rule set as one query can be processed in parallel among regions. +In other word the query latency is depends on the "slowest" region's latency. + +But notice that the increase of regions will bring some basic consumption and increase the complexity of the system. +You need to consider the requirement of data ingest rate, the query performance, +the data distribution on storage system. +You should shard a table only when necessary. + +For more information on the relationship between partitions and regions, refer to the [Table Sharding](/contributor-guide/frontend/table-sharding.md) section in the contributor guide. + +## Partition + +In GreptimeDB, a table can be horizontally partitioned in multiple ways and it uses the same +partitioning types (and corresponding syntax) as in MySQL. Currently, GreptimeDB supports "RANGE COLUMNS partitioning". + +Each partition includes only a portion of the data from the table, and is +grouped by some column(s) value range. For example, we can partition a table in GreptimeDB like +this: + +```sql +CREATE TABLE (...) +PARTITION ON COLUMNS () ( + +); +``` + +The syntax mainly consists of two parts: + +1. `PARTITION ON COLUMNS` followed by a comma-separated list of column names. This specifies which columns will be used for partitioning. The columns specified here must be of the Tag type (as specified by the PRIMARY KEY). Note that the ranges of all partitions must **not** overlap. + +2. `RULE LIST` is a list of multiple partition rules. Each rule is a combination of a partition name and a partition condition. The expressions here can use `=`, `!=`, `>`, `>=`, `<`, `<=`, `AND`, `OR`, column names, and literals. + +:::tip Note +Currently expressions are not supported in "PARTITION BY RANGE" syntax. +::: + +### Example + +## Create a distributed table + +You can use the MySQL CLI to [connect to GreptimeDB](/user-guide/protocols/mysql.md) and create a distributed table. +The following example creates a table and partitions it based on the `device_id` column. + +```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 +); +``` + +More partition columns can be used to create more complex partition rules: + +```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 < 'South', + device_id < 100 AND area >= 'South', + device_id >= 100 AND area <= 'East', + device_id >= 100 AND area > 'East' +); +``` + +The following content uses the `sensor_readings` table with two partition columns as an example. + +## Insert data into the table + +The following code inserts 3 rows into each partition of the `sensor_readings` table. + +```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'); +``` + +:::tip NOTE +Note that when the written data does not meet any of the rules in the partitioning scheme, it will be assigned to the default partition (i.e., the first partition 0 of the table). +::: + +## Distributed Read + +Simply use the `SELECT` statement to query the data: + +```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) +``` + +## Inspect a sharded table + +GreptimeDB provides severals system table to check DB's state. For table sharding information, you can query [`information_schema.partitions`](/reference/sql/information-schema/partitions.md) which gives the detail of partitions inside one table, and [`information_schema.region_peers`](/reference/sql/information-schema/region-peers.md) which gives the runtime distribution of regions. diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/configuration.md b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/configuration.md new file mode 100644 index 0000000000..f355803d5f --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/configuration.md @@ -0,0 +1,164 @@ +--- +keywords: [GreptimeDB, metadata storage, configuration, etcd, MySQL, PostgreSQL, metasrv, backend setup] +description: Comprehensive guide for configuring metadata storage backends (etcd, MySQL, PostgreSQL) in GreptimeDB's metasrv component, including setup instructions and best practices. +--- + +# Metadata Storage Configuration + +This section describes how to configure different metadata storage backends for the GreptimeDB Metasrv component. The metadata storage is used to store critical system information including catalogs, schemas, tables, regions, and other metadata that are essential for the operation of GreptimeDB. + +## Available Storage Backends + +GreptimeDB supports the following metadata storage backends: + +- **etcd**: The default and recommended backend for development and testing environments, offering simplicity and ease of setup +- **MySQL/PostgreSQL**: Production-ready backend options that integrate well with existing database infrastructure and cloud RDS services + +This documentation describes the TOML configuration for each backend. You can use these configurations when deploying GreptimeDB without Helm Chart. +If you are using Helm Chart to deploy GreptimeDB, please refer to [Common Helm Chart Configurations](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md#configuring-metasrv-backend-storage) for more details. + +## Use etcd as metadata storage + +While etcd is suitable for development and testing environments, it may not be ideal for production deployments requiring high availability and scalability. + +Configure the metasrv component to use etcd as metadata storage: + +```toml +# The metadata storage backend for metasrv +backend = "etcd_store" + +# Store server addresses +# You can specify multiple etcd endpoints for high availability +store_addrs = ["127.0.0.1:2379"] + +[backend_tls] +# - "disable" - No TLS +# - "require" - Require TLS +mode = "prefer" + +# Path to client certificate file (for client authentication) +# Like "/path/to/client.crt" +cert_path = "" + +# Path to client private key file (for client authentication) +# Like "/path/to/client.key" +key_path = "" + +# Path to CA certificate file (for server certificate verification) +# Required when using custom CAs or self-signed certificates +# Leave empty to use system root certificates only +# Like "/path/to/ca.crt" +ca_cert_path = "" +``` + +### Best Practices + +While etcd can be used as metadata storage, we recommend against using it in production environments unless you have extensive experience with etcd operations and maintenance. For detailed guidance on etcd management, including installation, backup, and maintenance procedures, please refer to [Manage etcd](/user-guide/deployments-administration/manage-metadata/manage-etcd.md). + +When using etcd as metadata storage: + +- Deploy multiple endpoints across different availability zones for high availability +- Configure appropriate auto-compaction settings to manage storage growth +- Implement regular maintenance procedures: + - Run `Defrag` command periodically to reclaim disk space + - Monitor etcd cluster health metrics + - Review and adjust resource limits based on usage patterns + + +## Use MySQL as metadata storage + +MySQL serves as a viable metadata storage backend option. This choice is particularly beneficial when you need to integrate with existing MySQL infrastructure or have specific MySQL-related requirements. For production deployments, we strongly recommend utilizing cloud providers' Relational Database Service (RDS) solutions for enhanced reliability and managed service benefits. + +Configure the metasrv component to use MySQL as metadata storage: + +```toml +# The metadata storage backend for metasrv +backend = "mysql_store" + +# Store server address +# Format: mysql://user:password@ip:port/dbname +store_addrs = ["mysql://user:password@ip:port/dbname"] + +# Optional: Custom table name for storing metadata +# Default: greptime_metakv +meta_table_name = "greptime_metakv" + +[backend_tls] +# - "disable" - No TLS +# - "prefer" (default) - Try TLS, fallback to plain +# - "require" - Require TLS +# - "verify_ca" - Require TLS and verify CA +# - "verify_full" - Require TLS and verify hostname +mode = "prefer" + +# Path to client certificate file (for client authentication) +# Like "/path/to/client.crt" +cert_path = "" + +# Path to client private key file (for client authentication) +# Like "/path/to/client.key" +key_path = "" + +# Path to CA certificate file (for server certificate verification) +# Required when using custom CAs or self-signed certificates +# Leave empty to use system root certificates only +# Like "/path/to/ca.crt" +ca_cert_path = "" +``` + +When sharing a MySQL instance between multiple GreptimeDB clusters, you must set a unique `meta_table_name` for each GreptimeDB cluster to avoid metadata conflicts. + +## Use PostgreSQL as metadata storage + +PostgreSQL serves as a viable metadata storage backend option. This choice is particularly beneficial when you need to integrate with existing PostgreSQL infrastructure or have specific PostgreSQL-related requirements. For production deployments, we strongly recommend utilizing cloud providers' Relational Database Service (RDS) solutions for enhanced reliability and managed service benefits. + +Configure the metasrv component to use PostgreSQL as metadata storage: + +```toml +# The metadata storage backend for metasrv +backend = "postgres_store" + +# Store server address +# Format: password=password dbname=postgres user=postgres host=localhost port=5432 +store_addrs = ["password=password dbname=postgres user=postgres host=localhost port=5432"] + +# Optional: Custom table name for storing metadata +# Default: greptime_metakv +meta_table_name = "greptime_metakv" + +# Optional: The schema for metadata table and election table name. +# In PostgreSQL 15 and later, the default public schema is restricted by default, +# and non-superusers are no longer allowed to create tables in the public schema. +# When encountering permission restrictions, use this parameter to specify a writable schema. +meta_schema_name = "greptime_schema" + +# Optional: Advisory lock ID for election +# Default: 1 +meta_election_lock_id = 1 + +[backend_tls] +# - "disable" - No TLS +# - "prefer" (default) - Try TLS, fallback to plain +# - "require" - Require TLS +# - "verify_ca" - Require TLS and verify CA +# - "verify_full" - Require TLS and verify hostname +mode = "prefer" + +# Path to client certificate file (for client authentication) +# Like "/path/to/client.crt" +cert_path = "" + +# Path to client private key file (for client authentication) +# Like "/path/to/client.key" +key_path = "" + +# Path to CA certificate file (for server certificate verification) +# Required when using custom CAs or self-signed certificates +# Leave empty to use system root certificates only +# Like "/path/to/ca.crt" +ca_cert_path = "" +``` +When sharing a PostgreSQL instance between multiple GreptimeDB clusters or with other applications, you must configure two unique identifiers to prevent conflicts: + +1. Set a unique `meta_table_name` for each GreptimeDB cluster to avoid metadata conflicts +2. Assign a unique `meta_election_lock_id` to each GreptimeDB cluster to prevent advisory lock conflicts with other applications using the same PostgreSQL instance \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/manage-etcd.md b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/manage-etcd.md new file mode 100644 index 0000000000..25cb017356 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/manage-etcd.md @@ -0,0 +1,548 @@ +--- +keywords: [etcd, kubernetes, helm, backup, restore] +description: A comprehensive guide for managing an etcd cluster including installation, backup, and restoration processes using Kubernetes and Helm. +--- + +# Manage etcd + +The GreptimeDB cluster requires an etcd cluster for [metadata storage](https://docs.greptime.com/nightly/contributor-guide/metasrv/overview) by default. Let's install an etcd cluster using Bitnami's etcd Helm [chart](https://github.com/bitnami/charts/tree/main/bitnami/etcd). + +## Prerequisites + +- [Kubernetes](https://kubernetes.io/docs/setup/) >= v1.23 +- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) >= v1.18.0 +- [Helm](https://helm.sh/docs/intro/install/) >= v3.0.0 + +## Install + +Save the following configuration as a file `etcd.yaml`: + +```yaml +global: + security: + allowInsecureImages: true + +replicaCount: 3 + +image: + registry: docker.io + repository: greptime/etcd + tag: VAR::etcdImageVersion + +auth: + rbac: + create: false + token: + enabled: false + +persistence: + storageClass: null + size: 8Gi + +resources: + limits: + cpu: '2' + memory: 8Gi + requests: + cpu: '2' + memory: 8Gi + +autoCompactionMode: "periodic" +autoCompactionRetention: "1h" + +extraEnvVars: + - name: ETCD_QUOTA_BACKEND_BYTES + value: "8589934592" + - name: ETCD_ELECTION_TIMEOUT + value: "2000" + - name: ETCD_SNAPSHOT_COUNT + value: "10000" +``` + +Install etcd cluster: + +```bash +helm upgrade --install etcd \ + oci://registry-1.docker.io/bitnamicharts/etcd \ + --create-namespace \ + --version VAR::etcdChartVersion \ + -n etcd-cluster \ + --values etcd.yaml +``` + +Wait for etcd cluster to be running: + +```bash +kubectl get pod -n etcd-cluster +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +etcd-0 1/1 Running 0 64s +etcd-1 1/1 Running 0 65s +etcd-2 1/1 Running 0 72s +``` +
+ +When the etcd cluster is running, use the following command to check the health status of etcd cluster: + +```bash +kubectl -n etcd-cluster \ + exec etcd-0 -- etcdctl \ + --endpoints etcd-0.etcd-headless.etcd-cluster:2379,etcd-1.etcd-headless.etcd-cluster:2379,etcd-2.etcd-headless.etcd-cluster:2379 \ + endpoint status -w table +``` + +
+ Expected Output +```bash ++----------------------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+ +| ENDPOINT | ID | VERSION | DB SIZE | IS LEADER | IS LEARNER | RAFT TERM | RAFT INDEX | RAFT APPLIED INDEX | ERRORS | ++----------------------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+ +| etcd-0.etcd-headless.etcd-cluster:2379 | 680910587385ae31 | 3.5.15 | 20 kB | false | false | 4 | 73991 | 73991 | | +| etcd-1.etcd-headless.etcd-cluster:2379 | d6980d56f5e3d817 | 3.5.15 | 20 kB | false | false | 4 | 73991 | 73991 | | +| etcd-2.etcd-headless.etcd-cluster:2379 | 12664fc67659db0a | 3.5.15 | 20 kB | true | false | 4 | 73991 | 73991 | | ++----------------------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+ +``` +
+ +## Backup + +In the bitnami etcd chart, a shared storage volume Network File System (NFS) is used to store etcd backup data. By using CronJob in Kubernetes to perform etcd snapshot backups and mount NFS PersistentVolumeClaim (PVC), snapshots can be transferred to NFS. + +Add the following configuration and name it `etcd-backup.yaml` file, Note that you need to modify **existingClaim** to your NFS PVC name: + +```yaml +global: + security: + allowInsecureImages: true + +replicaCount: 3 + +image: + registry: docker.io + repository: greptime/etcd + tag: VAR::etcdImageVersion + +auth: + rbac: + create: false + token: + enabled: false + +persistence: + storageClass: null + size: 8Gi + +resources: + limits: + cpu: '2' + memory: 8Gi + requests: + cpu: '2' + memory: 8Gi + +autoCompactionMode: "periodic" +autoCompactionRetention: "1h" + +extraEnvVars: + - name: ETCD_QUOTA_BACKEND_BYTES + value: "8589934592" + - name: ETCD_ELECTION_TIMEOUT + value: "2000" + - name: ETCD_SNAPSHOT_COUNT + value: "10000" + +# Backup settings +disasterRecovery: + enabled: true + cronjob: + schedule: "*/30 * * * *" + historyLimit: 2 + snapshotHistoryLimit: 2 + pvc: + existingClaim: "${YOUR_NFS_PVC_NAME_HERE}" +``` + +Redeploy etcd cluster: + +```bash +helm upgrade --install etcd \ + oci://registry-1.docker.io/bitnamicharts/etcd \ + --create-namespace \ + --version VAR::etcdChartVersion \ + -n etcd-cluster \ + --values etcd-backup.yaml +``` + +You can see the etcd backup scheduled task: + +```bash +kubectl get cronjob -n etcd-cluster +``` + +
+ Expected Output +```bash +NAME SCHEDULE TIMEZONE SUSPEND ACTIVE LAST SCHEDULE AGE +etcd-snapshotter */30 * * * * False 0 36s +``` +
+ +```bash +kubectl get pod -n etcd-cluster +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +etcd-0 1/1 Running 0 35m +etcd-1 1/1 Running 0 36m +etcd-2 0/1 Running 0 6m28s +etcd-snapshotter-28936038-tsck8 0/1 Completed 0 4m49s +``` +
+ +```bash +kubectl logs etcd-snapshotter-28936038-tsck8 -n etcd-cluster +``` + +
+ Expected Output +```log +etcd-0.etcd-headless.etcd-cluster.svc.cluster.local:2379 is healthy: successfully committed proposal: took = 2.698457ms +etcd 11:18:07.47 INFO ==> Snapshotting the keyspace +{"level":"info","ts":"2025-01-06T11:18:07.579095Z","caller":"snapshot/v3_snapshot.go:65","msg":"created temporary db file","path":"/snapshots/db-2025-01-06_11-18.part"} +{"level":"info","ts":"2025-01-06T11:18:07.580335Z","logger":"client","caller":"v3@v3.5.15/maintenance.go:212","msg":"opened snapshot stream; downloading"} +{"level":"info","ts":"2025-01-06T11:18:07.580359Z","caller":"snapshot/v3_snapshot.go:73","msg":"fetching snapshot","endpoint":"etcd-0.etcd-headless.etcd-cluster.svc.cluster.local:2379"} +{"level":"info","ts":"2025-01-06T11:18:07.582124Z","logger":"client","caller":"v3@v3.5.15/maintenance.go:220","msg":"completed snapshot read; closing"} +{"level":"info","ts":"2025-01-06T11:18:07.582688Z","caller":"snapshot/v3_snapshot.go:88","msg":"fetched snapshot","endpoint":"etcd-0.etcd-headless.etcd-cluster.svc.cluster.local:2379","size":"20 kB","took":"now"} +{"level":"info","ts":"2025-01-06T11:18:07.583008Z","caller":"snapshot/v3_snapshot.go:97","msg":"saved","path":"/snapshots/db-2025-01-06_11-18"} +Snapshot saved at /snapshots/db-2025-01-06_11-18 +``` +
+ +Next, you can see the etcd backup snapshot in the NFS server: + +```bash +ls ${NFS_SERVER_DIRECTORY} +``` + +
+ Expected Output +```bash +db-2025-01-06_11-18 db-2025-01-06_11-20 db-2025-01-06_11-22 +``` +
+ +## Restore + +When you encounter etcd data loss or corruption, such as critical information stored in etcd being accidentally deleted, or catastrophic cluster failure that prevents recovery, you need to perform an etcd restore. Additionally, restoring etcd can also be useful for development and testing purposes. + +Before recovery, you need to stop writing data to the etcd cluster (stop GreptimeDB Metasrv writing) and create the latest snapshot file use for recovery. + +Add the following configuration file and name it `etcd-restore.yaml`. Note that **existingClaim** is the name of your NFS PVC, and **snapshotFilename** is change to the etcd snapshot file name: + +```yaml +global: + security: + allowInsecureImages: true + +replicaCount: 3 + +image: + registry: docker.io + repository: greptime/etcd + tag: VAR::etcdImageVersion + +auth: + rbac: + create: false + token: + enabled: false + +persistence: + storageClass: null + size: 8Gi + +resources: + limits: + cpu: '2' + memory: 8Gi + requests: + cpu: '2' + memory: 8Gi + +autoCompactionMode: "periodic" +autoCompactionRetention: "1h" + +extraEnvVars: + - name: ETCD_QUOTA_BACKEND_BYTES + value: "8589934592" + - name: ETCD_ELECTION_TIMEOUT + value: "2000" + - name: ETCD_SNAPSHOT_COUNT + value: "10000" + +# Restore settings +startFromSnapshot: + enabled: true + existingClaim: "${YOUR_NFS_PVC_NAME_HERE}" + snapshotFilename: "${YOUR_ETCD_SNAPSHOT_FILE_NAME}" +``` + +Deploy etcd recover cluster: + +```bash +helm upgrade --install etcd-recover \ + oci://registry-1.docker.io/bitnamicharts/etcd \ + --create-namespace \ + --version VAR::etcdChartVersion \ + -n etcd-cluster \ + --values etcd-restore.yaml +``` + +After waiting for the etcd recover cluster to be Running: + +```bash +kubectl get pod -n etcd-cluster -l app.kubernetes.io/instance=etcd-recover +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +etcd-recover-0 1/1 Running 0 91s +etcd-recover-1 1/1 Running 0 91s +etcd-recover-2 1/1 Running 0 91s +``` +
+ +:::tip NOTE +The configuration structure has changed between chart versions: + +- In older version: `meta.etcdEndpoints` +- In newer version: `meta.backendStorage.etcd.endpoints` + +Always refer to the latest [values.yaml](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-cluster/values.yaml) in the Helm chart repository for the most up-to-date configuration structure. +::: + +Next, change Metasrv [backendStorage.etcd.endpoints](https://github.com/GreptimeTeam/helm-charts/tree/main/charts/greptimedb-cluster) to the new etcd recover cluster, in this example is `"etcd-recover.etcd-cluster.svc.cluster.local:2379"`: + +```yaml +apiVersion: greptime.io/v1alpha1 +kind: GreptimeDBCluster +metadata: + name: greptimedb +spec: + # Other configuration here + meta: + backendStorage: + etcd: + endpoints: + - "etcd-recover.etcd-cluster.svc.cluster.local:2379" +``` + +Restart GreptimeDB Metasrv to complete etcd restore. + +## Monitoring + +- Prometheus Operator installed (e.g. via [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack)). +- podmonitor CRD installed (automatically installed with Prometheus Operator). + +Add the following to your `etcd-monitoring.yaml` to enable monitoring: + +```yaml +global: + security: + allowInsecureImages: true + +replicaCount: 3 + +image: + registry: docker.io + repository: greptime/etcd + tag: VAR::etcdImageVersion + +auth: + rbac: + create: false + token: + enabled: false + +persistence: + storageClass: null + size: 8Gi + +resources: + limits: + cpu: '2' + memory: 8Gi + requests: + cpu: '2' + memory: 8Gi + +autoCompactionMode: "periodic" +autoCompactionRetention: "1h" + +extraEnvVars: + - name: ETCD_QUOTA_BACKEND_BYTES + value: "8589934592" + - name: ETCD_ELECTION_TIMEOUT + value: "2000" + - name: ETCD_SNAPSHOT_COUNT + value: "10000" + +# Monitoring settings +metrics: + enabled: true + podMonitor: + enabled: true + namespace: etcd-cluster + interval: 10s + scrapeTimeout: 10s + additionalLabels: + release: prometheus +``` + +Deploy etcd with Monitoring: + +```bash +helm upgrade --install etcd \ + oci://registry-1.docker.io/bitnamicharts/etcd \ + --create-namespace \ + --version VAR::etcdChartVersion \ + -n etcd-cluster \ + --values etcd-monitoring.yaml +``` + +### Grafana dashboard + +Use the [ETCD Cluster Overview dashboard](https://grafana.com/grafana/dashboards/15308-etcd-cluster-overview/) (ID: 15308) for monitoring key metrics. + +1. Log in your Grafana. +2. Navigate to Dashboards -> New -> Import. +3. Enter Dashboard ID: 15308, select the data source and load. + +![ETCD Cluster Overview dashboard](/etcd-cluster-overview-dashboard.png) + +## ⚠️ Defrag - Critical Warning + +Defragmentation is a HIGH-RISK operation that can severely impact your ETCD cluster and dependent systems (like GreptimeDB): + +1. Blocks ALL read/write operations during execution (cluster becomes unavailable). +2. High I/O usage may cause timeouts in client applications. +3. May trigger leader elections if defrag takes too long. +4. Can cause OOM kills if not properly resourced. +5. May corrupt data if interrupted mid-process. + +ETCD uses a multi-version concurrency control (MVCC) mechanism that stores multiple versions of KV. Over time, as data is updated and deleted, the backend database can become fragmented, leading to increased storage usage and reduced performance. Defragmentation is the process of compacting this storage to reclaim space and improve performance. + +Add the following defrag-related configuration to `etcd-defrag.yaml` file: + +```yaml +global: + security: + allowInsecureImages: true + +replicaCount: 3 + +image: + registry: docker.io + repository: greptime/etcd + tag: VAR::etcdImageVersion + +auth: + rbac: + create: false + token: + enabled: false + +persistence: + storageClass: null + size: 8Gi + +resources: + limits: + cpu: '2' + memory: 8Gi + requests: + cpu: '2' + memory: 8Gi + +autoCompactionMode: "periodic" +autoCompactionRetention: "1h" + +extraEnvVars: + - name: ETCD_QUOTA_BACKEND_BYTES + value: "8589934592" + - name: ETCD_ELECTION_TIMEOUT + value: "2000" + - name: ETCD_SNAPSHOT_COUNT + value: "10000" + +# Defragmentation settings +defrag: + enabled: true + cronjob: + schedule: "0 3 * * *" # Daily at 3:00 AM + suspend: false + successfulJobsHistoryLimit: 1 + failedJobsHistoryLimit: 1 +``` + +Deploying with Defrag Configuration: + +```bash +helm upgrade --install etcd \ + oci://registry-1.docker.io/bitnamicharts/etcd \ + --create-namespace \ + --version VAR::etcdChartVersion \ + -n etcd-cluster \ + --values etcd-defrag.yaml +``` + +You can see the etcd defrag scheduled task: + +```bash +kubectl get cronjob -n etcd-cluster +``` + +
+ Expected Output +```bash +NAME SCHEDULE TIMEZONE SUSPEND ACTIVE LAST SCHEDULE AGE +etcd-defrag 0 3 * * * False 0 34s +``` +
+ +```bash +kubectl get pod -n etcd-cluster +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +etcd-0 1/1 Running 0 4m30s +etcd-1 1/1 Running 0 4m29s +etcd-2 1/1 Running 0 4m29s +etcd-defrag-29128518-sstbf 0/1 Completed 0 90s +``` +
+ +```bash +kubectl logs etcd-defrag-29128518-sstbf -n etcd-cluster +``` + +
+ Expected Output +```log +Finished defragmenting etcd member[http://etcd-0.etcd-headless.etcd-cluster.svc.cluster.local:2379] +Finished defragmenting etcd member[http://etcd-1.etcd-headless.etcd-cluster.svc.cluster.local:2379] +Finished defragmenting etcd member[http://etcd-2.etcd-headless.etcd-cluster.svc.cluster.local:2379] +``` +
diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/overview.md b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/overview.md new file mode 100644 index 0000000000..9092908b26 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/overview.md @@ -0,0 +1,37 @@ +--- +keywords: [GreptimeDB, metadata storage, etcd, MySQL, PostgreSQL, configuration] +description: Overview of metadata storage options in GreptimeDB, including etcd, MySQL, and PostgreSQL, with recommendations for production deployments. +--- + +# Overview + +GreptimeDB cluster Metasrv component requires a metadata storage to store metadata. GreptimeDB offers flexible metadata storage options with [etcd](https://etcd.io/), [MySQL](https://www.mysql.com/), and [PostgreSQL](https://www.postgresql.org/). Each option is designed for different deployment scenarios, balancing factors like scalability, reliability, and operational overhead. + +- [etcd](https://etcd.io/): A lightweight distributed key-value store perfect for metadata management. Its simplicity and ease of setup make it an excellent choice for development and testing environments. + +- [MySQL](https://www.mysql.com/) and [PostgreSQL](https://www.postgresql.org/): Enterprise-grade relational databases that deliver robust metadata storage capabilities. They provide essential features including ACID transactions, replication, and comprehensive backup solutions, making them ideal for production environments. Both are widely available as managed database services (RDS) across major cloud platforms. + +## Recommendation + +For test and development environments, [etcd](https://etcd.io/) provides a lightweight and straightforward metadata storage solution. + +**For production deployments, we strongly recommend using cloud providers' Relational Database Service (RDS) for metadata storage.** This approach offers several advantages: + +- Managed service with built-in high availability and disaster recovery +- Automated backups and maintenance +- Professional monitoring and support +- Reduced operational complexity compared to self-hosted solutions +- Seamless integration with other cloud services + +## Best Practices + +- Implement regular backup schedules for your metadata storage +- Set up comprehensive monitoring for storage health and performance metrics +- Establish clear disaster recovery procedures +- Document your metadata storage configuration and maintenance procedures + + + +## Next steps +- To configure the metadata storage backend, please refer to [Configuration](/user-guide/deployments-administration/manage-metadata/configuration.md). +- To setup etcd for testing and development environments, please refer to [Manage etcd](/user-guide/deployments-administration/manage-metadata/manage-etcd.md). \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/restore-backup.md b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/restore-backup.md new file mode 100644 index 0000000000..dc3f644bc9 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/manage-metadata/restore-backup.md @@ -0,0 +1,38 @@ +--- +keywords: [GreptimeDB, metadata backup, restore, migration, etcd, MySQL, PostgreSQL, disaster recovery] +description: Guide for backing up, restoring, and migrating GreptimeDB metadata across different storage backends (etcd, MySQL, PostgreSQL) with best practices for data consistency. +--- + +# Backup and Restore, Migrate + +GreptimeDB provides metadata backup and restore capabilities through its CLI tool. This functionality supports all major metadata storage backends including etcd, MySQL, and PostgreSQL. For detailed instructions on using these features, refer to the [Backup and Restore](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data.md) guide. + +## Backup + +For optimal backup reliability, schedule metadata backups during periods of low DDL (Data Definition Language) activity. This helps ensure data consistency and reduces the risk of partial or incomplete backups. + +To perform a backup: + +1. Verify that your GreptimeDB cluster is operational +2. Execute the backup using the CLI tool, follows the export metadata steps in [Backup and Restore](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md) guide. +3. Ensure the backup output file is created, and the file size is greater than 0. + +## Restore + +To restore from a backup: + +1. Use the CLI tool to restore the metadata, follows the import metadata steps in [Backup and Restore](/user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data.md) guide. +2. Restart the GreptimeDB cluster to apply the restored metadata. +3. Set the [Next Table ID](/user-guide/deployments-administration/maintenance/sequence-management.md) to the original cluster's next table ID. +4. Call the [Table Reconciliation](/user-guide/deployments-administration/maintenance/table-reconciliation.md) function to repair the table metadata inconsistency. + +## Migrate + +We recommend to migrate metadata during periods of low DDL (Data Definition Language) activity to ensure data consistency and minimize the risk of partial or incomplete migrations. + +Migrate metadata from one metadata storage to another. + +1. Backup the metadata from the source storage. +2. Restore the metadata to the target storage. +3. Restart the whole GreptimeDB cluster(all components) to apply the restored metadata. + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/check-db-status.md b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/check-db-status.md new file mode 100644 index 0000000000..e6268b3074 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/check-db-status.md @@ -0,0 +1,48 @@ +--- +keywords: [GreptimeDB health check, GreptimeDB status, GreptimeDB deployment status, GreptimeDB metrics] +description: Check GreptimeDB health status, deployment status, and runtime metrics through HTTP endpoints. +--- + +# Check GreptimeDB Status + +GreptimeDB provides a series of HTTP endpoints to query the operational status of GreptimeDB. +The following HTTP requests assume that GreptimeDB is running on node `127.0.0.1` with the HTTP service listening on the default port `4000`. + +## Check if GreptimeDB is running normally + +You can use the `/health` endpoint to check if GreptimeDB is running normally. +An HTTP status code `200 OK` indicates that GreptimeDB is running normally. + +Example: + +```bash +curl -i -X GET http://127.0.0.1:4000/health +HTTP/1.1 200 OK +content-type: application/json +content-length: 2 +date: Tue, 31 Dec 2024 02:15:22 GMT + +{} +``` + +For more information about the health check endpoint, please refer to [the Health endpoint](/reference/http-endpoints.md#health-check). + +## Check GreptimeDB status + +You can use the `/status` endpoint to check the deployment status of GreptimeDB. + +```bash +curl -X GET http://127.0.0.1:4000/status | jq + +{ + "source_time": "2024-12-27T07:57:47Z", + "commit": "b4bd34c530d62b95346a26a9470c03b9f6fb15c8", + "branch": "main", + "rustc_version": "rustc 1.84.0-nightly (e92993dbb 2024-10-18)", + "hostname": "127.0.0.1", + "version": "0.12.0" +} +``` + +Please refer to [the Status endpoint](/reference/http-endpoints.md#status) for more details. + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/cluster-monitoring-deployment.md b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/cluster-monitoring-deployment.md new file mode 100644 index 0000000000..c82e37e4ca --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/cluster-monitoring-deployment.md @@ -0,0 +1,272 @@ +--- +keywords: [Kubernetes deployment, cluster, monitoring] +description: Complete guide to deploying self-monitoring for GreptimeDB clusters on Kubernetes, including Grafana dashboard setup and configuration options +--- + +# Self-Monitoring GreptimeDB Clusters + +Before reading this document, ensure you understand how to [deploy a GreptimeDB cluster on Kubernetes](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md). +This guide will walk you through configuring monitoring when deploying a GreptimeDB cluster. + +## Quick Start + +You can enable monitoring and Grafana by adding configurations to the `values.yaml` file when deploying the GreptimeDB cluster using Helm Chart. +Here's a complete example of `values.yaml` for deploying a minimal GreptimeDB cluster with monitoring and Grafana: + +```yaml +image: + registry: docker.io + # Image repository: + # Use `greptime/greptimedb` for OSS GreptimeDB + # Consult staff for GreptimeDB Enterprise + repository: + # Image tag: + # Use database version `VAR::greptimedbVersion` for OSS GreptimeDB + # Consult staff for GreptimeDB Enterprise + tag: + pullSecrets: [] + +initializer: + registry: docker.io + repository: greptime/greptimedb-initializer + +monitoring: + # Enable monitoring + enabled: true + +grafana: + # Enable Grafana deployment + # Requires monitoring to be enabled first (monitoring.enabled: true) + enabled: true + +frontend: + replicas: 1 + +meta: + replicas: 1 + backendStorage: + etcd: + endpoints: "etcd.etcd-cluster.svc.cluster.local:2379" + +datanode: + replicas: 1 +``` + +When `monitoring` is enabled, GreptimeDB Operator launches an additional GreptimeDB Standalone instance to collect metrics and logs from the GreptimeDB cluster. +To collect log data, GreptimeDB Operator starts a [Vector](https://vector.dev/) sidecar container in each Pod. + +When `grafana` is enabled, a Grafana instance is deployed that uses the GreptimeDB Standalone instance configured for cluster monitoring as its data source. +This enables visualization of the GreptimeDB cluster's monitoring data out of the box using both Prometheus and MySQL protocols. + +Then install the GreptimeDB cluster with the above `values.yaml` file: + +```bash +helm upgrade --install mycluster \ + greptime/greptimedb-cluster \ + --values /path/to/values.yaml \ + -n default +``` + +After installation, you can check the Pod status of the GreptimeDB cluster: + +```bash +kubectl -n default get pods +``` + +
+ Expected Output +```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 +``` +
+ +You can then access the Grafana dashboard by port-forwarding the Grafana service to your local machine: + +```shell +kubectl -n default port-forward svc/mycluster-grafana 18080:80 +``` + +Then refer to the [Access Grafana Dashboard](#access-grafana-dashboard) section below for details on accessing Grafana. + +## Monitoring Configuration + +This section covers the details of monitoring configurations. + +### Enable Monitoring + +Add the following configuration to [`values.yaml`](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md#setup-valuesyaml) to enable monitoring when deploying the GreptimeDB cluster: + +```yaml +monitoring: + enabled: true +``` + +This deploys a GreptimeDB Standalone instance named `${cluster-name}-monitoring` to collect metrics and logs. You can verify the deployment with: + +```bash +kubectl get greptimedbstandalones.greptime.io ${cluster-name}-monitoring -n ${namespace} +``` + +The GreptimeDB Standalone instance exposes services using `${cluster-name}-monitoring-standalone` as the Kubernetes Service name. You can use the following addresses to access monitoring data: + +- **Prometheus metrics**: `http://${cluster-name}-monitor-standalone.${namespace}.svc.cluster.local:4000/v1/prometheus` +- **SQL logs**: `${cluster-name}-monitor-standalone.${namespace}.svc.cluster.local:4002`. By default, cluster logs are stored in the `public._gt_logs` table. + +### Customize Monitoring Storage + +By default, the GreptimeDB Standalone instance stores monitoring data using the Kubernetes default StorageClass in local storage. +You can configure the GreptimeDB Standalone instance through the `monitoring.standalone` field in `values.yaml`. For example, the following configuration uses S3 object storage to store monitoring data: + +```yaml +monitoring: + enabled: true + standalone: + base: + main: + # Configure GreptimeDB Standalone instance image + image: "greptime/greptimedb:latest" + + # Configure GreptimeDB Standalone instance resources + resources: + requests: + cpu: "2" + memory: "4Gi" + limits: + cpu: "2" + memory: "4Gi" + + # Configure object storage for GreptimeDB Standalone instance + objectStorage: + s3: + # Configure bucket + bucket: "monitoring" + # Configure region + region: "ap-southeast-1" + # Configure secret name + secretName: "s3-credentials" + # Configure root path + root: "standalone-with-s3-data" +``` + +### Customize Vector Sidecar + +The Vector sidecar configuration for log collection can be customized via the `monitoring.vector` field. +For example, you can adjust the Vector image and resource limits as follows: + +```yaml +monitoring: + enabled: true + vector: + # Configure Vector image registry + registry: docker.io + # Configure Vector image repository + repository: timberio/vector + # Configure Vector image tag + tag: nightly-alpine + + # Configure Vector resources + resources: + requests: + cpu: "50m" + memory: "64Mi" + limits: + cpu: "50m" + memory: "64Mi" +``` + +### YAML Configuration with `kubectl` Deployment + +If you're not using Helm Chart, you can also use the `monitoring` field to manually configure self-monitoring mode in the `GreptimeDBCluster` YAML: + +```yaml +monitoring: + enabled: true +``` + +For detailed configuration options, refer to the [`GreptimeDBCluster` API documentation](https://github.com/GreptimeTeam/greptimedb-operator/blob/main/docs/api-references/docs.md#monitoringspec). + + +## Grafana Configuration + +### Enable Grafana + +To enable Grafana deployment, add the following configuration to `values.yaml`. +Note that monitoring must be enabled first [(`monitoring.enabled: true`)](#enable-monitoring): + +```yaml +monitoring: + enabled: true + +grafana: + enabled: true +``` + +### Customize Grafana Data Sources + +By default, Grafana uses `mycluster` and `default` as the cluster name and namespace to create data sources. +To monitor clusters with different names or namespaces, you need to create custom data source configurations based on the actual cluster names and namespaces. +Here's an example `values.yaml` configuration: + +```yaml +monitoring: + enabled: true + +grafana: + enabled: true + datasources: + datasources.yaml: + datasources: + - name: greptimedb-metrics + type: prometheus + url: http://${cluster-name}-monitor-standalone.${namespace}.svc.cluster.local:4000/v1/prometheus + access: proxy + isDefault: true + + - name: greptimedb-logs + type: mysql + url: ${cluster-name}-monitor-standalone.${namespace}.svc.cluster.local:4002 + access: proxy + database: public +``` + +This configuration creates the following data sources for GreptimeDB cluster monitoring in Grafana: + +- **`greptimedb-metrics`**: Cluster metrics stored in the standalone monitoring database, exposed via Prometheus protocol (`type: prometheus`) +- **`greptimedb-logs`**: Cluster logs stored in the standalone monitoring database, exposed via MySQL protocol (`type: mysql`). Uses the `public` database by default + +### Access Grafana Dashboard + +You can access the Grafana dashboard by port-forwarding the Grafana service to your local machine: + +```bash +kubectl -n ${namespace} port-forward svc/${cluster-name}-grafana 18080:80 +``` + +Then open `http://localhost:18080` to access the Grafana dashboard. +The default login credentials for Grafana are: + +- **Username**: `admin` +- **Password**: `gt-operator` + +Navigate to the `Dashboards` section to explore the pre-configured dashboards for monitoring your GreptimeDB cluster. + +![Grafana Dashboard](/kubernetes-cluster-grafana-dashboard.jpg) + + +## Cleanup the PVCs + +:::danger +The cleanup operation will remove the metadata and data of the GreptimeDB cluster. Please make sure you have backed up the data before proceeding. +::: +To uninstall the GreptimeDB cluster, please refer to the [Cleanup GreptimeDB Cluster](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md#cleanup) documentation. + +To clean up the Persistent Volume Claims (PVCs) used by the GreptimeDB standalone monitoring instance, delete the PVCs using the following command: + +```bash +kubectl -n default delete pvc -l app.greptime.io/component=${cluster-name}-monitor-standalone +``` diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/key-logs.md b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/key-logs.md new file mode 100644 index 0000000000..9d4d7f3856 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/key-logs.md @@ -0,0 +1,205 @@ +--- +keywords: [key logs, error logs, operational logs, GreptimeDB logs] +description: Understand GreptimeDB's operational status and troubleshoot errors through key logs. +--- + +# Key Logs + +During operation, GreptimeDB outputs key operations and unexpected error information to logs. +You can use these logs to understand GreptimeDB's operational status and troubleshoot errors. + +## Log Location + +GreptimeDB components default to outputting INFO level logs to the following locations: + +- Standard output +- `greptimedb_data/logs` directory under GreptimeDB's current working directory + +The log output directory can also be modified through the `[logging]` section in the configuration file or the `--log_dir` startup parameter: + +```toml +[logging] +dir = "/path/to/logs" +``` + +Log file formats are: +- `greptimedb.YYYY-MM-DD-HH` contains logs of INFO level and above +- `greptimedb-err.YYYY-MM-DD-HH` contains error logs + +For example: + +```bash +greptimedb.2025-04-11-06 +greptimedb-err.2025-04-11-06 +``` + +Currently, GreptimeDB components include: + +- frontend +- datanode +- metasrv +- flownode + +If you need to adjust log levels, such as viewing DEBUG level logs for a component, you can refer to [this document](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-change-log-level-on-the-fly.md) to modify them at runtime. + +## Important Logs + +The following lists recommended logs to monitor: + +### Error Logs + +When the database is running normally and stably, it will not output error logs. If database operations encounter exceptions or panics occur, error logs will be printed. It is recommended that users check error logs from all components. + +#### Panic + +If the database encounters a panic, it is recommended to collect the panic logs and report them to the official team. Typical panic logs look like this, with the keyword `panicked at`: + +```bash +2025-04-02T14:44:24.485935Z ERROR common_telemetry::panic_hook: panicked at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/expr/src/logical_plan/plan.rs:1035:25: +with_new_exprs for Distinct does not support sort expressions backtrace= 0: backtrace::backtrace::libunwind::trace + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/backtrace-0.3.74/src/backtrace/libunwind.rs:116:5 + backtrace::backtrace::trace_unsynchronized + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/backtrace-0.3.74/src/backtrace/mod.rs:66:5 + 1: backtrace::backtrace::trace + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/backtrace-0.3.74/src/backtrace/mod.rs:53:14 + 2: backtrace::capture::Backtrace::create + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/backtrace-0.3.74/src/capture.rs:292:9 + 3: backtrace::capture::Backtrace::new + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/backtrace-0.3.74/src/capture.rs:257:22 + 4: common_telemetry::panic_hook::set_panic_hook::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/common/telemetry/src/panic_hook.rs:37:25 + 5: as core::ops::function::Fn>::call + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/alloc/src/boxed.rs:1984:9 + std::panicking::rust_panic_with_hook + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/std/src/panicking.rs:820:13 + 6: std::panicking::begin_panic_handler::{{closure}} + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/std/src/panicking.rs:678:13 + 7: std::sys::backtrace::__rust_end_short_backtrace + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/std/src/sys/backtrace.rs:168:18 + 8: rust_begin_unwind + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/std/src/panicking.rs:676:5 + 9: core::panicking::panic_fmt + at /rustc/409998c4e8cae45344fd434b358b697cc93870d0/library/core/src/panicking.rs:75:14 + 10: datafusion_expr::logical_plan::plan::LogicalPlan::with_new_exprs + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/expr/src/logical_plan/plan.rs:1035:25 + 11: ::analyze::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/optimizer/type_conversion.rs:105:17 + 12: core::ops::function::impls:: for &F>::call_mut + at /greptime/.rustup/toolchains/nightly-2024-12-25-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/ops/function.rs:272:13 + 13: core::ops::function::impls:: for &mut F>::call_once + at /greptime/.rustup/toolchains/nightly-2024-12-25-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/ops/function.rs:305:13 + 14: datafusion_common::tree_node::Transformed::transform_parent + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/common/src/tree_node.rs:764:44 + 15: datafusion_common::tree_node::TreeNode::transform_up::transform_up_impl::{{closure}} + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/common/src/tree_node.rs:265:13 + 16: stacker::maybe_grow + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/stacker-0.1.17/src/lib.rs:55:9 + datafusion_common::tree_node::TreeNode::transform_up::transform_up_impl + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/common/src/tree_node.rs:260:9 + 17: datafusion_common::tree_node::TreeNode::transform_up + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/common/src/tree_node.rs:269:9 + 18: datafusion_common::tree_node::TreeNode::transform + at /greptime/.cargo/git/checkouts/datafusion-11a8b534adb6bd68-shallow/2464703/datafusion/common/src/tree_node.rs:220:9 + 19: ::analyze + at /greptime/codes/greptime/procedure-traits/src/query/src/optimizer/type_conversion.rs:46:9 + 20: query::query_engine::state::QueryEngineState::optimize_by_extension_rules::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/query_engine/state.rs:195:17 + 21: core::iter::traits::iterator::Iterator::try_fold + at /greptime/.rustup/toolchains/nightly-2024-12-25-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2370:21 + 22: query::query_engine::state::QueryEngineState::optimize_by_extension_rules + at /greptime/codes/greptime/procedure-traits/src/query/src/query_engine/state.rs:192:9 + 23: query::planner::DfLogicalPlanner::plan_sql::{{closure}}::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/planner.rs:119:20 + 24: as core::future::future::Future>::poll + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tracing-0.1.40/src/instrument.rs:321:9 + 25: query::planner::DfLogicalPlanner::plan_sql::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/planner.rs:71:5 + 26: ::plan::{{closure}}::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/planner.rs:198:73 + 27: as core::future::future::Future>::poll + at /greptime/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tracing-0.1.40/src/instrument.rs:321:9 + 28: ::plan::{{closure}} + at /greptime/codes/greptime/procedure-traits/src/query/src/planner.rs:195:5 +... +``` + +### Metasrv + +When the GreptimeDB cluster experiences node online/offline events, +region migration, schema changes, etc., +metasrv will record corresponding logs. +Therefore, in addition to error logs from each component, +it is also recommended to monitor the following metasrv log keywords: + +#### Metasrv Leader Step Down/Election + +```bash +// Error level, indicates current leader stepped down, new election will follow. Note the {:?} part is the leader identifier +"Leader :{:?} step down" +``` + +#### Region Lease Renewal Failure + +```bash +// Warning level, indicates a region lease renewal was denied. Region lease requests will be rejected when the region is not properly closed/scheduled on a datanode. +Denied to renew region lease for datanode: {datanode_id}, region_id: {region_id} +``` + +```bash +// Info level, datanode receives lease renewal failure and attempts to close target region +Closing staled region: +``` + +#### Region Failover + +```bash +// Warning level, detects some regions failed Phi health check, need to execute failover operation. Region IDs will be printed after the colon +Detects region failures: + +// A region migration failed +Failed to wait region migration procedure + +// Info level, when maintenance mode is enabled, failover procedure will be skipped +Maintenance mode is enabled, skip failover +``` + +#### Region Migration + +```bash +// Info level, indicates a region starts migration. Region information will be printed after the log +Starting region migration procedure + +// Error level, a region migration failed +Failed to wait region migration procedure +``` + +#### Procedure + +Metasrv internally uses a component called "procedure" to execute distributed operations. You can monitor error logs from this component: + +```bash +Failed to execute procedure +``` + +#### Flow Creation Failure + +When flow creation fails, the failure reason can usually be seen in procedure error logs. Logs may contain the following keywords: + +```bash +Failed to execute procedure metasrv-procedure:: CreateFlow +``` + +### Datanode + +#### Compaction + +When compaction starts and ends, datanode will log the following information: + +```bash +2025-05-16T06:01:08.794415Z INFO mito2::compaction::task: Compacted SST files, region_id: 4612794875904(1074, 0), input: [FileMeta { region_id: 4612794875904(1074, 0), file_id: FileId(a29500fb-cae0-4f3f-8376-cb3f14653378), time_range: (1686455010000000000::Nanosecond, 1686468410000000000::Nanosecond), level: 0, file_size: 45893329, available_indexes: [], index_file_size: 0, num_rows: 5364000, num_row_groups: 53, sequence: Some(114408000) }, FileMeta { region_id: 4612794875904(1074, 0), file_id: FileId(a31dcb1b-19ae-432f-8482-9e1b7db7b53b), time_range: (1686468420000000000::Nanosecond, 1686481820000000000::Nanosecond), level: 0, file_size: 45900506, available_indexes: [], index_file_size: 0, num_rows: 5364000, num_row_groups: 53, sequence: Some(119772000) }], output: [FileMeta { region_id: 4612794875904(1074, 0), file_id: FileId(5d105ca7-9e3c-4298-afb3-e85baae3b2e8), time_range: (1686455010000000000::Nanosecond, 1686481820000000000::Nanosecond), level: 1, file_size: 91549797, available_indexes: [], index_file_size: 0, num_rows: 10728000, num_row_groups: 105, sequence: Some(119772000) }], window: Some(86400), waiter_num: 0, merge_time: 3.034328293s +``` + +```bash +2025-05-16T06:01:08.805366Z INFO mito2::request: Successfully compacted region: 4612794875904(1074, 0) +``` + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/monitor-cluster-with-prometheus.md b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/monitor-cluster-with-prometheus.md new file mode 100644 index 0000000000..1ad30f86f8 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/monitor-cluster-with-prometheus.md @@ -0,0 +1,116 @@ +--- +keywords: [cluster, monitoring, Prometheus] +description: Learn how to monitor a GreptimeDB cluster using an existing Prometheus instance in Kubernetes, including configuration steps and Grafana dashboard setup. +--- + +# Prometheus-Monitoring GreptimeDB Cluster + +Before reading this document, ensure you understand how to [deploy a GreptimeDB cluster on Kubernetes](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md). + +It is recommended to use [self-monitoring mode](cluster-monitoring-deployment.md) to monitor GreptimeDB cluster, +as it's simple to set up and provides out-of-the-box Grafana dashboards. +However, if you already have a Prometheus instance deployed in your Kubernetes cluster and want to integrate +GreptimeDB cluster metrics into it, follow the steps below. + + +## Check the Prometheus Instance Configuration + +Ensure you have deployed the Prometheus Operator and created a Prometheus instance. For example, you can use [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) to deploy the Prometheus stack. Refer to its [official documentation](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) for more details. + +When deploying the Prometheus instance, ensure you set the labels used for scraping GreptimeDB cluster metrics. +For example, your existing Prometheus instance may contain the following configuration: + +```yaml +apiVersion: monitoring.coreos.com/v1 +kind: PodMonitor +metadata: + name: greptime-podmonitor + namespace: default +spec: + selector: + matchLabels: + release: prometheus + # other configurations... +``` + +When the `PodMonitor` is deployed, +the Prometheus Operator continuously watches for pods in the `default` namespace that match all labels defined in `spec.selector.matchLabels` (in this example, `release: prometheus`). + +## Enable `prometheusMonitor` for GreptimeDB Cluster + +When deploying a GreptimeDB cluster using a Helm Chart, +enable the `prometheusMonitor` field in your `values.yaml` file. For example: + +```yaml +prometheusMonitor: + # Enable Prometheus monitoring - this will create PodMonitor resources + enabled: true + # Configure scrape interval + interval: "30s" + # Configure labels + labels: + release: prometheus +``` + +**Important:** The `labels` field value (`release: prometheus`) +must match the `matchLabels` field used to create the Prometheus instance, +otherwise metrics collection won't work properly. + +After configuring `prometheusMonitor`, +the GreptimeDB Operator will automatically create `PodMonitor` resources and import metrics into Prometheus at the specified `interval`. +You can check the `PodMonitor` resources with: + +``` +kubectl get podmonitors.monitoring.coreos.com -n ${namespace} +``` + + +:::note +If you're not using a Helm Chart, you can manually configure Prometheus monitoring in the `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 + backendStorage: + etcd: + endpoints: + - "etcd.etcd-cluster.svc.cluster.local:2379" + datanode: + replicas: 1 + prometheusMonitor: + enabled: true + interval: "30s" + labels: + release: prometheus +``` + +::: + +## Grafana Dashboards + +You need to deploy Grafana by yourself, +then import the dashboards. + +### Add Data Sources + +After deploying Grafana, +refer to Grafana's [data sources](https://grafana.com/docs/grafana/latest/datasources/) documentation to add the following two type data sources: + +- **Prometheus**: Name it `metrics`. This data source connects to your Prometheus instance, which collects GreptimeDB cluster monitoring metrics. Use your Prometheus instance URL as the connection URL. +- **MySQL**: Name it `information-schema`. This data source connects to your GreptimeDB cluster to access cluster metadata via the SQL protocol. If you have deployed GreptimeDB following the [Deploy a GreptimeDB Cluster on Kubernetes](/user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster.md) guide, use `${cluster-name}-frontend.${namespace}.svc.cluster.local:4002` as the server address with database `information_schema`. + +### Import Dashboards + +The [GreptimeDB Cluster Metrics Dashboard](https://github.com/GreptimeTeam/greptimedb/tree/VAR::greptimedbVersion/grafana/dashboards/metrics/cluster) uses the `metrics` and `information-schema` data sources to display GreptimeDB cluster metrics. + +Refer to Grafana's [Import dashboards](https://grafana.com/docs/grafana/latest/dashboards/build-dashboards/import-dashboards/) documentation to learn how to import dashboards. diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/overview.md b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/overview.md new file mode 100644 index 0000000000..35ccd3b86c --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/overview.md @@ -0,0 +1,15 @@ +--- +keywords: [GreptimeDB monitoring, metrics export, tracing, database monitoring] +description: Overview of monitoring methods for GreptimeDB, including exporting metrics and tracing. +--- + +import DocCardList from '@theme/DocCardList'; + +# Monitoring + +Effective database administration relies heavily on monitoring. +You can monitor GreptimeDB using the following methods: + + + + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/runtime-info.md b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/runtime-info.md new file mode 100644 index 0000000000..3af86cb989 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/runtime-info.md @@ -0,0 +1,31 @@ +--- +keywords: [GreptimeDB runtime information, system metadata, cluster topology, table regions distribution, SQL queries] +description: Provides access to system metadata through the INFORMATION_SCHEMA database, including cluster topology and table regions distribution. Examples of SQL queries to retrieve region IDs and distribution are included. +--- + +# Runtime Information + +The `INFORMATION_SCHEMA` database provides access to system metadata, such as the name of a database or table, the data type of a column, etc. + +* Find the topology information of the cluster though [CLUSTER_INFO](/reference/sql/information-schema/cluster-info.md) table. +* Find the table regions distribution though [PARTITIONS](/reference/sql/information-schema/partitions.md) and [REGION_PEERS](/reference/sql/information-schema/region-peers.md) tables. + +For example, find all the region id of a table: + +```sql +SELECT greptime_partition_id FROM PARTITIONS WHERE table_name = 'monitor' +``` + +Find the distribution of all regions in a table: + +```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 +``` + +For more information about the `INFORMATION_SCHEMA` database, +Please read the [reference](/reference/sql/information-schema/overview.md). diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/slow-query.md b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/slow-query.md new file mode 100644 index 0000000000..8ebd0a5cf3 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/slow-query.md @@ -0,0 +1,71 @@ +--- +keywords: [GreptimeDB slow query, slow query log, slow query monitoring, slow query configuration] +description: Guide on configuring and using slow query logging in GreptimeDB for monitoring. +--- + +# Slow Query (Experimental) + +GreptimeDB provides a slow query log to help you find and fix slow queries. By default, the slow queries are output to the system table `greptime_private.slow_queries` with `30s` threshold and `1.0` sample ratio with `30d` TTL. + +The schema of the `greptime_private.slow_queries` table is as follows: + +```sql ++--------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------+----------------------+------+------+---------+---------------+ +| cost | UInt64 | | NO | | FIELD | +| threshold | UInt64 | | NO | | FIELD | +| query | String | | NO | | FIELD | +| is_promql | Boolean | | NO | | FIELD | +| timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| promql_range | UInt64 | | NO | | FIELD | +| promql_step | UInt64 | | NO | | FIELD | +| promql_start | TimestampMillisecond | | NO | | FIELD | +| promql_end | TimestampMillisecond | | NO | | FIELD | ++--------------+----------------------+------+------+---------+---------------+ +``` + +- `cost`: The cost of the query in milliseconds. +- `threshold`: The threshold of the query in milliseconds. +- `query`: The query string. +- `is_promql`: Whether the query is a PromQL query. +- `timestamp`: The timestamp of the query. +- `promql_range`: The range of the query. Only used when `is_promql` is `true`. +- `promql_step`: The step of the query. Only used when `is_promql` is `true`. +- `promql_start`: The start time of the query. Only used when `is_promql` is `true`. +- `promql_end`: The end time of the query. Only used when `is_promql` is `true`. + +In cluster mode, you can configure the slow query in frontend configs (same as in standalone mode), for example: + +```toml +[slow_query] +## Whether to enable slow query log. +enable = true + +## The record type of slow queries. It can be `system_table` or `log`. +## If `system_table` is selected, the slow queries will be recorded in a system table `greptime_private.slow_queries`. +## If `log` is selected, the slow queries will be logged in a log file `greptimedb-slow-queries.*`. +record_type = "system_table" + +## The threshold of slow query. It can be human readable time string, for example: `10s`, `100ms`, `1s`. +threshold = "30s" + +## The sampling ratio of slow query log. The value should be in the range of (0, 1]. For example, `0.1` means 10% of the slow queries will be logged and `1.0` means all slow queries will be logged. +sample_ratio = 1.0 + +## The TTL of the `slow_queries` system table. Default is `30d` when `record_type` is `system_table`. +ttl = "30d" +``` + +If you use the Helm chart to deploy GreptimeDB, you can configure the slow query in the `values.yaml` file, for example: + +```yaml +slowQuery: + enable: true + recordType: "system_table" + threshold: "30s" + sampleRatio: "1.0" + ttl: "30d" +``` + +If you use `log` as the record type, the slow queries will be logged in a log file `greptimedb-slow-queries.*`. By default, the log file is located in the `${data_home}/logs` directory. diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/standalone-monitoring.md b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/standalone-monitoring.md new file mode 100644 index 0000000000..48c0bbb459 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/standalone-monitoring.md @@ -0,0 +1,62 @@ +--- +keywords: [standalone monitoring, GreptimeDB, metrics, Grafana] +description: Guide to monitor GreptimeDB standalone instance using Prometheus metrics and Grafana. +--- + +# Standalone Monitoring + +GreptimeDB standalone provides a `/metrics` endpoint on the HTTP port (default `4000`) that exposes [Prometheus metrics](/reference/http-endpoints.md#metrics). + +## Monitoring configuration + +You can configure GreptimeDB to export metrics to GreptimeDB itself or to an external Prometheus instance. + +### Internal Metrics Storage + +Configuring GreptimeDB to store its own metrics internally is convenient and recommended for self-monitoring, +it also enables SQL-based querying and analysis. + +To enable self-monitoring, configure the `export_metrics` section in your TOML configuration file: + +```toml +[export_metrics] +enable = true +# Metrics collection interval +write_interval = "30s" +[export_metrics.self_import] +db = "greptime_metrics" +``` + +This configuration: +- Collects and writes metrics every 30 seconds. +- Exports metrics to the `greptime_metrics` database within GreptimeDB. Ensure the `greptime_metrics` database [is created](/reference/sql/create.md#create-database) before exporting metrics. + +### Export metrics to Prometheus + +For environments with existing Prometheus infrastructure, +GreptimeDB can export metrics via the Prometheus remote write protocol. + +To do this, configure the `export_metrics` section in your TOML configuration file with the `remote_write` option: + +```toml +[export_metrics] +enable=true +write_interval = "30s" +[export_metrics.remote_write] +# URL specified by Prometheus Remote-Write protocol +url = "https://your/remote_write/endpoint" +# Some optional HTTP parameters, such as authentication information +headers = { Authorization = {{Authorization}} } +``` + +This configuration: +- Sets the export interval to 30 seconds +- Specifies the Prometheus remote write URL, which should point to your Prometheus instance +- Optionally includes HTTP headers for the remote write URL, such as authentication information + +## Grafana Dashboard Integration + +GreptimeDB provides pre-built Grafana dashboards for monitoring standalone deployments. +You can access the dashboard JSON files from the [GreptimeDB repository](https://github.com/GreptimeTeam/greptimedb/tree/VAR::greptimedbVersion/grafana/dashboards/metrics/standalone). + + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/tracing.md b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/tracing.md new file mode 100644 index 0000000000..2d0db63c89 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/monitoring/tracing.md @@ -0,0 +1,116 @@ +--- +keywords: [GreptimeDB tracing, Jaeger, distributed tracing, tracing configuration, tracing sampling rates] +description: Guide on using distributed tracing in GreptimeDB with Jaeger. Includes steps for deploying Jaeger, configuring GreptimeDB for tracing, obtaining trace information, and configuring tracing sampling rates. +--- + +# Tracing + +GreptimeDB supports distributed tracing. GreptimeDB exports all collected spans using the gRPC-based OTLP protocol. Users can use [Jaeger](https://www.jaegertracing.io/), [Tempo](https://grafana.com/oss/tempo/) and other OTLP protocol backends that support gRPC to collect the span instrument by GreptimeDB. + +In the [logging section](/user-guide/deployments-administration/configuration.md#logging-options) in the configuration, there are descriptions of configuration items related to tracing, [standalone.example.toml](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/standalone.example.toml) provide a reference configuration in the logging section. + +## Tutorial: Use Jaeger to trace GreptimeDB + +[Jaeger](https://www.jaegertracing.io/) is an open source, end-to-end distributed tracing system, originally developed and open sourced by Uber. Its goal is to help developers monitor and debug the request flow in complex microservice architectures. + +Jaeger supports gRPC-based OTLP protocol, so GreptimeDB can export trace data to Jaeger. The following tutorial shows you how to deploy and use Jaeger to track GreptimeDB. + +### Step 1: Deploy Jaeger + +Start a Jaeger instance using the `all-in-one` docker image officially provided by jaeger: + +```bash +docker run --rm -d --name jaeger \ + -e COLLECTOR_ZIPKIN_HOST_PORT=:9411 \ + -p 6831:6831/udp \ + -p 6832:6832/udp \ + -p 5778:5778 \ + -p 16686:16686 \ + -p 4317:4317 \ + -p 4318:4318 \ + -p 14250:14250 \ + -p 14268:14268 \ + -p 14269:14269 \ + -p 9411:9411 \ + jaegertracing/all-in-one:latest +``` + +### Step 2: Deploy GreptimeDB + +Write configuration files to allow GreptimeDB to perform tracing. Save the following configuration items as the file `config.toml` + +```Toml +[logging] +enable_otlp_tracing = true +``` + +Then start GreptimeDB using standalone mode + +```bash +greptime standalone start -c config.toml +``` + +Refer to the chapter [MySQL](/user-guide/protocols/mysql.md) on how to connect to GreptimeDB. Run the following SQL statement in MySQL Client: + +```sql +CREATE TABLE host ( + ts timestamp(3) time index, + host STRING PRIMARY KEY, + val BIGINT, +); + +INSERT INTO TABLE host VALUES + (0, 'host1', 0), + (20000, 'host2', 5); + +SELECT * FROM host ORDER BY ts; + +DROP TABLE host; +``` + +### Step 3: Obtain trace information in Jaeger + +1. Go to http://127.0.0.1:16686/ and select the Search tab. +2. Select the `greptime-standalone` service in the service drop-down list. +3. Click **Find Traces** to display trace information. + +![JaegerUI](/jaegerui.png) + +![Select-tracing](/select-tracing.png) + +## Guide: How to configure tracing sampling rate + +GreptimeDB provides many protocols and interfaces for data insertion, query and other functions. You can collect the calling chains of each operation through tracing. However, for some high-frequency operations, collecting all tracing of the operation may be unnecessary and waste storage space. At this time, you can use `tracing_sample_ratio` to set the sampling rate of tracing for various operations, which can greatly reduce the number of exported tracing and facilitate system observation. + +All tracing within GreptimeDB is classified according to the protocol it is connected to and the corresponding operations of that protocol: + +| **protocol** | **request_type** | +|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| grpc | inserts / query.sql / query.logical_plan / query.prom_range / query.empty / ddl.create_database / ddl.create_table / ddl.alter / ddl.drop_table / ddl.truncate_table / ddl.empty / deletes / row_inserts / row_deletes | +| mysql | | +| postgres | | +| otlp | metrics / traces | +| opentsdb | | +| influxdb | write_v1 / write_v2 | +| prometheus | remote_read / remote_write / format_query / instant_query / range_query / labels_query / series_query / label_values_query | +| http | sql / promql + +You can configure different tracing sampling rates through `tracing_sample_ratio`. + +```toml +[logging] +enable_otlp_tracing = true +[logging.tracing_sample_ratio] +default_ratio = 0.0 +[[logging.tracing_sample_ratio.rules]] +protocol = "mysql" +ratio = 1.0 +[[logging.tracing_sample_ratio.rules]] +protocol = "grpc" +request_types = ["inserts"] +ratio = 0.3 +``` + +The above configuration formulates two sampling rules and sets a default sampling rate. GreptimeDB will start matching from the first one according to the sampling rules, and use the first matching sampling rule as the sampling rate of the tracing. If no rule matches, `default_ratio` will be used as the default sampling rate. The range of sampling rate is `[0.0, 1.0]`, `0.0` means not sampling, `1.0` means sampling all tracing. + +For example, according to the rules provided above, all calls accessed using the mysql protocol will be sampled, data inserted using grpc will be sampled 30%, and all remaining tracing will not be sampled. \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/overview.md b/versioned_docs/version-1.0/user-guide/deployments-administration/overview.md new file mode 100644 index 0000000000..04478d7905 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/overview.md @@ -0,0 +1,59 @@ +--- +keywords: [deployment, configuration, authentication, Kubernetes, Android, capacity planning, GreptimeCloud] +description: Overview of deploying GreptimeDB, including configuration, authentication, Kubernetes deployment, running on Android, capacity planning, and using GreptimeCloud. +--- + +# Deployments & Administration + +GreptimeDB can be deployed and managed either on your own infrastructure or through GreptimeCloud. +This guide provides an overview of deployment strategies, configuration, monitoring, and administration. + +## GreptimeDB Architecture + +Before diving into the deployment and administration of GreptimeDB, +it's important to understand its [architecture](/user-guide/concepts/architecture.md). + +## Self-Managed GreptimeDB Deployment + +This section outlines the key aspects of deploying and administering GreptimeDB in your own environment. + +### Configuration and Deployment + +- **Configuration:** Before deployment, [check the configuration](configuration.md) to suit your requirements, including protocol settings, storage options, and more. +- **Authentication:** By default, authentication is not enabled. Learn how to [enable and configure authentication](./authentication/overview.md) for secure deployments. +- **Kubernetes Deployment:** Follow the [step-by-step guide](./deploy-on-kubernetes/overview.md) to deploy GreptimeDB on Kubernetes. +- **Capacity Planning:** Ensure your deployment can handle your workload by [planning for capacity](/user-guide/deployments-administration/capacity-plan.md). + +### Component Management + +- **Cluster Failover:** Set up [Remote WAL](./wal/remote-wal/configuration.md) for high availability. +- **Manage Metadata:** Set up [Metadata Storage](./manage-data/overview.md) for GreptimeDB. + +### Monitoring + +- **Monitoring:** [Monitor cluster's health and performance](./monitoring/overview.md) through metrics, tracing, and runtime information. + +### Data Management and Performance + +- **Data Management:** [Manage your data](/user-guide/deployments-administration/manage-data/overview.md) to prevent data loss, reduce costs, and optimize performance. +- **Performance Tuning:** Review [performance tuning tips](/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md) and learn how to [design your table schema](/user-guide/deployments-administration/performance-tuning/design-table.md) for optimal efficiency. + +### Disaster Recovery + +- **Disaster Recovery:** Implement [disaster recovery strategies](/user-guide/deployments-administration/disaster-recovery/overview.md) to protect your data and ensure business continuity. + +### Additional Topics + +- **Run on Android:** Learn how to [run GreptimeDB on Android devices](run-on-android.md). +- **Upgrade:** Follow the [upgrade guide](/user-guide/deployments-administration/upgrade.md) to keep the version of GreptimeDB up to date. + +## GreptimeCloud + +For a fully managed experience, +consider [GreptimeCloud](https://greptime.cloud). +GreptimeCloud enables you to deploy, monitor, +and scale GreptimeDB instances effortlessly, with built-in metrics monitoring and alerting. +It is designed to provide a scalable, efficient, +and serverless solution for time-series data platforms and Prometheus backends. + +For more details, refer to the [GreptimeCloud documentation](https://docs.greptime.com/nightly/greptimecloud/overview). diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/performance-tuning/design-table.md b/versioned_docs/version-1.0/user-guide/deployments-administration/performance-tuning/design-table.md new file mode 100644 index 0000000000..c4af256692 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/performance-tuning/design-table.md @@ -0,0 +1,386 @@ +--- +keywords: [table schema, data model, cardinality, tag columns, field columns, time index, primary key, inverted index, full-text index, skipping index, append-only tables, data updating, wide table, distributed tables, partitioning] +description: Learn how to design your table schema in GreptimeDB for optimal performance and query efficiency +--- + +# Design Your Table Schema + +The design of your table schema significantly impacts both write and query performance. +Before writing data, +it is crucial to understand the data types, scale, and common queries relevant to your business, +then model the data accordingly. +This document provides a comprehensive guide on GreptimeDB's data model and table schema design for various scenarios. + +## Understanding GreptimeDB's Data Model + +Before proceeding, please review the GreptimeDB [Data Model Documentation](/user-guide/concepts/data-model.md). + +## Basic Concepts + +### Cardinality + +**Cardinality**: Refers to the number of unique values in a dataset. It can be classified as "high cardinality" or "low cardinality": + +- **Low Cardinality**: Low cardinality columns usually have constant values. + The total number of unique values usually no more than 10 thousand. + For example, `namespace`, `cluster`, `http_method` are usually low cardinality. +- **High Cardinality**: High cardinality columns contain a large number of unique values. + For example, `trace_id`, `span_id`, `user_id`, `uri`, `ip`, `uuid`, `request_id`, table auto increment id, timestamps are usually high cardinality. + +### Column Types + +In GreptimeDB, columns are categorized into three semantic types: `Tag`, `Field`, and `Timestamp`. +The timestamp usually represents the time of data sampling or the occurrence time of logs/events. +GreptimeDB uses the `TIME INDEX` constraint to identify the `Timestamp` column. +So the `Timestamp` column is also called the `TIME INDEX` column. +If you have multiple columns with timestamp data type, you can only define one as `TIME INDEX` and others as `Field` columns. + +In GreptimeDB, tag columns are optional. The main purposes of tag columns include: + +1. Defining the ordering of data in storage. + GreptimeDB reuses the `PRIMARY KEY` constraint to define tag columns and the ordering of tags. + Unlike traditional databases, GreptimeDB defines time-series by the primary key. + Tables in GreptimeDB sort rows in the order of `(primary key, timestamp)`. + This improves the locality of data with the same tags. + If there are no tag columns, GreptimeDB sorts rows by timestamp. +2. Identifying a unique time-series. + When the table is not append-only, GreptimeDB can deduplicate rows by timestamp under the same time-series (primary key). +3. Smoothing migration from other TSDBs that use tags or labels. + + +## Primary key + +### Primary key is optional + +Bad primary key or index may significantly degrade performance. +Generally you can create an append-only table without a primary key since ordering data by timestamp is sufficient for many workloads. +It can also serve as a baseline. + +```sql +CREATE TABLE http_logs ( + access_time TIMESTAMP TIME INDEX, + application STRING, + remote_addr STRING, + http_status STRING, + http_method STRING, + http_refer STRING, + user_agent STRING, + request_id STRING, + request STRING, +) with ('append_mode'='true'); +``` + +The `http_logs` table is an example for storing HTTP server logs. + +- The `'append_mode'='true'` option creates the table as an append-only table. + This ensures a log doesn't override another one with the same timestamp. +- The table sorts logs by time so it is efficient to search logs by time. + + +### When to use primary key + +You can use primary key when there are suitable low cardinality columns and one of the following conditions is met: + +- Most queries can benefit from the ordering. +- You need to deduplicate (including delete) rows by the primary key and time index. + +For example, if you always only query logs of a specific application, you may set the `application` column as primary key (tag). + +```sql +SELECT message FROM http_logs WHERE application = 'greptimedb' AND access_time > now() - '5 minute'::INTERVAL; +``` + +The number of applications is usually limited. Table `http_logs_v2` uses `application` as the primary key. +It sorts logs by application so querying logs under the same application is faster as it only has to scan a small number of rows. Setting tags may also reduce disk space usage as it improves the locality of data. + +```sql +CREATE TABLE http_logs_v2 ( + access_time TIMESTAMP TIME INDEX, + application STRING, + remote_addr STRING, + http_status STRING, + http_method STRING, + http_refer STRING, + user_agent STRING, + request_id STRING, + request STRING, + PRIMARY KEY(application), +) with ('append_mode'='true'); +``` + + +In order to improve sort and deduplication speed under time-series workloads, GreptimeDB buffers and processes rows by time-series internally. +So it doesn't need to compare the primary key for each row repeatedly. +This can be a problem if the tag column has high cardinality: + +1. Performance degradation since the database can't batch rows efficiently. +2. It may increase memory and CPU usage as the database has to maintain the metadata for each time-series. +3. Deduplication may be too expensive. + + +So you must not use high cardinality column as the primary key or put too many columns in the primary key. Currently, the recommended number of values for the primary key is no more than 100 thousand. A long primary key will negatively affect the insert performance and enlarge the memory footprint. A primary key with no more than 5 columns is recommended. + + +Recommendations for tags: + +- Low cardinality columns that occur in `WHERE`/`GROUP BY`/`ORDER BY` frequently. + These columns usually remain constant. + For example, `namespace`, `cluster`, or an AWS `region`. +- No need to set all low cardinality columns as tags since this may impact the performance of ingestion and querying. +- Typically use short strings and integers for tags, avoiding `FLOAT`, `DOUBLE`, `TIMESTAMP`. +- Never set high cardinality columns as tags if they change frequently. + For example, `trace_id`, `span_id`, `user_id` must not be used as tags. + GreptimeDB works well if you set them as fields instead of tags. + + +## Index + +Besides primary key, you can also use index to accelerate specific queries on demand. + +### Inverted Index + +GreptimeDB supports inverted index that may speed up filtering low cardinality columns. +When creating a table, you can specify the [inverted index](/contributor-guide/datanode/data-persistence-indexing.md#inverted-index) columns using the `INVERTED INDEX` clause. +For example, `http_logs_v3` adds an inverted index for the `http_method` column. + +```sql +CREATE TABLE http_logs_v3 ( + access_time TIMESTAMP TIME INDEX, + application STRING, + remote_addr STRING, + http_status STRING, + http_method STRING INVERTED INDEX, + http_refer STRING, + user_agent STRING, + request_id STRING, + request STRING, + PRIMARY KEY(application), +) with ('append_mode'='true'); +``` + +The following query can use the inverted index on the `http_method` column. + +```sql +SELECT message FROM http_logs_v3 WHERE application = 'greptimedb' AND http_method = `GET` AND access_time > now() - '5 minute'::INTERVAL; +``` + +Inverted index supports the following operators: +- `=` +- `<` +- `<=` +- `>` +- `>=` +- `IN` +- `BETWEEN` +- `~` + + +### Skipping Index + +For high cardinality columns like `trace_id`, `request_id`, using a [skipping index](/user-guide/manage-data/data-index.md#skipping-index) is more appropriate. +This method has lower storage overhead and resource usage, particularly in terms of memory and disk consumption. + +Example: + +```sql +CREATE TABLE http_logs_v4 ( + access_time TIMESTAMP TIME INDEX, + application STRING, + remote_addr STRING, + http_status STRING, + http_method STRING INVERTED INDEX, + http_refer STRING, + user_agent STRING, + request_id STRING SKIPPING INDEX, + request STRING, + PRIMARY KEY(application), +) with ('append_mode'='true'); +``` + +The following query can use the skipping index to filter the `request_id` column. + +```sql +SELECT message FROM http_logs_v4 WHERE application = 'greptimedb' AND request_id = `25b6f398-41cf-4965-aa19-e1c63a88a7a9` AND access_time > now() - '5 minute'::INTERVAL; +``` + +However, note that the query capabilities of the skipping index are generally inferior to those of the inverted index. +Skipping index can't handle complex filter conditions and may have a lower filtering performance on low cardinality columns. It only supports the equal operator. + + +### Full-Text Index + +For unstructured log messages that require tokenization and searching by terms, GreptimeDB provides full-text index. + +For example, the `raw_logs` table stores unstructured logs in the `message` field. + +```sql +CREATE TABLE IF NOT EXISTS `raw_logs` ( + message STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', case_sensitive = 'false'), + ts TIMESTAMP(9) NOT NULL, + TIME INDEX (ts), +) with ('append_mode'='true'); +``` + +The `message` field is full-text indexed using the `FULLTEXT INDEX` option. +See [fulltext column options](/reference/sql/create.md#fulltext-column-option) for more information. + +Storing and querying structured logs usually have better performance than unstructured logs with full-text index. +It's recommended to [use Pipeline](/user-guide/logs/quick-start.md#create-a-pipeline) to convert logs into structured logs. + + +### When to use index + +Index in GreptimeDB is flexible and powerful. +You can create an index for any column, no matter if the column is a tag or a field. +It's meaningless to create additional index for the timestamp column. +Generally you don't need to create indexes for all columns. +Maintaining indexes may introduce additional cost and stall ingestion. +A bad index may occupy too much disk space and make queries slower. + + +You can use a table without additional index as a baseline. +There is no need to create an index for the table if the query performance is already acceptable. +You can create an index for a column when: + +- The column occurs in the filter frequently. +- Filtering the column without an index isn't fast enough. +- There is a suitable index for the column. + + +The following table lists the suitable scenarios of all index types. + +| | Inverted Index | Full-Text Index | Skip Index| +| ----- | ----------- | ------------- |------------- | +| Suitable Scenarios | - Filtering low cardinality columns | - Text content search | - Precise filtering high cardinality columns | +| Creation Method | - Specified using `INVERTED INDEX` |- Specified using `FULLTEXT INDEX` in column options | - Specified using `SKIPPING INDEX` in column options | + + +## Deduplication + +If deduplication is necessary, you can use the default table options, which sets the `append_mode` to `false` and enables deduplication. + +```sql +CREATE TABLE IF NOT EXISTS system_metrics ( + host STRING, + cpu_util DOUBLE, + memory_util DOUBLE, + disk_util DOUBLE, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY(host), + TIME INDEX(ts) +); +``` + +GreptimeDB deduplicates rows by the same primary key and timestamp if the table isn't append-only. +For example, the `system_metrics` table removes duplicate rows by `host` and `ts`. + +### Data updating and merging + +GreptimeDB supports two different strategies for deduplication: `last_row` and `last_non_null`. +You can specify the strategy by the `merge_mode` table option. + +GreptimeDB uses an LSM Tree-based storage engine, +which does not overwrite old data in place but allows multiple versions of data to coexist. +These versions are merged during the query process. +The default merge behavior is `last_row`, meaning the most recently inserted row takes precedence. + +![merge-mode-last-row](/merge-mode-last-row.png) + +In `last_row` merge mode, +the latest row is returned for queries with the same primary key and time value, +requiring all Field values to be provided during updates. + +For scenarios where only specific Field values need updating while others remain unchanged, +the `merge_mode` option can be set to `last_non_null`. +This mode retains the latest non-null value for each field during queries, +allowing updates to provide only the values that need to change. + +![merge-mode-last-non-null](/merge-mode-last-non-null.png) + +The `last_non_null` merge mode is the default for tables created automatically via the InfluxDB line protocol, +aligning with InfluxDB's update behavior. + +The `last_row` merge mode doesn't have to check each individual field value so it is usually faster than the `last_non_null` mode. +Note that `merge_mode` cannot be set for Append-Only tables, as they do not perform merges. + +### When to use append-only tables + +If you don't need the following features, you can use append-only tables: + +- Deduplication +- Deletion + +GreptimeDB implements `DELETE` via deduplicating rows so append-only tables don't support deletion now. +Deduplication requires more computation and restricts the parallelism of ingestion and querying. +Using append-only tables usually has better query performance. + + +## Wide Table vs. Multiple Tables + +In monitoring or IoT scenarios, multiple metrics are often collected simultaneously. +We recommend placing metrics collected simultaneously into a single table to improve read/write throughput and data compression efficiency. + +![wide_table](/wide_table.png) + +Although Prometheus uses single-value model for metrics, GreptimeDB's Prometheus Remote Storage protocol supports sharing a wide table for metrics at the underlying layer through the [Metric Engine](/contributor-guide/datanode/metric-engine.md). + +## Distributed Tables + +GreptimeDB supports partitioning data tables to distribute read/write hotspots and achieve horizontal scaling. + +### Two misunderstandings about distributed tables + +As a time-series database, GreptimeDB automatically partitions data based on the TIME INDEX column at the storage layer. +Therefore, it is unnecessary and not recommended for you to partition data by time +(e.g., one partition per day or one table per week). + +Additionally, GreptimeDB is a columnar storage database, +so partitioning a table refers to horizontal partitioning by rows, +with each partition containing all columns. + +### When to Partition and Determining the Number of Partitions + +A table can utilize all the resources in the machine, especially during query. +Partitioning a table may not always improve the performance: + +- A distributed query plan isn't always as efficient as a local query plan. +- Distributed query may introduce additional data transmission across the network. + + +There is no need to partition a table unless a single machine isn't enough to serve the table. +For example: + +- There is not enough local disk space to store the data or to cache the data when using object stores. +- You need more CPU cores to improve the query performance or more memory for costly queries. +- The disk throughput becomes the bottleneck. +- The ingestion rate is larger than the throughput of a single node. + +GreptimeDB releases a [benchmark report](https://github.com/GreptimeTeam/greptimedb/tree/VAR::greptimedbVersion/docs/benchmarks/tsbs) with each major version update, +detailing the ingestion throughput of a single partition. +Use this report alongside your target scenario to estimate if the write volume approaches the single partition's limit. + + +To estimate the total number of partitions, +consider the write throughput and reserve an additional 50% resource of CPU +to ensure query performance and stability. Adjust this ratio as necessary. +You can reserve more CPU cores if there are more queries. + + +### Partitioning Methods + +GreptimeDB employs expressions to define partitioning rules. +For optimal performance, +select partition keys that are evenly distributed, stable, and align with query conditions. + +Examples include: + +- Partitioning by the prefix of a trace id. +- Partitioning by data center name. +- Partitioning by business name. + +The partition key should closely match the query conditions. +For instance, if most queries target data from a specific data center, +using the data center name as a partition key is appropriate. +If the data distribution is not well understood, perform aggregate queries on existing data to gather relevant information. + +For more details, refer to the [table partition guide](/user-guide/deployments-administration/manage-data/table-sharding.md#partition). diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md b/versioned_docs/version-1.0/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md new file mode 100644 index 0000000000..ff8adc26fa --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/performance-tuning/performance-tuning-tips.md @@ -0,0 +1,163 @@ +--- +keywords: [GreptimeDB performance tuning, query optimization, caching, primary keys, append-only tables, metrics] +description: Tips for tuning GreptimeDB performance, including query optimization, caching, enlarging cache size, primary keys, and using append-only tables. Also covers metrics for diagnosing query and ingestion issues. +--- + +# Performance Tuning Tips + +A GreptimeDB instance's default configuration may not fit all use cases. It's important to tune the database configurations and usage according to the scenario. + +GreptimeDB provides various metrics to help monitor and troubleshoot performance issues. The official repository provides [Grafana dashboard templates](https://github.com/GreptimeTeam/greptimedb/tree/main/grafana) for both standalone and cluster modes. + +## Query + +### ANALYZE QUERY + +GreptimeDB supports query analysis functionality. +Using the `EXPLAIN ANALYZE [VERBOSE] ` statement, you can view step-by-step query execution times. + +### Metrics + +The following metrics help diagnose query performance issues: +| Metric | Type | Description | +|---|---|---| +| greptime_mito_read_stage_elapsed_bucket | histogram | The elapsed time of different phases of a query in the storage engine. | +| greptime_mito_cache_bytes | gauge | Size of cached contents | +| greptime_mito_cache_hit | counter | Total count of cache hit | +| greptime_mito_cache_miss | counter | Total count of cache miss | + + +### Enlarging cache size + +You can monitor the `greptime_mito_cache_bytes` and `greptime_mito_cache_miss` metrics to determine if you need to increase the cache size. The `type` label in these metrics indicates the type of cache. + +If the `greptime_mito_cache_miss` metric is consistently high and increasing, or if the `greptime_mito_cache_bytes` metric reaches the cache capacity, you may need to adjust the cache size configurations of the storage engine. + + +Here is an example: + + +```toml +[[region_engine]] +[region_engine.mito] +# Cache size for the write cache. The `type` label value for this cache is `file`. +write_cache_size = "10G" +# Cache size for SST metadata. The `type` label value for this cache is `sst_meta`. +sst_meta_cache_size = "128MB" +# Cache size for vectors and arrow arrays. The `type` label value for this cache is `vector`. +vector_cache_size = "512MB" +# Cache size for pages of SST row groups. The `type` label value for this cache is `page`. +page_cache_size = "512MB" +# Cache size for time series selector (e.g. `last_value()`). The `type` label value for this cache is `selector_result`. +selector_result_cache_size = "512MB" + +[region_engine.mito.index] +## The max capacity of the index staging directory. +staging_size = "10GB" +``` + + +Some tips: + +- 1/10 of disk space for the write cache at least +- 1/4 of total memory for the `page_cache_size` at least if the memory usage is under 20% +- Double the cache size if the cache hit ratio is less than 50% +- If using full-text index, leave 1/10 of disk space for the `staging_size` at least + +### Avoid adding high cardinality columns to the primary key + +Putting high cardinality columns, such as `trace_id` or `uuid`, into the primary key can negatively impact both write and query performance. Instead, consider using an [append-only table](/reference/sql/create.md#create-an-append-only-table) and setting these high cardinality columns as fields. + +### Using append-only table if possible + +In general, append-only tables have a higher scan performance as the storage engine can skip merging and deduplication. What's more, the query engine can use statistics to speed up some queries if the table is append-only. + +We recommend enabling the [append_mode](/reference/sql/create.md#create-an-append-only-table) for the table if it doesn't require deduplication or performance is prioritized over deduplication. For example, a log table should be append-only as log messages may have the same timestamp. + +### Disable Write-Ahead-Log(WAL) + +If you are consuming and writing to GreptimeDB from replayable data sources such as Kafka, you can further improve write throughput by disabling WAL. + +Please note that when WAL is disabled, unflushed data to disk or object storage will not be recoverable and will need to be restored from the original data source, such as re-reading from Kafka or re-fetching logs. + +Disable WAL by setting the table option `skip_wal='true'`: + +```sql +CREATE TABLE logs( + message STRING, + ts TIMESTAMP TIME INDEX +) WITH (skip_wal = 'true'); +``` + + +## Ingestion + +### Metrics + +The following metrics help diagnose ingestion issues: + +| Metric | Type | Description | +| -------------------------------------------- | --------- | ---------------------------------------------------------------------------------------- | +| greptime_mito_write_stage_elapsed_bucket | histogram | The elapsed time of different phases of processing a write request in the storage engine | +| greptime_mito_write_buffer_bytes | gauge | The current estimated bytes allocated for the write buffer (memtables). | +| greptime_mito_write_rows_total | counter | The number of rows written to the storage engine | +| greptime_mito_write_stall_total | gauge | The number of rows currently stalled due to high memory pressure | +| greptime_mito_write_reject_total | counter | The number of rows rejected due to high memory pressure | +| raft_engine_sync_log_duration_seconds_bucket | histogram | The elapsed time of flushing the WAL to the disk | +| greptime_mito_flush_elapsed | histogram | The elapsed time of flushing the SST files | + +### Batching rows + +Batching means sending multiple rows to the database over the same request. This can significantly improve ingestion throughput. A recommended starting point is 1000 rows per batch. You can enlarge the batch size if latency and resource usage are still acceptable. + +### Writing by time window + +Although GreptimeDB can handle out-of-order data, it still affects performance. GreptimeDB infers a time window size from ingested data and partitions the data into multiple time windows according to their timestamps. If the written rows are not within the same time window, GreptimeDB needs to split them, which affects write performance. + +Generally, real-time data doesn't have the issues mentioned above as they always use the latest timestamp. If you need to import data with a long time range into the database, we recommend creating the table in advance and [specifying the compaction.twcs.time_window option](/reference/sql/create.md#create-a-table-with-custom-compaction-options). + +## Schema + +### Using multiple fields + +While designing the schema, we recommend putting related metrics that can be collected together in the same table. This can also improve the write throughput and compression ratio. + +For example, the following three tables collect the CPU usage metrics. + +```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) +); +``` + +We can merge them into one table with three fields. + +```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/versioned_docs/version-1.0/user-guide/deployments-administration/run-on-android.md b/versioned_docs/version-1.0/user-guide/deployments-administration/run-on-android.md new file mode 100644 index 0000000000..717551f7a1 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/run-on-android.md @@ -0,0 +1,107 @@ +--- +keywords: [Android, Termux, installation, configuration, database, ARM64] +description: Instructions for running GreptimeDB on Android platforms, including installation of Termux, downloading the GreptimeDB binary, creating a configuration file, starting the database, and connecting to it from another device. +--- + +# Run on Android Platforms + +Since v0.4.0, GreptimeDB supports running on Android platforms with ARM64 CPU and Android API level >= 23. + +## Install terminal emulator on Android + +You can install [Termux](https://termux.dev/) from [GitHub release page](https://github.com/termux/termux-app/releases/latest). + + +## Download GreptimeDB Android binary. + +```bash +VERSION=$(curl -sL \ + -H "Accept: application/vnd.github+json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + "https://api.github.com/repos/GreptimeTeam/greptimedb/releases/latest" | sed -n 's/.*"tag_name": "\([^"]*\)".*/\1/p') + +curl -sOL "https://github.com/GreptimeTeam/greptimedb/releases/download/${VERSION}/greptime-android-arm64-${VERSION}.tar.gz" +tar zxvf ./greptime-android-arm64-${VERSION}.tar.gz +./greptime -V +``` + +If binary's downloaded correctly, the command is expected to print the version of downloaded binary. + +## Create GreptimeDB configuration file + +You can create a minimal configuration file that allows access from local network. + +```bash +DATA_DIR="$(pwd)/greptimedb-data" +mkdir -p ${DATA_DIR} + +cat < ./config.toml +[http] +addr = "0.0.0.0:4000" + +[grpc] +bind_addr = "0.0.0.0:4001" + +[mysql] +addr = "0.0.0.0:4002" + +[storage] +data_home = "${DATA_DIR}" +type = "File" +EOF +``` + +## Start GreptimeDB from command line + +```bash +./greptime --log-dir=$(pwd)/logs standalone start -c ./config.toml +``` + +## Connect to GreptimeDB running on Android +> You can find the IP address of your Android device from system settings or `ifconfig`. + +You can now connect to the GreptimeDB instance running on Android from another device with MySQL client installed. + +```bash +mysql -h -P 4002 +``` + +And play like on any other platforms! +``` +Welcome to the MySQL monitor. Commands end with ; or \g. +Your MySQL connection id is 8 +Server version: 5.1.10-alpha-msql-proxy Greptime + +Copyright (c) 2000, 2023, Oracle and/or its affiliates. + +Oracle is a registered trademark of Oracle Corporation and/or its +affiliates. Other names may be trademarks of their respective +owners. + +Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. + +mysql> CREATE TABLE monitor (env STRING, host STRING, ts TIMESTAMP, cpu DOUBLE DEFAULT 0, memory DOUBLE, TIME INDEX (ts), PRIMARY KEY(env,host)); +Query OK, 0 rows affected (0.14 sec) + +mysql> INSERT INTO monitor(ts, env, host, cpu, memory) VALUES + -> (1655276557000,'prod', 'host1', 66.6, 1024), + -> (1655276557000,'prod', 'host2', 66.6, 1024), + -> (1655276557000,'prod', 'host3', 66.6, 1024), + -> (1655276558000,'prod', 'host1', 77.7, 2048), + -> (1655276558000,'prod', 'host2', 77.7, 2048), + -> (1655276558000,'test', 'host3', 77.7, 2048), + -> (1655276559000,'test', 'host1', 88.8, 4096), + -> (1655276559000,'test', 'host2', 88.8, 4096), + -> (1655276559000,'test', 'host3', 88.8, 4096); +Query OK, 9 rows affected (0.14 sec) + +mysql> +mysql> select * from monitor where env='test' and host='host3'; ++------+-------+---------------------+------+--------+ +| env | host | ts | cpu | memory | ++------+-------+---------------------+------+--------+ +| test | host3 | 2022-06-15 15:02:38 | 77.7 | 2048 | +| test | host3 | 2022-06-15 15:02:39 | 88.8 | 4096 | ++------+-------+---------------------+------+--------+ +2 rows in set (0.20 sec) +``` diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/troubleshooting.md b/versioned_docs/version-1.0/user-guide/deployments-administration/troubleshooting.md new file mode 100644 index 0000000000..773267dff6 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/troubleshooting.md @@ -0,0 +1,150 @@ +--- +keywords: [troubleshooting, configuration troubleshooting, performance troubleshooting, write troubleshooting] +description: GreptimeDB troubleshooting guide, including methods and metrics for diagnosing common issues. +--- + +# Troubleshooting + +When encountering errors or performance issues, +you can understand GreptimeDB's status through metrics and logs. +This information can also help further investigate the root causes of problems. + +The following lists troubleshooting methods for some common abnormal situations. +For cases where the cause cannot be easily identified, +providing metrics and logs to the official team can also improve the efficiency of official troubleshooting. + +## Checking CPU and Memory Load + +You can directly view the CPU and Memory load of corresponding components from the Dashboard. +CPU is displayed in millicores, while Memory shows the current process RSS. +You need to pay attention to whether the corresponding CPU and Memory load exceeds the Pod's Limit. +If CPU has reached the Pod's Limit, +throttling will be triggered, and clients will experience slower request processing. +If Memory reaches over 70% of the Limit, it may result in OOM (Out of Memory). + +## Flow Creation Failure + +When flow creation fails, +one common scenario is that flownode is not deployed. +You can check: + +- Whether flownode is deployed in the cluster +- Whether the flownode status in the cluster is READY + +If flownode is already deployed, +you can further investigate by examining metasrv and flownode logs, +or check whether the flow node was successfully created through internal tables: + +```sql +select * from information_schema.cluster_info; +``` + +## Object Storage Configuration Issues + +When object storage is misconfigured, +GreptimeDB will encounter exceptions when accessing object storage. +If GreptimeDB hasn't stored any data, +it generally doesn't need to access object storage, +so errors might not be observable immediately after deployment. +Once you create a table or start writing data to GreptimeDB through write protocols, you can observe request errors. + +Typically, DB error messages will include object storage error details. +You can find specific object storage error information through DB error logs. +Some common error causes include: + +- Incorrect Access Key or Secret Access Key +- Improper object storage permission configuration +- If using Tencent Cloud COS's S3-compatible API, since Tencent Cloud has [disabled path-style domains](https://cloud.tencent.com/document/product/436/102489), you need to set `enable_virtual_host_style = true` in GreptimeDB's S3 configuration + +For S3 as an example, GreptimeDB requires the following permissions: + +```txt +"s3:PutObject", +"s3:ListBucket", +"s3:GetObject", +"s3:DeleteObject" +``` + +## Low Write Throughput + +You can observe write throughput through the Ingestion-related panels in the dashboard: + +![ingestion rate](/ingestion-rate.jpg) + +If write throughput is lower than expected load + it might be due to high write latency causing DB backlog. + The dashboard provides panels in the `Frontend Requests` area to observe request latency: + +![p99-latencies](/dashboard-p99-latencies.jpg) + +You can check if any nodes are experiencing stall through the `Write Stall` panel in the `Mito Engine` area (stall values remaining above 0 for extended periods). +If so, it indicates that node writes have encountered bottlenecks. + +![write-stall](/write-stall.jpg) + +By observing the `Write Buffer` panel, you can also monitor size changes in buffers used for writing. If buffers fill up quickly, consider proportionally increasing `global_write_buffer_size` and `global_write_buffer_reject_size`: + +![write-buffer](/write-buffer.jpg) + +The Write Stage panel shows which stages have high write latency: + +![write-stage](/write-stage.jpg) + +You can check background task status through Compaction/Flush related panels: +- Whether frequent flush operations occur; if so, consider proportionally increasing `global_write_buffer_size` and `global_write_buffer_reject_size` +- Whether there are long-running compaction and flush operations; if so, writes might be affected by these background tasks + +Additionally, logs related to `flush memtables` can show the latency of individual flush operations. + +## High Memory Consumption During Writes + +During DB write operations, +the total size of all memtables is estimated. +You can view memtable memory usage through the `Write Buffer` panel. + +![write-buffer-memtable](/write-buffer-memtable.jpg) + +Note that these values might be smaller than the actual allocated memory. + +If you notice that DB memory grows too quickly during writes, +or if writes frequently encounter OOM situations, +this might be related to unreasonable table schema design. + +A common cause is improper Primary Key design. +If there are too many primary keys, +it will consume excessive memory during writes, +potentially causing database memory usage to become too high. +In such cases, `Write Buffer` often remains at high levels. +Increasing write buffer size generally won't improve this issue; +you need to reduce the number of primary key columns or remove high-cardinality primary key columns. + +## High Query Latency + +If query latency is high, +you can add `EXPLAIN ANALYZE` or `EXPLAIN ANALYZE VERBOSE` before the query and re-execute it. +The query results will include execution time for each stage to assist in troubleshooting. + +Additionally, the `Read Stage` panel can help understand query latency across different stages: + +![read-stage](/read-stage.jpg) + +## Cache Full + +To understand the size of various caches, +you can check the used size of different caches on nodes through the `Cached Bytes` panel: + +![cached-bytes](/cached-bytes.jpg) + +For nodes with high query latency, +you can also determine if caches are full by checking cache sizes. + +## Object Storage Latency + +You can view object storage operation latency through panels in the `OpenDAL` area of the dashboard. +For example, the following panel shows response latency for object storage write operations: + +![opendal](/opendal.jpg) + +If you suspect object storage operations are experiencing jitter, +you can observe the related panels. + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/upgrade.md b/versioned_docs/version-1.0/user-guide/deployments-administration/upgrade.md new file mode 100644 index 0000000000..ca709757a4 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/upgrade.md @@ -0,0 +1,30 @@ +--- +keywords: [GreptimeDB upgrade, upgrade example] +description: Introduce how to upgrade GreptimeDB to the latest version, including some incompatible changes and specific upgrade steps. +--- + +# Upgrade + +## How to Upgrade GreptimeDB + +If your currently deployed GreptimeDB version is v0.12 or higher, v0.14 is fully compatible with existing database configurations and data formats, allowing for a direct upgrade. If you are using a version prior to v0.12, it is recommended to first refer to the v0.12 upgrade documentation to upgrade your database to v0.12, and then upgrade to v0.14, to ensure compatibility and a smooth transition. + + +## Minimizing Business Impact During Upgrade + +Before upgrading GreptimeDB, +it is essential to perform a comprehensive backup of your data to safeguard against potential data loss. +This backup acts as a safety measure in the event of any issues during the upgrade process. + +To minimize business impact during the upgrade, consider the following optional best practices: + +- **Rolling Upgrade:** Utilize [rolling upgrades](https://kubernetes.io/docs/tutorials/kubernetes-basics/update/update-intro/) on Kubernetes to update GreptimeDB instances incrementally. +This approach replaces old instances with new ones while maintaining service availability and minimizing downtime. +- **Automatic Retries:** Configure client applications to enable automatic retries with exponential backoff. +This helps handle temporary service interruptions gracefully. +- **Temporary Pause of Write Operations:** For applications that can tolerate brief maintenance windows, +consider pausing write operations during the upgrade to ensure data consistency. +- **Double Writing:** Implement double writing to both the old and new versions of GreptimeDB, +then switch to the new version once you have verified that it is functioning correctly. +This allows you to verify data consistency and gradually redirect read traffic to the upgraded version. + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/wal/local-wal.md b/versioned_docs/version-1.0/user-guide/deployments-administration/wal/local-wal.md new file mode 100644 index 0000000000..0863bcfca5 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/wal/local-wal.md @@ -0,0 +1,41 @@ +--- +keywords: [Configuration, Local WAL, GreptimeDB Datanode, GreptimeDB] +description: This section describes how to configure the Local WAL for GreptimeDB Datanode component. +--- +# Local WAL + +This section describes how to configure the local WAL for GreptimeDB Datanode component. + +```toml +[wal] +provider = "raft_engine" +file_size = "128MB" +purge_threshold = "1GB" +purge_interval = "1m" +read_batch_size = 128 +sync_write = false +``` + +## Options + +If you are using Helm Chart to deploy GreptimeDB, you can refer to [Common Helm Chart Configurations](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md) to learn how to configure the Datanode by injecting configuration files. + +| Configuration Option | Description | Default Value | +| -------------------- | -------------------------------------------------------------------------------------------------------------------- | ----------------- | +| `provider` | The provider of the WAL. Options: `raft_engine` (local file system storage), `kafka` (remote WAL storage in Kafka), or `noop` (no-op WAL provider) | `"raft_engine"` | +| `dir` | The directory where to write logs | `{data_home}/wal` | +| `file_size` | The size of single WAL log file | `128MB` | +| `purge_threshold` | The threshold of the WAL size to trigger purging | `1GB` | +| `purge_interval` | The interval to trigger purging | `1m` | +| `read_batch_size` | The read batch size | `128` | +| `sync_write` | Whether to call fsync when writing every log | `false` | + +## Best practices + +### Using a separate High-Performance Volume for WAL +It is beneficial to configure a separate volume for the WAL (Write-Ahead Log) directory when deploying GreptimeDB. This setup allows you to: + +- Leverage a high-performance disk—either a dedicated physical volume or one provisioned via a custom `StorageClass`. +- Isolate WAL I/O from cache file access, reducing I/O contention and enhancing overall system performance. + +If you are using Helm Chart to deploy GreptimeDB, you can refer to [Common Helm Chart Configurations](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md) to learn how to configure a dedicated WAL volume. diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/wal/noop-wal.md b/versioned_docs/version-1.0/user-guide/deployments-administration/wal/noop-wal.md new file mode 100644 index 0000000000..5b75204678 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/wal/noop-wal.md @@ -0,0 +1,41 @@ +--- +keywords: [Configuration, Noop WAL, GreptimeDB Datanode, GreptimeDB, cluster mode] +description: This section describes how to configure the Noop WAL for GreptimeDB Datanode component in cluster mode. +--- +# Noop WAL + +Noop WAL is a special WAL provider for emergency situations when the configured WAL provider becomes temporarily unavailable. It does not store any WAL data. + +## Availability + +Noop WAL is **only available in cluster mode**, not in standalone mode. + +## Use Cases + +- **Temporary WAL Unavailability**: When the WAL provider (e.g., Kafka) is temporarily unavailable, switch the Datanode to Noop WAL to keep the cluster running. +- **Testing and Development**: Useful for testing scenarios where WAL persistence is not required. + +## Data Loss Warning + +**When using Noop WAL, all unflushed data will be lost when the Datanode is shutdown or restarted.** Only use this provider temporarily when the normal WAL provider is unavailable. Not recommended for production use except in emergency situations. + +## Configuration + +To configure Noop WAL for a Datanode: + +```toml +[wal] +provider = "noop" +``` + +In a GreptimeDB cluster, WAL configuration has two parts: + +- **Metasrv** - Generates WAL metadata for new regions. Should be set to `raft_engine` or `kafka`. +- **Datanode** - Reads and writes WAL data. Configure as `noop` when the WAL provider is unavailable. + +Note: Noop WAL can only be configured on Datanode, not on Metasrv. When using Noop WAL on Datanode, Metasrv continues using its configured WAL provider. + +## Best Practices + +- Flush regions regularly using `admin flush_table()` or `admin flush_region()` to minimize data loss. +- Switch back to the normal WAL provider as soon as it becomes available. diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/wal/overview.md b/versioned_docs/version-1.0/user-guide/deployments-administration/wal/overview.md new file mode 100644 index 0000000000..5f05ae4391 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/wal/overview.md @@ -0,0 +1,57 @@ +--- +keywords: [WAL, Write-Ahead Logging, Local WAL, Remote WAL, GreptimeDB] +description: This section describes the WAL (Write-Ahead Logging) in GreptimeDB, including the advantages and disadvantages of Local WAL and Remote WAL. +--- +# Overview + +The [Write-Ahead Logging](/contributor-guide/datanode/wal.md#introduction)(WAL) is a crucial component in GreptimeDB that persistently records every data modification to ensure no memory-cached data loss. GreptimeDB provides three WAL storage options: + +- **Local WAL**: Uses an embedded storage engine([raft-engine](https://github.com/tikv/raft-engine)) within the [Datanode](/user-guide/concepts/why-greptimedb.md). + +- **Remote WAL**: Uses [Apache Kafka](https://kafka.apache.org/) as the external(remote) WAL storage component. + +- **Noop WAL**: A no-op WAL provider for emergency situations when WAL becomes unavailable. Does not store any data. + +## Local WAL + +### Advantages + +- **Low latency**: The local WAL is stored within the same process as the Datanode, eliminating network overhead and providing low write latency. + +- **Easy to deploy**: Since the WAL is co-located with the Datanode, no additional components are required, simplifying deployment and operations. + +- **Zero RPO**: When deploying GreptimeDB in the cloud, you can configure persistent storage for WAL data using cloud storage services such as AWS EBS or GCP Persistent Disk. This ensures zero [Recovery Point Objective](https://en.wikipedia.org/wiki/Disaster_recovery#Recovery_Point_Objective) (RPO), meaning no data loss, even in the event of system failure. + +### Disadvantages + +- **High RTO**: Because the WAL resides on the same node as the Datanode, the [Recovery Time Objective](https://en.wikipedia.org/wiki/Disaster_recovery#Recovery_Time_Objective) (RTO) is relatively high. After a Datanode restarts, it must replay the WAL to restore the latest data, during which time the node remains unavailable. + +- **Single-Point Access Limitation**: The local WAL is tightly coupled with the Datanode process and only supports a single consumer, which limits features such as region hot standby and [Region Migration](/user-guide/deployments-administration/manage-data/region-migration.md). + +## Remote WAL + +### Advantages + +- **Low RTO**: By decoupling WAL from the Datanode, [Recovery Time Objective](https://en.wikipedia.org/wiki/Disaster_recovery#Recovery_Time_Objective) (RTO) is minimized. If a Datanode crashes, the Metasrv can quickly trigger a [Region Failover](/user-guide/deployments-administration/manage-data/region-failover.md) to migrate affected regions to healthy nodes—without the need to replay WAL locally. + +- **Multi-Consumer Subscriptions**: Remote WAL supports multiple consumers subscribing to WAL logs simultaneously, enabling features such as region hot standby and [Region Migration](/user-guide/deployments-administration/manage-data/region-migration.md), thereby enhancing system availability and flexibility. + +### Disadvantages + +- **External dependencies**: Remote WAL relies on an external Kafka cluster, which increases the complexity of deployment, operation, and maintenance. + +- **Network overhead**: Since WAL data needs to be transmitted over the network, careful planning of cluster network bandwidth is required to ensure low latency and high throughput, especially under write-heavy workloads. + +## Noop WAL + +Noop WAL is a special WAL provider for emergency situations when the configured WAL provider becomes temporarily unavailable. It does not store any WAL data and is only available in cluster mode. + +For detailed configuration, see the [Noop WAL](/user-guide/deployments-administration/wal/noop-wal.md) page. + +## Next steps + +- To configure the Local WAL storage, please refer to [Local WAL](/user-guide/deployments-administration/wal/local-wal.md). + +- To learn more about the Remote WAL, please refer to [Remote WAL](/user-guide/deployments-administration/wal/remote-wal/configuration.md). + +- To learn more about the Noop WAL, please refer to [Noop WAL](/user-guide/deployments-administration/wal/noop-wal.md). \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/configuration.md b/versioned_docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/configuration.md new file mode 100644 index 0000000000..c90cfe365e --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/configuration.md @@ -0,0 +1,166 @@ +--- +keywords: [GreptimeDB Remote WAL, configuration, Kafka, Metasrv, Datanode, GreptimeDB] +description: This section describes how to configure the Remote WAL for GreptimeDB Cluster. +--- +# Configuration + +The configuration of Remote WAL contains two parts: + +- Metasrv Configuration +- Datanode Configuration + +If you are using Helm Chart to deploy GreptimeDB, you can refer to [Common Helm Chart Configurations](/user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations.md) to learn how to configure Remote WAL. + +## Metasrv Configuration + +On the Metasrv side, Remote WAL is primarily responsible for managing Kafka topics and periodically pruning stale WAL data. + +```toml +[wal] +provider = "kafka" +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] + +# WAL data pruning options +auto_prune_interval = "30m" +auto_prune_parallelism = 10 +flush_trigger_size = "512MB" +checkpoint_trigger_size = "128MB" + +# Topic creation options +auto_create_topics = true +num_topics = 64 +replication_factor = 1 +topic_name_prefix = "greptimedb_wal_topic" +``` + +### Options + +| Configuration Option | Description | +| Configuration Option | Description | +|----------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `provider` | The WAL provider to use. Set to `"kafka"` to enable Remote WAL with Kafka. | +| `broker_endpoints` | List of Kafka broker addresses to connect to. Example: `["kafka.kafka-cluster.svc:9092"]`. | +| `auto_prune_interval` | How often to automatically prune (delete) stale WAL data. Specify as a duration string (e.g., `"30m"`). Set to `"0s"` to disable automatic pruning. | +| `auto_prune_parallelism` | Maximum number of concurrent pruning tasks. Increasing this value may speed up pruning but will use more resources. | +| `auto_create_topics` | If `true`, Metasrv will automatically create required Kafka topics. If `false`, you must manually create all topics before starting Metasrv. | +| `num_topics` | Number of Kafka topics to use for WAL storage. More topics can improve scalability and performance. | +| `replication_factor` | Replication factor for Kafka topics. Determines how many Kafka brokers will store copies of each topic's data. | +| `topic_name_prefix` | Prefix for Kafka topic names. WAL topics will be named as `{topic_name_prefix}_{index}` (e.g., `greptimedb_wal_topic_0`). The prefix must match the regex `[a-zA-Z_:-][a-zA-Z0-9_:\-\.@#]*`. | +| `flush_trigger_size` | Estimated size threshold (e.g., `"512MB"`) for triggering a flush operation in a region. Calculated as `(latest_entry_id - flushed_entry_id) * avg_record_size`. When this value exceeds `flush_trigger_size`, MetaSrv initiates a flush. Set to `"0"` to let the system automatically determine the flush trigger size. This also controls the maximum replay size from a topic during region replay; using a smaller value can help reduce region replay time during Datanode startup. | +| `checkpoint_trigger_size` | Estimated size threshold (e.g., `"128MB"`) for triggering a checkpoint operation in a region. Calculated as `(latest_entry_id - last_checkpoint_entry_id) * avg_record_size`. When this value exceeds `checkpoint_trigger_size`, MetaSrv initiates a checkpoint. Set to `"0"` to let the system automatically determine the checkpoint trigger size. Using a smaller value can help reduce region replay time during Datanode startup. | + +#### Topic Setup and Kafka Permissions + +To ensure Remote WAL works correctly with Kafka, please check the following: + +- If `auto_create_topics = false`: + - All required topics must be created manually **before** starting Metasrv. + - Topic names must follow the pattern `{topic_name_prefix}_{index}` where `index` ranges from `0` to `{num_topics - 1}`. For example, with the default prefix `greptimedb_wal_topic` and `num_topics = 64`, you need to create topics from `greptimedb_wal_topic_0` to `greptimedb_wal_topic_63`. + - Topics must be configured to support **LZ4 compression**. +- The Kafka user must have the following permissions: + - **Append** records to WAL topics (requires LZ4 compression support). + - **Read** records from WAL topics (requires LZ4 compression support). + - **Delete** records from WAL topics. + - **Create** topics (only required if `auto_create_topics = true`). + +## Datanode Configuration + +The Datanode side is mainly used to write the data to the Kafka topics and read the data from the Kafka topics. + +```toml +[wal] +provider = "kafka" +broker_endpoints = ["kafka.kafka-cluster.svc:9092"] +max_batch_bytes = "1MB" +overwrite_entry_start_id = true +``` + +### Options + +| Configuration Option | Description | +| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| `provider` | Set to "kafka" to enable Remote WAL via Kafka. | +| `broker_endpoints` | List of Kafka broker addresses. | +| `max_batch_bytes` | Maximum size for each Kafka producer batch. | +| `overwrite_entry_start_id` | If true, the Datanode will skip over missing entries during WAL replay. Prevents out-of-range errors, but may hide data loss. | + + +#### Required Settings and Limitations + +:::warning IMPORTANT: Kafka Retention Policy Configuration +Please configure Kafka retention policy very carefully to avoid data loss. GreptimeDB will automatically recycle unneeded WAL data, so in most cases you don't need to set the retention policy. However, if you do set it, please ensure the following: + +- **Size-based retention**: Typically not needed, as the database manages its own data lifecycle +- **Time-based retention**: If you choose to set this, ensure it's **significantly greater than the auto-flush-interval** to prevent premature data deletion + +Improper retention settings can lead to data loss if WAL data is deleted before GreptimeDB has processed it. +::: + +- If you set `overwrite_entry_start_id = true`: + - Ensure that `auto_prune_interval` is enabled in Metasrv to allow automatic WAL pruning. + - Kafka topics **must not use size-based retention policies**. + - If time-based retention is enabled, the retention period should be set to a value significantly greater than auto-flush-interval, preferably at least 2 times its value. + +- Ensure the Kafka user used by Datanode has the following permissions: + - **Append** records to WAL topics (requires LZ4 compression support). + - **Read** records from WAL topics (requires LZ4 compression support). +- Ensure that `max_batch_bytes` does not exceed Kafka’s maximum message size (typically 1MB by default). + +## Kafka Authentication Configuration + +Kafka authentication settings apply to both Metasrv and Datanode under the `[wal]` section. + +### SASL + +Kafka supports several SASL mechanisms: `PLAIN`, `SCRAM-SHA-256`, and `SCRAM-SHA-512`. + +```toml +[wal] +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] + +[wal.sasl] +type = "SCRAM-SHA-512" +username = "user" +password = "secret" +``` + +### TLS + +You can enable TLS encryption for Kafka connections by configuring the `[wal.tls]` section. There are three common modes: + +#### Using System CA Certificate + +To use system-wide trusted CAs, enable TLS without providing any certificate paths: + +```toml +[wal] +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] + +[wal.tls] +``` + +#### Using Custom CA Certificate + +If your Kafka cluster uses a private CA, specify the server CA certificate explicitly: + +```toml +[wal] +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] + +[wal.tls] +server_ca_cert_path = "/path/to/server.crt" +``` + +#### Using Mutual TLS (mTLS) + +To enable mutual authentication, provide both the client certificate and private key along with the server CA: + +```toml +[wal] +broker_endpoints = ["kafka.kafka-cluster.svc.cluster.local:9092"] +[wal.tls] +server_ca_cert_path = "/path/to/server_cert" +client_cert_path = "/path/to/client_cert" +client_key_path = "/path/to/key" +``` + diff --git a/versioned_docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/manage-kafka.md b/versioned_docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/manage-kafka.md new file mode 100644 index 0000000000..08e818945a --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/deployments-administration/wal/remote-wal/manage-kafka.md @@ -0,0 +1,103 @@ +--- +keywords: [Kafka, kubernetes, helm, GreptimeDB, remote WAL, installation, configuration, management] +description: This guide describes how to install and manage Kafka cluster. +--- +# Manage Kafka + +The GreptimeDB cluster uses Kafka as the [Remote WAL](/user-guide/deployments-administration/wal/remote-wal/configuration.md) storage. This guide describes how to manage Kafka cluster. This guide will use Bitnami's Kafka Helm [chart](https://github.com/bitnami/charts/tree/main/bitnami/kafka) as an example. + +## Prerequisites + +- [Kubernetes](https://kubernetes.io/docs/setup/) >= v1.23 +- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) >= v1.18.0 +- [Helm](https://helm.sh/docs/intro/install/) >= v3.0.0 + +## Install + +Save the following configuration as a file `kafka.yaml`: + +```yaml +global: + security: + allowInsecureImages: true + +image: + registry: docker.io + repository: greptime/kafka + tag: 3.9.0-debian-12-r12 + +controller: + replicaCount: 3 + + resources: + requests: + cpu: 2 + memory: 2Gi + limits: + cpu: 2 + memory: 2Gi + + persistence: + enabled: true + size: 200Gi + +broker: + replicaCount: 3 + + resources: + requests: + cpu: 2 + memory: 2Gi + limits: + cpu: 2 + memory: 2Gi + + persistence: + enabled: true + size: 200Gi + +listeners: + client: + # When deploying on production environment, you normally want to use a more secure protocol like SASL. + # Please refer to the chart's docs for the "how-to": https://artifacthub.io/packages/helm/bitnami/kafka#enable-security-for-kafka + # Here for the sake of example's simplicity, we use plaintext (no authentications). + protocol: plaintext +``` + +Install Kafka cluster: + +```bash +helm upgrade --install kafka \ + oci://registry-1.docker.io/bitnamicharts/kafka \ + --values kafka.yaml \ + --version 32.4.3 \ + --create-namespace \ + -n kafka-cluster +``` + +Wait for Kafka cluster to be ready: + +```bash +kubectl wait --for=condition=ready pod \ + -l app.kubernetes.io/instance=kafka \ + -n kafka-cluster \ +``` + +Check the status of the Kafka cluster: + +```bash +kubectl get pods -n kafka-cluster +``` + +
+ Expected Output +```bash +NAME READY STATUS RESTARTS AGE +kafka-controller-0 1/1 Running 0 64s +kafka-controller-1 1/1 Running 0 64s +kafka-controller-2 1/1 Running 0 64s +kafka-broker-0 1/1 Running 0 63s +kafka-broker-1 1/1 Running 0 62s +kafka-broker-2 1/1 Running 0 61s +``` +
diff --git a/versioned_docs/version-1.0/user-guide/flow-computation/continuous-aggregation.md b/versioned_docs/version-1.0/user-guide/flow-computation/continuous-aggregation.md new file mode 100644 index 0000000000..2e31ce5ceb --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/flow-computation/continuous-aggregation.md @@ -0,0 +1,565 @@ +--- +keywords: [continuous aggregation, real-time analytics, time-series data, Flow engine, log analysis, sensor monitoring] +description: Learn how to use GreptimeDB's continuous aggregation for real-time analytics. Master Flow engine basics, time-window calculations, and SQL queries through practical examples of log analysis and sensor monitoring. +--- + +# Continuous Aggregation + +Continuous aggregation is a crucial aspect of processing time-series data to deliver real-time insights. +The Flow engine empowers developers to perform continuous aggregations, +such as calculating sums, averages, and other metrics, seamlessly. +It efficiently updates the aggregated data within specified time windows, making it an invaluable tool for analytics. + +Following are three major usecase examples for continuous aggregation: + +1. **Real-time Analytics**: A real-time analytics platform that continuously aggregates data from a stream of events, delivering immediate insights while optionally downsampling the data to a lower resolution. For instance, this system can compile data from a high-frequency stream of log events (e.g., occurring every millisecond) to provide up-to-the-minute insights such as the number of requests per minute, average response times, and error rates per minute. + +2. **Real-time Monitoring**: A real-time monitoring system that continuously aggregates data from a stream of events and provides real-time alerts based on the aggregated data. For example, a system that aggregates data from a stream of sensor events and provides real-time alerts when the temperature exceeds a certain threshold. + +3. **Real-time Dashboard**: A real-time dashboard that shows the number of requests per minute, the average response time, and the number of errors per minute. This dashboard can be used to monitor the health of the system and to detect any anomalies in the system. + +In all these usecases, the continuous aggregation system continuously aggregates data from a stream of events and provides real-time insights and alerts based on the aggregated data. The system can also downsample the data to a lower resolution to reduce the amount of data stored and processed. This allows the system to provide real-time insights and alerts while keeping the data storage and processing costs low. + + +## Real-time Analytics Example + +### Calculate the Log Statistics + +This use case is to calculate the total number of logs, the minimum size, the maximum size, the average size, and the number of packets with the size greater than 550 for each status code in a 1-minute fixed window for access logs. +First, create a source table `ngx_access_log` and a sink table `ngx_statistics` with following clauses: + +```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 INDEX, + `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`) +); +``` + +Then create the flow `ngx_aggregation` to aggregate a series of aggregate functions, including `count`, `min`, `max`, `avg` of the `size` column, and the sum of all packets of size great than 550. The aggregation is calculated in 1-minute fixed windows of `access_time` column and also grouped by the `status` column. So you can be made aware in real time the information about packet size and action upon it, i.e. if the `high_size_count` became too high at a certain point, you can further examine if anything goes wrong, or if the `max_size` column suddenly spike in a 1 minute time window, you can then trying to locate that packet and further inspect it. + +The `EXPIRE AFTER '6h'` in the following SQL ensures that the flow computation only uses source data from the last 6 hours. Data older than 6 hours in the sink table will not be modified by this flow. For more details, see [manage-flow](manage-flow.md#expire-after). + +```sql +CREATE FLOW ngx_aggregation +SINK TO ngx_statistics +EXPIRE AFTER '6h' +COMMENT 'aggregate nginx access logs' +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('1 minutes'::INTERVAL, access_time) as time_window, +FROM ngx_access_log +GROUP BY + status, + time_window; +``` + +To observe the outcome of the continuous aggregation in the `ngx_statistics` table, insert some data into the source table `ngx_access_log`. + +```sql +INSERT INTO ngx_access_log +VALUES + ('android', 'Android', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 200, 1000, 'agent', now() - INTERVAL '1' minute), + ('ios', 'iOS', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 200, 500, 'agent', now() - INTERVAL '1' minute), + ('android', 'Android', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 200, 600, 'agent', now()), + ('ios', 'iOS', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 404, 700, 'agent', now()); +``` + +Then the sink table `ngx_statistics` will be incremental updated and contain the following data: + +```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 | 2025-04-24 06:46:00 | 2025-04-24 06:47:06.680000 | +| 200 | 1 | 600 | 600 | 600 | 1 | 2025-04-24 06:47:00 | 2025-04-24 06:47:06.680000 | +| 404 | 1 | 700 | 700 | 700 | 1 | 2025-04-24 06:47:00 | 2025-04-24 06:47:06.680000 | ++--------+------------+----------+----------+----------+-----------------+---------------------+----------------------------+ +3 rows in set (0.01 sec) +``` + +Try to insert more data into the `ngx_access_log` table: + +```sql +INSERT INTO ngx_access_log +VALUES + ('android', 'Android', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 200, 500, 'agent', now()), + ('ios', 'iOS', 'referer', 'GET', '/api/v1', 'trace_id', 'HTTP', 404, 800, 'agent', now()); +``` + +The sink table `ngx_statistics` now have corresponding rows updated, notes how `max_size`, `avg_size` and `high_size_count` are updated: + +```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 | 2025-04-24 06:46:00 | 2025-04-24 06:47:06.680000 | +| 200 | 2 | 500 | 600 | 550 | 1 | 2025-04-24 06:47:00 | 2025-04-24 06:47:21.720000 | +| 404 | 2 | 700 | 800 | 750 | 2 | 2025-04-24 06:47:00 | 2025-04-24 06:47:21.720000 | ++--------+------------+----------+----------+----------+-----------------+---------------------+----------------------------+ +3 rows in set (0.01 sec) +``` + +Here is the explanation of the columns in the `ngx_statistics` table: + +- `status`: The status code of the HTTP response. +- `total_logs`: The total number of logs with the same status code. +- `min_size`: The minimum size of the packets with the same status code. +- `max_size`: The maximum size of the packets with the same status code. +- `avg_size`: The average size of the packets with the same status code. +- `high_size_count`: The number of packets with the size greater than 550. +- `time_window`: The time window of the aggregation. +- `update_at`: The time when the aggregation is updated. + +### Retrieve Distinct Countries by Time Window + +Another example of real-time analytics is to retrieve all distinct countries from the `ngx_access_log` table. +You can use the following query to group countries by time window: + +```sql +/* input table */ +CREATE TABLE ngx_access_log ( + client STRING, + country STRING, + access_time TIMESTAMP TIME INDEX, + PRIMARY KEY(client) +) +WITH( + append_mode = 'true' +); + +/* sink table */ +CREATE TABLE ngx_country ( + country STRING, + time_window TIMESTAMP TIME INDEX, + update_at TIMESTAMP, + PRIMARY KEY(country) +); + +/* create flow task to calculate the distinct country */ +CREATE FLOW calc_ngx_country +SINK TO ngx_country +EXPIRE AFTER '7days'::INTERVAL +COMMENT 'aggregate for distinct country' +AS +SELECT + DISTINCT country, + date_bin('1 hour'::INTERVAL, access_time) as time_window, +FROM ngx_access_log +GROUP BY + country, + time_window; +``` + +The above query puts the data from the `ngx_access_log` table into the `ngx_country` table. +It calculates the distinct country for each time window. +The `date_bin` function is used to group the data into one-hour intervals. +The `ngx_country` table will be continuously updated with the aggregated data, +providing real-time insights into the distinct countries that are accessing the system. The `EXPIRE AFTER` make flow ignore data with `access_time` older than 7 days and no longer calculate them anymore, see more explain in [manage-flow](manage-flow.md#expire-after). + +You can insert some data into the source table `ngx_access_log`: + +```sql +INSERT INTO ngx_access_log VALUES + ('client1', 'US', now() - '2 hour'::INTERVAL), + ('client2', 'US', now() - '2 hour'::INTERVAL), + ('client3', 'UK', now() - '2 hour'::INTERVAL), + ('client4', 'UK', now() - '1 hour'::INTERVAL), + ('client5', 'CN', now() - '1 hour'::INTERVAL), + ('client6', 'CN', now() - '1 hour'::INTERVAL), + ('client7', 'JP', now()), + ('client8', 'JP', now()), + ('client9', 'KR', now()), + ('client10', 'KR', now()); +``` + +Wait for few seconds for the Flow to write the result to the sink table and then query: + +```sql +select * from ngx_country; +``` + +```sql ++---------+---------------------+----------------------------+ +| country | time_window | update_at | ++---------+---------------------+----------------------------+ +| CN | 2025-04-24 05:00:00 | 2025-04-24 06:55:17.217000 | +| JP | 2025-04-24 06:00:00 | 2025-04-24 06:55:17.217000 | +| KR | 2025-04-24 06:00:00 | 2025-04-24 06:55:17.217000 | +| UK | 2025-04-24 04:00:00 | 2025-04-24 06:55:17.217000 | +| UK | 2025-04-24 05:00:00 | 2025-04-24 06:55:17.217000 | +| US | 2025-04-24 04:00:00 | 2025-04-24 06:55:17.217000 | ++---------+---------------------+----------------------------+ +6 rows in set (0.00 sec) +``` + +## Real-Time Monitoring Example + +Consider a usecase where you have a stream of sensor events from a network of temperature sensors that you want to monitor in real-time. The sensor events contain information such as the sensor ID, the temperature reading, the timestamp of the reading, and the location of the sensor. You want to continuously aggregate this data to provide real-time alerts when the temperature exceeds a certain threshold. Then the query for continuous aggregation would be: + +```sql +/* create input table */ +CREATE TABLE temp_sensor_data ( + sensor_id INT, + loc STRING, + temperature DOUBLE, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY(sensor_id, loc) +) +WITH( + append_mode = 'true' +); + +/* create sink table */ +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 +EXPIRE AFTER '1h' +AS +SELECT + sensor_id, + loc, + max(temperature) as max_temp, + date_bin('10 seconds'::INTERVAL, ts) as time_window, +FROM temp_sensor_data +GROUP BY + sensor_id, + loc, + time_window +HAVING max_temp > 100; +``` + +The above query continuously aggregates data from the `temp_sensor_data` table into the `temp_alerts` table. +It calculates the maximum temperature reading for each sensor and location, +filtering out data where the maximum temperature exceeds 100 degrees. +The `temp_alerts` table will be continuously updated with the aggregated data, +providing real-time alerts (in the form of new rows in the `temp_alerts` table) when the temperature exceeds the threshold. The `EXPIRE AFTER '1h'` makes flow only calculate source data with `ts` in `(now - 1h, now)` range, see more explain in [manage-flow](manage-flow.md#expire-after). + +Now that we have created the flow task, we can insert some data into the source table `temp_sensor_data`: + +```sql + +INSERT INTO temp_sensor_data VALUES + (1, 'room1', 98.5, now() - '10 second'::INTERVAL), + (2, 'room2', 99.5, now()); +``` +table should be empty now, but still wait at least few seconds for flow to update results to sink table: + +```sql +SELECT * FROM temp_alerts; +``` + +```sql +Empty set (0.00 sec) +``` + +Now insert some data that will trigger the alert: + +```sql +INSERT INTO temp_sensor_data VALUES + (1, 'room1', 101.5, now()), + (2, 'room2', 102.5, now()); +``` + +wait at least few seconds for flow to update results to sink table: + +```sql +SELECT * FROM temp_alerts; +``` + +```sql ++-----------+-------+----------+---------------------+----------------------------+ +| sensor_id | loc | max_temp | time_window | update_at | ++-----------+-------+----------+---------------------+----------------------------+ +| 1 | room1 | 101.5 | 2025-04-24 06:58:20 | 2025-04-24 06:58:32.379000 | +| 2 | room2 | 102.5 | 2025-04-24 06:58:20 | 2025-04-24 06:58:32.379000 | ++-----------+-------+----------+---------------------+----------------------------+ +2 rows in set (0.01 sec) +``` + +## Real-Time Dashboard + +Consider a usecase in which you need a bar graph that show the distribution of packet sizes for each status code to monitor the health of the system. The query for continuous aggregation would be: + +```sql +/* create input table */ +CREATE TABLE ngx_access_log ( + client STRING, + stat INT, + size INT, + access_time TIMESTAMP TIME INDEX +) +WITH( + append_mode = 'true' +); +/* create sink table */ +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) +); +/* create flow task to calculate the distribution of packet sizes for each status code */ +CREATE FLOW calc_ngx_distribution SINK TO ngx_distribution +EXPIRE AFTER '6h' +AS +SELECT + stat, + trunc(size, -1)::INT as bucket_size, + count(client) AS total_logs, + date_bin('1 minutes'::INTERVAL, access_time) as time_window, +FROM + ngx_access_log +GROUP BY + stat, + time_window, + bucket_size; +``` + +The query aggregates data from the `ngx_access_log` table into the `ngx_distribution` table. +It computes the total number of logs for each status code and packet size bucket (bucket size of 10, as specified by `trunc` with a second argument of -1) within each time window. +The `date_bin` function groups the data into one-minute intervals. +The `EXPIRE AFTER '6h'` ensures that the flow computation only uses source data from the last 6 hours. See more details in [manage-flow](manage-flow.md#expire-after). +Consequently, the `ngx_distribution` table is continuously updated, offering real-time insights into the distribution of packet sizes per status code. + +Now that we have created the flow task, we can insert some data into the source table `ngx_access_log`: + +```sql +INSERT INTO ngx_access_log VALUES + ('cli1', 200, 100, now()), + ('cli2', 200, 104, now()), + ('cli3', 200, 120, now()), + ('cli4', 200, 124, now()), + ('cli5', 200, 140, now()), + ('cli6', 404, 144, now()), + ('cli7', 404, 160, now()), + ('cli8', 404, 164, now()), + ('cli9', 404, 180, now()), + ('cli10', 404, 184, now()); +``` +wait at least few seconds for flow to update results to sink table: + +```sql +SELECT * FROM ngx_distribution; +``` + +```sql ++------+-------------+------------+---------------------+----------------------------+ +| stat | bucket_size | total_logs | time_window | update_at | ++------+-------------+------------+---------------------+----------------------------+ +| 200 | 100 | 2 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | +| 200 | 120 | 2 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | +| 200 | 140 | 1 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | +| 404 | 140 | 1 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | +| 404 | 160 | 2 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | +| 404 | 180 | 2 | 2025-04-24 07:05:00 | 2025-04-24 07:05:56.308000 | ++------+-------------+------------+---------------------+----------------------------+ +6 rows in set (0.00 sec) +``` + +## Using TQL with Flow for Advanced Time-Series Analysis + +:::warning Experimental Feature +This experimental feature may contain unexpected behavior and have its functionality change in the future. +::: + +TQL (Time Query Language) can be seamlessly integrated with Flow to perform advanced time-series computations like rate calculations, moving averages, and other complex time-window operations. This combination allows you to create continuous aggregation flows that leverage TQL's powerful analytical functions for real-time insights. + + +### Understanding TQL Flow Components + +The TQL integration with Flow provides several advantages: + +1. **Time Range Specification**: The `EVAL (start_time, end_time, step)` syntax allows precise control over the evaluation window, see [TQL](/reference/sql/tql.md). +2. **Automatic Schema Generation**: GreptimeDB creates appropriate sink tables based on TQL function outputs +3. **Continuous Processing**: Combined with Flow's scheduling, TQL functions run continuously on incoming data +4. **Advanced Analytics**: Access to sophisticated time-series functions like `rate()`, `increase()`, and statistical aggregations + +### Setting Up the Source Table + +First, let's create a source table to store HTTP request metrics: + +```sql +CREATE TABLE http_requests_total ( + host STRING, + job STRING, + instance STRING, + byte DOUBLE, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY (host, job, instance) +); +``` + +This table will serve as the data source for our TQL-based Flow computations. The `ts` column acts as the time index, while `byte` represents the metric values we want to analyze. + +### Creating a Rate Calculation Flow + +Now we'll create a Flow that uses TQL to calculate the rate of `byte` over time: + +```sql +CREATE FLOW calc_rate +SINK TO rate_reqs +EVAL INTERVAL '1m' AS +TQL EVAL (now() - '1m'::interval, now(), '30s') rate(http_requests_total{job="my_service"}[1m]); +``` + +This Flow definition includes several key components: +- **EVAL INTERVAL '1m'**: Executes the Flow every minute for continuous updates +- **TQL EVAL**: Specifies the time range for evaluation from 1 minute ago to now, see [TQL](/reference/sql/tql.md). +- **rate()**: TQL function that calculates the rate of change +- **[1m]**: Defines a 1-minute lookback window for the rate calculation + +### Examining the Generated Sink Table + +You can inspect the automatically created sink table structure: + +```sql +SHOW CREATE TABLE rate_reqs; +``` + +```sql ++-----------+-------------------------------------+ +| Table | Create Table | ++-----------+-------------------------------------+ +| rate_reqs | CREATE TABLE IF NOT EXISTS `rate_reqs` ( + `ts` TIMESTAMP(3) NOT NULL, + `prom_rate(ts_range,byte,ts,Int64(60000))` DOUBLE NULL, + `host` STRING NULL, + `job` STRING NULL, + `instance` STRING NULL, + TIME INDEX (`ts`), + PRIMARY KEY (`host`, `job`, `instance`) +) + +ENGINE=mito + | ++-----------+-------------------------------------+ +``` + +This shows how GreptimeDB automatically generates the appropriate schema for storing TQL computation results, creating a table with the same structure as the prom ql query result. + +### Testing with Sample Data + +Let's insert some test data to see the Flow in action: + +```sql +INSERT INTO TABLE http_requests_total VALUES + ('localhost', 'my_service', 'instance1', 100, now() - INTERVAL '2' minute), + ('localhost', 'my_service', 'instance1', 200, now() - INTERVAL '1' minute), + ('remotehost', 'my_service', 'instance1', 300, now() - INTERVAL '30' second), + ('remotehost', 'their_service', 'instance1', 300, now() - INTERVAL '30' second), + ('localhost', 'my_service', 'instance1', 400, now()); +``` + +This creates a simple increasing sequence of values over time, which will produce a measurable rate when processed by our TQL Flow. + +### Triggering Flow Execution + +To manually trigger the Flow computation and see immediate results: + +```sql +ADMIN FLUSH_FLOW('calc_rate'); +``` + +This command forces the Flow to process all available data immediately, rather than waiting for the next scheduled interval. + +### Verifying Results + +Finally, verify that the Flow has successfully processed the data: + +```sql +SELECT count(*) > 0 FROM rate_reqs; +``` + +```sql ++---------------------+ +| count(*) > Int64(0) | ++---------------------+ +| true | ++---------------------+ +``` + +This query confirms that the rate calculation has produced results and populated the sink table with computed rate values. + +You can also examine the actual computed rate values: + +```sql +SELECT * FROM rate_reqs; +``` + +```sql ++---------------------+------------------------------------------+-----------+------------+-----------+ +| ts | prom_rate(ts_range,byte,ts,Int64(60000)) | host | job | instance | ++---------------------+------------------------------------------+-----------+------------+-----------+ +| 2025-09-01 13:14:34 | 4.166666666666666 | localhost | my_service | instance1 | +| 2025-09-01 13:15:04 | 4.444444444444444 | localhost | my_service | instance1 | ++---------------------+------------------------------------------+-----------+------------+-----------+ +2 rows in set (0.03 sec) +``` + +Note that the timestamps and exact rate values may vary depending on when you run the example, but you should see similar rate calculations based on the input data pattern. + +### Cleanup + +When you're done experimenting, clean up the resources: + +```sql +DROP FLOW calc_rate; +DROP TABLE http_requests; +DROP TABLE rate_reqs; +``` + +## Next Steps + +- [Manage Flow](manage-flow.md): Gain insights into the mechanisms of the Flow engine and the SQL syntax for defining a Flow. +- [Expressions](expressions.md): Learn about the expressions supported by the Flow engine for data transformation. diff --git a/versioned_docs/version-1.0/user-guide/flow-computation/expressions.md b/versioned_docs/version-1.0/user-guide/flow-computation/expressions.md new file mode 100644 index 0000000000..c34230caa9 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/flow-computation/expressions.md @@ -0,0 +1,21 @@ +--- +keywords: [expressions, aggregate functions, scalar functions, data transformation, SQL functions] +description: Lists supported aggregate and scalar functions in GreptimeDB's flow, including count, sum, avg, min, max, and various scalar functions. It provides links to detailed documentation for each function. +--- + +# Expressions + +## Aggregate functions + +Flow support all aggregate functions that a normal sql query supports such as `COUNT`, `SUM`, `MIN`, `MAX`, etc. For a detailed list, please refer to [Aggregate Functions](/reference/sql/functions/df-functions.md#aggregate-functions). + + +## Scalar functions + +Flow support all scalar functions that a normal sql query supports in our [SQL reference](/reference/sql/functions/overview.md). + +And here are some of the most commonly used scalar functions in 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. diff --git a/versioned_docs/version-1.0/user-guide/flow-computation/manage-flow.md b/versioned_docs/version-1.0/user-guide/flow-computation/manage-flow.md new file mode 100644 index 0000000000..38317635b0 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/flow-computation/manage-flow.md @@ -0,0 +1,245 @@ +--- +keywords: [manage flows, create flow, delete flow, source table, sink table, SQL queries] +description: Describes how to manage flows in GreptimeDB, including creating, updating, and deleting flows. It explains the syntax for creating flows, the importance of sink tables, and how to use the EXPIRE AFTER clause. Examples of SQL queries for managing flows are provided. +--- + +# Manage Flows + +Each `flow` is a continuous aggregation query in GreptimeDB. +It continuously updates the aggregated data based on the incoming data. +This document describes how to create, and delete a flow. + +## Create a Source Table + +Before creating a flow, you need to create a source table to store the raw data. Like this: + +```sql +CREATE TABLE temp_sensor_data ( + sensor_id INT, + loc STRING, + temperature DOUBLE, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY(sensor_id, loc) +); +``` +However, if you don't want to store the raw data, you can use a temporary table as the source table by creating table using `WITH ('ttl' = 'instant')` table option: + +```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'); +``` + +Setting `'ttl'` to `'instant'` will make the table a temporary table, which means it will automatically discard all inserted data and the table will always be empty, only sending them to flow task for computation. + +## Create a Sink Table + +Before creating a flow, you need a sink table to store the aggregated data generated by the flow. +While it is the same to a regular time series table, there are a few important considerations: + +- **Column order and type**: Ensure the order and type of the columns in the sink table match the query result of the flow. +- **Time index**: Specify the `TIME INDEX` for the sink table, typically using the time window column generated by the time window function. +- **Update time**: The Flow engine automatically appends the update time to the end of each computation result row. This update time is stored in the `updated_at` column. Ensure that this column is included in the sink table schema. +- **Tags**: Use `PRIMARY KEY` to specify Tags, which together with the time index serves as a unique identifier for row data and optimizes query performance. + +For example: + +```sql +/* Create sink table */ +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('10 seconds'::INTERVAL, ts) AS time_window +FROM temp_sensor_data +GROUP BY + sensor_id, + loc, + time_window +HAVING max_temp > 100; +``` + +The sink table has the columns `sensor_id`, `loc`, `max_temp`, `time_window`, and `update_at`. + +- The first four columns correspond to the query result columns of flow: `sensor_id`, `loc`, `max(temperature)` and `date_bin('10 seconds'::INTERVAL, ts)` respectively. +- The `time_window` column is specified as the `TIME INDEX` for the sink table. +- The `update_at` column is the last one in the schema to store the update time of the data. +- The `PRIMARY KEY` at the end of the schema definition specifies `sensor_id` and `loc` as the tag columns. + This means the flow will insert or update data based on the tags `sensor_id` and `loc` along with the time index `time_window`. + +## Create a flow + +The grammar to create a flow is: + + + +```sql +CREATE [ OR REPLACE ] FLOW [ IF NOT EXISTS ] +SINK TO +[ EXPIRE AFTER ] +[ COMMENT '' ] +AS +; +``` + +When `OR REPLACE` is specified, any existing flow with the same name will be updated to the new version. It's important to note that this only affects the flow task itself; the source and sink tables will remain unchanged. + +Conversely, when `IF NOT EXISTS` is specified, the command will have no effect if the flow already exists, rather than reporting an error. Additionally, please note that `OR REPLACE` cannot be used in conjunction with `IF NOT EXISTS`. + + +- `flow-name` is an unique identifier in the catalog level. +- `sink-table-name` is the table name where the materialized aggregated data is stored. + It can be an existing table or a new one. `flow` will create the sink table if it doesn't exist. + +- `EXPIRE AFTER` is an optional interval to expire the data from the Flow engine. + For more details, please refer to the [`EXPIRE AFTER`](#expire-after) part. +- `COMMENT` is the description of the flow. +- `SQL` part defines the continuous aggregation query. + It defines the source tables provide data for the flow. + Each flow can have multiple source tables. + Please Refer to [Write a Query](#write-a-sql-query) for the details. + +A simple example to create a flow: + +```sql +CREATE FLOW IF NOT EXISTS my_flow +SINK TO my_sink_table +EXPIRE AFTER '1 hour'::INTERVAL +COMMENT 'My first flow in GreptimeDB' +AS +SELECT + max(temperature) as max_temp, + date_bin('10 seconds'::INTERVAL, ts) as time_window, +FROM temp_sensor_data +GROUP BY time_window; +``` + +The created flow will compute `max(temperature)` for every 10 seconds and store the result in `my_sink_table`. All data comes within 1 hour will be used in the flow. + +### EXPIRE AFTER + +The `EXPIRE AFTER` clause specifies the interval after which data will expire from the flow engine. + +Data in the source table that exceeds the specified expiration time will no longer be included in the flow's calculations. +Similarly, data in the sink table that is older than the expiration time will not be updated. +This means the flow engine will ignore data older than the specified interval during aggregation. +This mechanism helps to manage the state size for stateful queries, such as those involving `GROUP BY`. + +It is important to note that the `EXPIRE AFTER` clause does not delete data from either the source table or the sink table. +It only controls how the flow engine processes the data. +If you want to delete data from the source or sink table, please [set the `TTL` option](/user-guide/manage-data/overview.md#manage-data-retention-with-ttl-policies) when creating tables. + +Setting a reasonable time interval for `EXPIRE AFTER` is helpful to limit state size and avoid memory overflow. This is somewhere similar to the ["Watermarks"](https://docs.risingwave.com/processing/watermarks) concept in streaming processing. + +For example, if the flow engine processes the aggregation at 10:00:00 and the `'1 hour'::INTERVAL` is set, +any input data that arrive now with a time index older than 1 hour (before 09:00:00) will expire and be ignore. +Only data timestamped from 09:00:00 onwards will be used in the aggregation and update to sink table. + +### Write a SQL query + +The `SQL` part of the flow is similar to a standard `SELECT` clause with a few differences. The syntax of the query is as follows: + +```sql +SELECT AGGR_FUNCTION(column1, column2,..) [, TIME_WINDOW_FUNCTION() as time_window] FROM GROUP BY {time_window | column1, column2,.. }; +``` + +Only the following types of expressions are allowed after the `SELECT` keyword: +- Aggregate functions: Refer to the [Expressions](expressions.md) documentation for details. +- Time window functions: Refer to the [define time window](#define-time-window) section for details. +- Scalar functions: Such as `col`, `to_lowercase(col)`, `col + 1`, etc. This part is the same as in a standard `SELECT` clause in GreptimeDB. + +The following points should be noted about the rest of the query syntax: +- The query must include a `FROM` clause to specify the source table. + As join clauses are currently not supported, + the query can only aggregate columns from a single table. +- `WHERE` and `HAVING` clauses are supported. + The `WHERE` clause filters data before aggregation, + while the `HAVING` clause filters data after aggregation. +- `DISTINCT` currently only works with the `SELECT DISTINCT column1 ..` syntax. + It is used to remove duplicate rows from the result set. + Support for `SELECT count(DISTINCT column1) ...` is not available yet but will be added in the future. +- The `GROUP BY` clause works the same as a standard queries, + grouping data by specified columns. + The time window column in the `GROUP BY` clause is crucial for continuous aggregation scenarios. + Other expressions in `GROUP BY` can include literals, columns, or scalar expressions. +- `ORDER BY`, `LIMIT`, and `OFFSET` are not supported. + +Refer to [Continuous Aggregation](continuous-aggregation.md) for more examples of how to use continuous aggregation in real-time analytics, monitoring, and dashboards. + +### Define time window + +A time window is a crucial attribute of your continuous aggregation query. +It determines how data is aggregated within the flow. +These time windows are left-closed and right-open intervals. + +A time window represents a specific range of time. +Data from the source table is mapped to the corresponding window based on the time index column. +The time window also defines the scope for each calculation of an aggregation expression, +resulting in one row per time window in the result table. + +You can use `date_bin()` after the `SELECT` keyword to define fixed time windows. +For example: + +```sql +SELECT + max(temperature) as max_temp, + date_bin('10 seconds'::INTERVAL, ts) as time_window +FROM temp_sensor_data +GROUP BY time_window; +``` + +In this example, the `date_bin('10 seconds'::INTERVAL, ts)` function creates 10-second time windows starting from UTC 00:00:00. +The `max(temperature)` function calculates the maximum temperature value within each time window. + +For more details on the behavior of the function, +please refer to [`date_bin`](/reference/sql/functions/df-functions.md#date_bin). + +:::tip NOTE +Currently, flow rely on the time window expr to determine how to incrementally update the result. So it's better to use a relatively small time window when possible. +::: + +## Flush a flow + +The flow engine automatically processes aggregation operations within a short period(i.e. few seconds) when new data arrives in the source table. +However, you can manually trigger the flow engine to process the aggregation operation immediately using the `ADMIN FLUSH_FLOW` command. + +```sql +ADMIN FLUSH_FLOW('') +``` + +## Delete a flow + +To delete a flow, use the following `DROP FLOW` clause: + +```sql +DROP FLOW [IF EXISTS] +``` + +For example: + +```sql +DROP FLOW IF EXISTS my_flow; +``` diff --git a/versioned_docs/version-1.0/user-guide/flow-computation/overview.md b/versioned_docs/version-1.0/user-guide/flow-computation/overview.md new file mode 100644 index 0000000000..48a9da5d57 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/flow-computation/overview.md @@ -0,0 +1,125 @@ +--- +keywords: [Flow engine, real-time computation, ETL, data streams, user agent statistics, nginx logs] +description: Discover how GreptimeDB's Flow engine enables real-time computation of data streams for ETL processes and on-the-fly calculations. Learn about its programming model, use cases, and a quick start example for calculating user agent statistics from nginx logs. +--- + +# Flow Computation + +GreptimeDB's Flow engine enables real-time computation of data streams. +It is particularly beneficial for Extract-Transform-Load (ETL) processes or for performing on-the-fly filtering, calculations and queries such as sum, average, and other aggregations. +The Flow engine ensures that data is processed incrementally and continuously, +updating the final results as new streaming data arrives. +You can think of it as a clever materialized views that know when to update result view table and how to update it with minimal effort. + +Use cases include: + +- Real-time analytics that deliver actionable insights almost instantaneously. +- Downsampling data points, such as using average pooling, to reduce the volume of data for storage and analysis. + +## Programming Model + +Upon data insertion into the source table, +the data is concurrently ingested to the Flow engine. +At each trigger interval (one second), +the Flow engine executes the specified computations and updates the sink table with the results. +Both the source and sink tables are time-series tables within GreptimeDB. +Before creating a Flow, +it is crucial to define the schemas for these tables and design the Flow to specify the computation logic. +This process is visually represented in the following image: + +![Continuous Aggregation](/flow-ani.svg) + +## Quick Start Example + +To illustrate the capabilities of GreptimeDB's Flow engine, +consider the task of calculating user agent statistics from nginx logs. +The source table is `nginx_access_log`, +and the sink table is `user_agent_statistics`. + +First, create the source table `nginx_access_log`. +To optimize performance for counting the `user_agent` field, +specify it as a `TAG` column type using the `PRIMARY KEY` keyword. + +```sql +CREATE TABLE ngx_http_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'); +``` + +Next, create the sink table `user_agent_statistics`. +The `update_at` column tracks the last update time of the record, which is automatically updated by the Flow engine. +Although all tables in GreptimeDB are time-series tables, this computation does not require time windows. +Therefore, the `__ts_placeholder` column is included as a time index 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) +); +``` + +Finally, create the Flow `user_agent_flow` to count the occurrences of each user agent in the `ngx_http_log` table. + +```sql +CREATE FLOW user_agent_flow +SINK TO user_agent_statistics +AS +SELECT + user_agent, + COUNT(user_agent) AS total_count +FROM + ngx_http_log +GROUP BY + user_agent; +``` + +Once the Flow is created, +the Flow engine will continuously process data from the `ngx_http_log` table and update the `user_agent_statistics` table with the computed results. + +To observe the results, +insert sample data into the `ngx_http_log` table. + +```sql +INSERT INTO ngx_http_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'); +``` + +After inserting the data, +query the `user_agent_statistics` table to view the results. + +```sql +SELECT * FROM user_agent_statistics; +``` + +The query results will display the total count of each user agent in the `user_agent_statistics` table. + +```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 | ++-------------+-------------+----------------------------+---------------------+ +``` + +## Next Steps + +- [Continuous Aggregation](./continuous-aggregation.md): Explore the primary scenario in time-series data processing, with three common use cases for continuous aggregation. +- [Manage Flow](manage-flow.md): Gain insights into the mechanisms of the Flow engine and the SQL syntax for defining a Flow. +- [Expressions](expressions.md): Learn about the expressions supported by the Flow engine for data transformation. + diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/emqx.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/emqx.md new file mode 100644 index 0000000000..a48cc28301 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/emqx.md @@ -0,0 +1,10 @@ +--- +keywords: [EMQX, MQTT broker, IoT, real-time messaging, data integration, data ingestion] +description: Overview of integrating GreptimeDB with EMQX, an open-source MQTT broker for IoT and real-time messaging applications. +--- + +# EMQX + +[EMQX](https://www.emqx.io/) is an open-source, highly scalable, and feature-rich MQTT broker designed for IoT and real-time messaging applications. It supports various protocols, including MQTT (3.1, 3.1.1, and 5.0), HTTP, QUIC, and WebSocket. + +GreptimeDB can be used as a data system for EMQX. To learn how to integrate GreptimeDB with EMQX, please refer to [Ingest MQTT Data into GreptimeDB](https://docs.emqx.com/en/emqx/latest/data-integration/data-bridge-greptimedb.html). diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/go.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/go.md new file mode 100644 index 0000000000..d9c88fd1d3 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/go.md @@ -0,0 +1,315 @@ +--- +keywords: [Go SDK, gRPC, data ingestion, installation, connection, low-level API, high-level API] +description: Guide on using the Go ingester SDK for GreptimeDB, including installation, connection, data model, and examples of low-level and high-level APIs. +--- + +# Go + +GreptimeDB offers ingester libraries for high-throughput data writing. +It utilizes the gRPC protocol, +which supports schemaless writing and eliminates the need to create tables before writing data. +For more information, refer to [Automatic Schema Generation](/user-guide/ingest-data/overview.md#automatic-schema-generation). + +The Go ingester SDK provided by GreptimeDB is a lightweight, +concurrent-safe library that is easy to use with the metric struct. + +## Quick start demos + +To quickly get started, you can explore the [quick start demos](https://github.com/GreptimeTeam/greptimedb-ingester-go/tree/main/examples) to understand how to use the GreptimeDB Go ingester SDK. + +## Installation + +Use the following command to install the GreptimeDB client library for Go: + +```shell +go get -u github.com/GreptimeTeam/greptimedb-ingester-go@VAR::goSdkVersion +``` + +Import the library in your code: + +```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" +) +``` + +## Connect to database + +If you have set the [`--user-provider` configuration](/user-guide/deployments-administration/authentication/overview.md) when starting GreptimeDB, +you will need to provide a username and password to connect to GreptimeDB. +The following example shows how to set the username and password when using the library to connect to GreptimeDB. + +```go +cfg := greptime.NewConfig("127.0.0.1"). + // change the database name to your database name + WithDatabase("public"). + // Default port 4001 + // WithPort(4001). + // Enable secure connection if your server is secured by TLS + // WithInsecure(false). + // set authentication information + // If the database doesn't require authentication, just remove the WithAuth method + WithAuth("username", "password") + +cli, _ := greptime.NewClient(cfg) +defer cli.Close() +``` + +## Data model + +Each row item in a table consists of three types of columns: `Tag`, `Timestamp`, and `Field`. For more information, see [Data Model](/user-guide/concepts/data-model.md). +The types of column values could be `String`, `Float`, `Int`, `Timestamp`, `JSON` etc. For more information, see [Data Types](/reference/sql/data-types.md). + +## Set table options + +Although the time series table is created automatically when writing data to GreptimeDB via the SDK, +you can still configure table options. +The SDK supports the following table options: + +- `auto_create_table`: Default is `True`. If set to `False`, it indicates that the table already exists and does not need automatic creation, which can improve write performance. +- `ttl`, `append_mode`, `merge_mode`: For more details, refer to the [table options](/reference/sql/create.md#table-options). + +You can set table options using the `ingesterContext` context. +For example, to set the `ttl` option, use the following code: + +```go +hints := []*ingesterContext.Hint{ + { + Key: "ttl", + Value: "3d", + }, +} + +ctx, cancel := context.WithTimeout(context.Background(), time.Second*3) +ctx = ingesterContext.New(ctx, ingesterContext.WithHint(hints)) +// Use the ingesterContext when writing data to GreptimeDB. +// The `data` object is described in the following sections. +resp, err := cli.Write(ctx, data) +if err != nil { + return err +} +``` + +For how to write data to GreptimeDB, see the following sections. + +## Low-level API + +The GreptimeDB low-level API provides a straightforward method to write data to GreptimeDB +by adding rows to the table object with a predefined schema. + +### Create row objects + +This following code snippet begins by constructing a table named `cpu_metric`, +which includes columns `host`, `cpu_user`, `cpu_sys`, and `ts`. +Subsequently, it inserts a single row into the table. + +The table consists of three types of columns: + +- `Tag`: The `host` column, with values of type `String`. +- `Field`: The `cpu_user` and `cpu_sys` columns, with values of type `Float`. +- `Timestamp`: The `ts` column, with values of type `Timestamp`. + +```go +// Construct the table schema for CPU metrics +cpuMetric, err := table.New("cpu_metric") +if err != nil { + // Handle error appropriately +} + +// Add a 'Tag' column for host identifiers +cpuMetric.AddTagColumn("host", types.STRING) +// Add a 'Timestamp' column for recording the time of data collection +cpuMetric.AddTimestampColumn("ts", types.TIMESTAMP_MILLISECOND) +// Add 'Field' columns for user and system CPU usage measurements +cpuMetric.AddFieldColumn("cpu_user", types.FLOAT) +cpuMetric.AddFieldColumn("cpu_sys", types.FLOAT) + +// Insert example data +// NOTE: The arguments must be in the same order as the columns in the defined schema: host, ts, cpu_user, cpu_sys +err = cpuMetric.AddRow("127.0.0.1", time.Now(), 0.1, 0.12) +err = cpuMetric.AddRow("127.0.0.1", time.Now(), 0.11, 0.13) +if err != nil { + // Handle error appropriately +} + +``` + +To improve the efficiency of writing data, you can create multiple rows at once to write to GreptimeDB. + +```go +cpuMetric, err := table.New("cpu_metric") +if err != nil { + // Handle error appropriately +} +cpuMetric.AddTagColumn("host", types.STRING) +cpuMetric.AddTimestampColumn("ts", types.TIMESTAMP_MILLISECOND) +cpuMetric.AddFieldColumn("cpu_user", types.FLOAT) +cpuMetric.AddFieldColumn("cpu_sys", types.FLOAT) +err = cpuMetric.AddRow("127.0.0.1", time.Now(), 0.1, 0.12) +if err != nil { + // Handle error appropriately +} + +memMetric, err := table.New("mem_metric") +if err != nil { + // Handle error appropriately +} +memMetric.AddTagColumn("host", types.STRING) +memMetric.AddTimestampColumn("ts", types.TIMESTAMP_MILLISECOND) +memMetric.AddFieldColumn("mem_usage", types.FLOAT) +err = memMetric.AddRow("127.0.0.1", time.Now(), 112) +if err != nil { + // Handle error appropriately +} +``` + +### Insert data + +The following example shows how to insert rows to tables in GreptimeDB. + +```go +resp, err := cli.Write(ctx, cpuMetric, memMetric) +if err != nil { + // Handle error appropriately +} +log.Printf("affected rows: %d\n", resp.GetAffectedRows().GetValue()) +``` + +### Streaming insert + +Streaming insert is useful when you want to insert a large amount of data such as importing historical data. + +```go +err := cli.StreamWrite(ctx, cpuMetric, memMetric) +if err != nil { + // Handle error appropriately +} +``` + +Close the stream writing after all data has been written. +In general, you do not need to close the stream writing when continuously writing data. + +```go +affected, err := cli.CloseStream(ctx) +``` + +## High-level API + +The high-level API uses an ORM style object to write data to GreptimeDB. +It allows you to create, insert, and update data in a more object-oriented way, +providing developers with a friendlier experience. +However, it is not as efficient as the low-level API. +This is because the ORM style object may consume more resources and time when converting the objects. + +### Create row objects + +```go +type CpuMetric struct { + Host string `greptime:"tag;column:host;type:string"` + CpuUser float64 `greptime:"field;column:cpu_user;type:float64"` + CpuSys float64 `greptime:"field;column:cpu_sys;type:float64"` + Ts time.Time `greptime:"timestamp;column:ts;type:timestamp;precision:millisecond"` +} + +func (CpuMetric) TableName() string { + return "cpu_metric" +} + +cpuMetrics := []CpuMetric{ + { + Host: "127.0.0.1", + CpuUser: 0.10, + CpuSys: 0.12, + Ts: time.Now(), + } +} +``` + +### Insert data + +```go +resp, err := cli.WriteObject(ctx, cpuMetrics) +log.Printf("affected rows: %d\n", resp.GetAffectedRows().GetValue()) +``` + +### Streaming insert + +Streaming insert is useful when you want to insert a large amount of data such as importing historical data. + +```go +err := cli.StreamWriteObject(ctx, cpuMetrics) +``` + +Close the stream writing after all data has been written. +In general, you do not need to close the stream writing when continuously writing data. + +```go +affected, err := cli.CloseStream(ctx) +``` + +## Insert data in JSON type + +GreptimeDB supports storing complex data structures using [JSON type data](/reference/sql/data-types.md#json-type). +With this ingester library, you can insert JSON data using string values. +For instance, if you have a table named `sensor_readings` and wish to add a JSON column named `attributes`, +refer to the following code snippet. + +In the [low-level API](#low-level-api), +you can specify the column type as `types.JSON` using the `AddFieldColumn` method to add a JSON column. +Then, use a `struct` or `map` to insert JSON data. + +```go +sensorReadings, err := table.New("sensor_readings") +// The code for creating other columns is omitted +// ... +// specify the column type as JSON +sensorReadings.AddFieldColumn("attributes", types.JSON) + +// Use struct to insert JSON data +type Attributes struct { + Location string `json:"location"` + Action string `json:"action"` +} +attributes := Attributes{ Location: "factory-1" } +sensorReadings.AddRow(... , attributes) + +// The following code for writing data is omitted +// ... +``` + +In the [high-level API](#high-level-api), you can specify the column type as JSON using the `greptime:"field;column:details;type:json"` tag. + +```go +type SensorReadings struct { + // The code for creating other columns is omitted + // ... + // specify the column type as JSON + Attributes string `greptime:"field;column:details;type:json"` + // ... +} + +// Use struct to insert JSON data +type Attributes struct { + Location string `json:"location"` + Action string `json:"action"` +} +attributes := Attributes{ Action: "running" } +sensor := SensorReadings{ + // ... + Attributes: attributes, +} + +// The following code for writing data is omitted +// ... +``` + +For the executable code for inserting JSON data, please refer to the [example](https://github.com/GreptimeTeam/greptimedb-ingester-go/tree/main/examples/jsondata) in the SDK repository. + + +## Ingester library reference + +- [API Documentation](https://pkg.go.dev/github.com/GreptimeTeam/greptimedb-ingester-go) + diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/java.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/java.md new file mode 100644 index 0000000000..d6cbaa61df --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/java.md @@ -0,0 +1,491 @@ +--- +keywords: [Java SDK, gRPC, data ingestion, installation, connection, Batching Write, Streaming Write, Bulk Write] +description: Guide on using the Java ingester SDK for GreptimeDB, including installation, connection, data model, and examples of low-level and high-level APIs. +--- + +# Java Ingester for GreptimeDB + +GreptimeDB offers ingester libraries for high-throughput data writing. +It utilizes the gRPC protocol, +which supports schemaless writing and eliminates the need to create tables before writing data. +For more information, refer to [Automatic Schema Generation](/user-guide/ingest-data/overview.md#automatic-schema-generation). + +The Java ingester SDK provided by GreptimeDB is a lightweight, high-performance client designed for efficient time-series data ingestion. It leverages the gRPC protocol to provide a non-blocking, purely asynchronous API that delivers exceptional throughput while maintaining seamless integration with your applications. + +This client offers multiple ingestion methods optimized for various performance requirements and use cases. You can select the approach that best suits your specific needs—whether you require simple unary writes for low-latency operations or high-throughput bulk streaming for maximum efficiency when handling large volumes of time-series data. + +## High Level Architecture + +``` ++-----------------------------------+ +| Client Applications | +| +------------------+ | +| | Application Code | | +| +------------------+ | ++-------------+---------------------+ + | + v ++-------------+---------------------+ +| API Layer | +| +---------------+ | +| | GreptimeDB | | +| +---------------+ | +| / \ | +| v v | +| +-------------+ +-------------+ | +------------------+ +| | BulkWrite | | Write | | | Data Model | +| | Interface | | Interface | |------->| | +| +-------------+ +-------------+ | | +------------+ | ++-------|----------------|----------+ | | Table | | + | | | +------------+ | + v v | | | ++-------|----------------|----------+ | v | +| Transport Layer | | +------------+ | +| +-------------+ +-------------+ | | | TableSchema| | +| | BulkWrite | | Write | | | +------------+ | +| | Client | | Client | | +------------------+ +| +-------------+ +-------------+ | +| | \ / | | +| | \ / | | +| | v v | | +| | +-------------+ | | +| | |RouterClient | | | ++-----|--+-------------|---+--------+ + | | | | + | | | | + v v v | ++-----|----------------|---|--------+ +| Network Layer | +| +-------------+ +-------------+ | +| | Arrow Flight| | gRPC Client | | +| | Client | | | | +| +-------------+ +-------------+ | +| | | | ++-----|----------------|------------+ + | | + v v + +-------------------------+ + | GreptimeDB Server | + +-------------------------+ +``` + +- **API Layer**: Provides high-level interfaces for client applications to interact with GreptimeDB +- **Data Model**: Defines the structure and organization of time series data with tables and schemas +- **Transport Layer**: Handles communication logistics, request routing, and client management +- **Network Layer**: Manages low-level protocol communications using Arrow Flight and gRPC + +## How To Use + +### Installation + +1. Install the Java Development Kit(JDK) + +Make sure that your system has JDK 8 or later installed. For more information on how to +check your version of Java and install the JDK, see the [Oracle Overview of JDK Installation documentation](https://www.oracle.com/java/technologies/javase-downloads.html) + +2. Add GreptiemDB Java SDK as a Dependency + +If you are using [Maven](https://maven.apache.org/), add the following to your pom.xml +dependencies list: + +```xml + + io.greptime + ingester-all + VAR::javaSdkVersion + +``` + +The latest version can be viewed [here](https://central.sonatype.com/search?q=io.greptime&name=ingester-all). + +After configuring your dependencies, make sure they are available to your project. This may require refreshing the project in your IDE or running the dependency manager. + +### Client Initialization + +The entry point to the GreptimeDB Ingester Java client is the `GreptimeDB` class. You create a client instance by calling the static create method with appropriate configuration options. + +```java +// GreptimeDB has a default database named "public" in the default catalog "greptime", +// we can use it as the test database +String database = "public"; +// By default, GreptimeDB listens on port 4001 using the gRPC protocol. +// We can provide multiple endpoints that point to the same GreptimeDB cluster. +// The client will make calls to these endpoints based on a load balancing strategy. +// The client performs regular health checks and automatically routes requests to healthy nodes, +// providing fault tolerance and improved reliability for your application. +String[] endpoints = {"127.0.0.1:4001"}; +// Sets authentication information. +AuthInfo authInfo = new AuthInfo("username", "password"); +GreptimeOptions opts = GreptimeOptions.newBuilder(endpoints, database) + // If the database does not require authentication, we can use `AuthInfo.noAuthorization()` as the parameter. + .authInfo(authInfo) + // Enable secure connection if your server is secured by TLS + //.tlsOptions(new TlsOptions()) + // A good start ^_^ + .build(); + +// Initialize the client +// NOTE: The client instance is thread-safe and should be reused as a global singleton +// for better performance and resource utilization. +GreptimeDB client = GreptimeDB.create(opts); +``` + +### Writing Data + +The ingester provides a unified approach for writing data to GreptimeDB through the `Table` abstraction. All data writing operations, including high-level APIs, are built on top of this fundamental structure. To write data, you create a `Table` with your time series data and write it to the database. + +#### Creating and Writing Tables + +Define a table schema and create a table: + +```java +// Create a table schema +TableSchema schema = TableSchema.newBuilder("metrics") + .addTag("host", DataType.String) + .addTag("region", DataType.String) + .addField("cpu_util", DataType.Float64) + .addField("memory_util", DataType.Float64) + .addTimestamp("ts", DataType.TimestampMillisecond) + .build(); + +// Create a table from the schema +Table table = Table.from(schema); + +// Add rows to the table +// The values must be provided in the same order as defined in the schema +// In this case: addRow(host, region, cpu_util, memory_util, ts) +table.addRow("host1", "us-west-1", 0.42, 0.78, System.currentTimeMillis()); +table.addRow("host2", "us-west-2", 0.46, 0.66, System.currentTimeMillis()); +// Add more rows +// .. + +// Complete the table to make it immutable. This finalizes the table for writing. +// If users forget to call this method, it will automatically be called internally +// before the table data is written. +table.complete(); + +// Write the table to the database +CompletableFuture> future = client.write(table); +``` + +GreptimeDB supports storing complex data structures using [JSON type data](/reference/sql/data-types.md#json-type). You can define JSON columns in your table schema and insert data using Map objects: + +```java +// Construct the table schema for sensor_readings +TableSchema sensorReadings = TableSchema.newBuilder("sensor_readings") + // The code for creating other columns is omitted + // ... + // specify the column type as JSON + .addField("attributes", DataType.Json) + .build(); + +// ... +// Use map to insert JSON data +Map attr = new HashMap<>(); +attr.put("location", "factory-1"); +sensorReadings.addRow(... , attr); +``` + +##### TableSchema + +The `TableSchema` defines the structure for writing data to GreptimeDB. It specifies the table structure including column names, semantic types, and data types. For detailed information about column semantic types (`Tag`, `Timestamp`, `Field`), refer to the [Data Model](/user-guide/concepts/data-model.md) documentation. + +##### Table + +The `Table` interface represents data that can be written to GreptimeDB. It provides methods for adding rows and manipulating the data. Essentially, `Table` temporarily stores data in memory, allowing you to accumulate multiple rows for batch processing before sending them to the database, which significantly improves write efficiency compared to writing individual rows. + +A table goes through several distinct lifecycle stages: + +1. **Creation**: Initialize a table from a schema using `Table.from(schema)` +2. **Data Addition**: Populate the table with rows using `addRow()` method +3. **Completion**: Finalize the table with `complete()` when all rows have been added +4. **Writing**: Send the completed table to the database + +Important considerations: +- Tables are not thread-safe and should be accessed from a single thread +- Tables cannot be reused after writing - create a new instance for each write operation +- The associated `TableSchema` is immutable and can be safely reused across multiple operations + +### Write Operations + +Although the time series table is created automatically when writing data to GreptimeDB via the SDK, +you can still configure table options. +The SDK supports the following table options: + +- `auto_create_table`: Default is `True`. If set to `False`, it indicates that the table already exists and does not need automatic creation, which can improve write performance. +- `ttl`, `append_mode`, `merge_mode`: For more details, refer to the [table options](/reference/sql/create.md#table-options). + +You can set table options using the `Context`. +For example, to set the `ttl` option, use the following code: + +```java +Context ctx = Context.newDefault(); +// Add a hint to make the database create a table with the specified TTL (time-to-live) +ctx = ctx.withHint("ttl", "3d"); +// Set the compression algorithm to Zstd. +ctx = ctx.withCompression(Compression.Zstd); +// Use the ctx when writing data to GreptimeDB +CompletableFuture> future = client.write(Arrays.asList(table1, table2), WriteOp.Insert, ctx); +``` + +For how to write data to GreptimeDB, see the following sections. + +### Batching Write + +Batching write allows you to write data to multiple tables in a single request. It returns a `CompletableFuture>` and provides good performance through asynchronous execution. + +This is the recommended way to write data to GreptimeDB for most use cases. + +```java +// The batching write API +CompletableFuture> future = client.write(table1, table2, table3); + +// For performance reasons, the SDK is designed to be purely asynchronous. +// The return value is a CompletableFuture object. If you want to immediately obtain +// the result, you can call `future.get()`, which will block until the operation completes. +// For production environments, consider using non-blocking approaches with callbacks or +// the CompletableFuture API. +Result result = future.get(); +``` + +### Streaming Write + +The streaming write API maintains a persistent connection to GreptimeDB for continuous data ingestion with rate limiting. It allows writing data from multiple tables through a single stream. + +Use this API when you need: +- Continuous data collection with moderate volume +- Writing to multiple tables via one connection +- Cases where simplicity and convenience are more important than maximum throughput + +```java +// Create a stream writer +StreamWriter writer = client.streamWriter(); + +// Write multiple tables +writer.write(table1) + .write(table2) + .write(table3); + +// Complete the stream and get the result +CompletableFuture result = writer.completed(); +``` + +You can also set a rate limit for stream writing: + +```java +// Limit to 1000 points per second +StreamWriter writer = client.streamWriter(1000); +``` + +### Bulk Write + +The Bulk Write API provides a high-performance, memory-efficient mechanism for ingesting large volumes of time-series data into GreptimeDB. It leverages off-heap memory management to achieve optimal throughput when writing batches of data. + +**Important**: +1. **Manual Table Creation Required**: Bulk API does **not** create tables automatically. You must create the table beforehand using either: + - Insert API (which supports auto table creation), or + - SQL DDL statements (CREATE TABLE) +2. **Schema Matching**: The table template in bulk API must exactly match the existing table schema. +3. **Column Types**: For bulk operations, currently use `addField()` instead of `addTag()`. Tag columns are part of the primary key in GreptimeDB, but bulk operations don't yet support tables with tag columns. This limitation will be addressed in future versions. + +This API supports writing to one table per stream and handles large data volumes (up to 200MB per write) with adaptive flow control. Performance advantages include: +- Off-heap memory management with Arrow buffers +- Efficient binary serialization and data transfer +- Optional compression +- Batched operations + +This approach is particularly well-suited for: +- Large-scale batch processing and data migrations +- High-throughput log and sensor data ingestion +- Time-series applications with demanding performance requirements +- Systems processing high-frequency data collection + +Here's a typical pattern for using the Bulk Write API: + +```java +// Create a BulkStreamWriter with the table schema +try (BulkStreamWriter writer = greptimeDB.bulkStreamWriter(schema)) { + // Write multiple batches + for (int batch = 0; batch < batchCount; batch++) { + // Get a TableBufferRoot for this batch + Table.TableBufferRoot table = writer.tableBufferRoot(1000); // column buffer size + + // Add rows to the batch + for (int row = 0; row < rowsPerBatch; row++) { + Object[] rowData = generateRow(batch, row); + table.addRow(rowData); + } + + // Complete the table to prepare for transmission + table.complete(); + + // Send the batch and get a future for completion + CompletableFuture future = writer.writeNext(); + + // Wait for the batch to be processed (optional) + Integer affectedRows = future.get(); + + System.out.println("Batch " + batch + " wrote " + affectedRows + " rows"); + } + + // Signal completion of the stream + writer.completed(); +} +``` + +#### Configuration + +The Bulk Write API can be configured with several options to optimize performance: + +```java +BulkWrite.Config cfg = BulkWrite.Config.newBuilder() + .allocatorInitReservation(64 * 1024 * 1024L) // Customize memory allocation: 64MB initial reservation + .allocatorMaxAllocation(4 * 1024 * 1024 * 1024L) // Customize memory allocation: 4GB max allocation + .timeoutMsPerMessage(60 * 1000) // 60 seconds timeout per request + .maxRequestsInFlight(8) // Concurrency Control: Configure with 10 maximum in-flight requests + .build(); +// Enable Zstd compression +Context ctx = Context.newDefault().withCompression(Compression.Zstd); + +BulkStreamWriter writer = greptimeDB.bulkStreamWriter(schema, cfg, ctx); +``` + +### Resource Management + +It's important to properly shut down the client when you're finished using it: + +```java +// Gracefully shut down the client +client.shutdownGracefully(); +``` + +### Performance Tuning + +#### Compression Options + +The ingester supports various compression algorithms to reduce network bandwidth and improve throughput. + +```java +// Set the compression algorithm to Zstd +Context ctx = Context.newDefault().withCompression(Compression.Zstd); +``` + +#### Write Operation Comparison + +Understanding the performance characteristics of different write methods is crucial for optimizing data ingestion. + +| Write Method | API | Throughput | Latency | Memory Efficiency | CPU Usage | Best For | Limitations | +|--------------|-----|------------|---------|-------------------|-----------|----------|-------------| +| Batching Write | `write(tables)` | Better | Good | High | Higher | Simple applications, low latency requirements | Lower throughput for large volumes | +| Streaming Write | `streamWriter()` | Moderate | Good | Moderate | Moderate | Continuous data streams, moderate throughput | More complex to use than regular writes | +| Bulk Write | `bulkStreamWriter()` | Best | Higher | Best | Moderate | Maximum throughput, large batch operations | Higher latency, requires manual table creation | + +#### Buffer Size Optimization + +When using `BulkStreamWriter`, you can configure the column buffer size: + +```java +// Get the table buffer with a specific column buffer size +Table.TableBufferRoot table = bulkStreamWriter.tableBufferRoot(columnBufferSize); +``` + +This option can significantly improve the speed of data conversion to the underlying format. For optimal performance, we recommend setting the column buffer size to 1024 or larger, depending on your specific workload characteristics and available memory. + +### Export Metrics + +The ingester exposes comprehensive metrics that enable you to monitor its performance, health, and operational status. + +For detailed information about available metrics and their usage, refer to the [Ingester Prometheus Metrics](https://github.com/GreptimeTeam/greptimedb-ingester-java/tree/main/ingester-prometheus-metrics) documentation. + + +## Key Configuration Options + +`GreptimeOptions` is the main configuration class for the GreptimeDB Java client, used to configure client connections, write options, RPC settings, and various other parameters. + +For production environments, you may need to configure these commonly used options. Complete reference: [GreptimeOptions JavaDoc](https://javadoc.io/static/io.greptime/ingester-protocol/VAR::javaSdkVersion/io/greptime/options/GreptimeOptions.html). + +**Key Options:** +- `database`: Target database name, format `[catalog-]schema` (default: `public`) +- `authInfo`: Authentication credentials for production environments +- `rpcOptions.defaultRpcTimeout`: RPC request timeout (default: 60 seconds) +- `writeMaxRetries`: Maximum retries for failed writes (default: 1) +- `maxInFlightWritePoints`: Maximum data points in-flight for write flow control (default: 655360) +- `writeLimitedPolicy`: Policy when write flow limit exceeded (default: AbortOnBlockingTimeoutPolicy 3s) +- `defaultStreamMaxWritePointsPerSecond`: Rate limit for StreamWriter (default: 655360) + +```java +// Production-ready configuration +RpcOptions rpcOpts = RpcOptions.newDefault(); +rpcOpts.setDefaultRpcTimeout(30000); // 30 seconds timeout + +AuthInfo authInfo = new AuthInfo("username", "password"); + +GreptimeOptions options = GreptimeOptions.newBuilder("127.0.0.1:4001", "production_db") + .authInfo(authInfo) + .rpcOptions(rpcOpts) + .writeMaxRetries(3) + .maxInFlightWritePoints(1000000) + .writeLimitedPolicy(new LimitedPolicy.AbortOnBlockingTimeoutPolicy(5, TimeUnit.SECONDS)) + .defaultStreamMaxWritePointsPerSecond(50000) + .build(); +``` + +## FAQ + +### Why am I getting some connection exceptions? + +When using the GreptimeDB Java ingester SDK, you may encounter some connection exceptions. +For example, exceptions that are "`Caused by: java.nio.channels.UnsupportedAddressTypeException`", +"`Caused by: java.net.ConnectException: connect(..) failed: Address family not supported by protocol`", or +"`Caused by: java.net.ConnectException: connect(..) failed: Invalid argument`". While you are certain that the +GreptimeDB server is running, and its endpoint is reachable. + +These connection exceptions could be all because the gRPC's `io.grpc.NameResolverProvider` service provider is not +packaged into the final JAR, during the assembling process. So the fix can be: + +- If you are using Maven Assembly plugin, add the `metaInf-services` container descriptor handler to your assembly + file, like this: + ```xml + + ... + + + metaInf-services + + + + ``` +- And if you are using Maven Shade plugin, you can add the `ServicesResourceTransformer` instead: + ```xml + + ... + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + + shade + + + + + + + + + + + + ... + + ``` + +## API Documentation and Examples +- [API Reference](https://javadoc.io/doc/io.greptime/ingester-protocol/latest/index.html) +- [Examples](https://github.com/GreptimeTeam/greptimedb-ingester-java/tree/main/ingester-example/) \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/overview.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/overview.md new file mode 100644 index 0000000000..184dcf0492 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/grpc-sdks/overview.md @@ -0,0 +1,11 @@ +--- +keywords: [gRPC SDK, client libraries, data ingestion, Go, Java] +description: Demonstrates how to use client libraries to write data in GreptimeDB, with links to guides for Go and Java. +--- + +# gRPC SDKs + +This guide will demonstrate how to use client libraries to write data in GreptimeDB. + +- [Go](go.md) +- [Java](java.md) diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/influxdb-line-protocol.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/influxdb-line-protocol.md new file mode 100644 index 0000000000..d0cbae0a77 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/influxdb-line-protocol.md @@ -0,0 +1,209 @@ +--- +keywords: [InfluxDB Line Protocol, HTTP API, data ingestion, Telegraf integration, data model, authentication] +description: Guide on using InfluxDB Line Protocol to ingest data into GreptimeDB, including examples, authentication, Telegraf integration, and data model differences. +--- + +# InfluxDB Line Protocol + +GreptimeDB supports HTTP InfluxDB Line protocol. + +## Ingest data + +### Protocols + +#### Post metrics + +You can write data to GreptimeDB using the `/influxdb/write` API. +Here's an example of how to use this API: + + + + + +```shell +curl -i -XPOST "http://localhost:4000/v1/influxdb/api/v2/write?db=public&precision=ms" \ + -H "authorization: token {{greptime_user:greptimedb_password}}" \ + --data-binary \ + 'monitor,host=127.0.0.1 cpu=0.1,memory=0.4 1667446797450 + monitor,host=127.0.0.2 cpu=0.2,memory=0.3 1667446798450 + monitor,host=127.0.0.1 cpu=0.5,memory=0.2 1667446798450' +``` + + + + +```shell +curl -i -XPOST "http://localhost:4000/v1/influxdb/write?db=public&precision=ms&u={{greptime_user}}&p={{greptimedb_password}}" \ +--data-binary \ +'monitor,host=127.0.0.1 cpu=0.1,memory=0.4 1667446797450 + monitor,host=127.0.0.2 cpu=0.2,memory=0.3 1667446798450 + monitor,host=127.0.0.1 cpu=0.5,memory=0.2 1667446798450' +``` + + + + +The `/influxdb/write` supports query params including: + +* `db`: Specifies the database to write to. The default value is `public`. +* `precision`: Defines the precision of the timestamp provided in the request body. Accepted values are `ns` (nanoseconds), `us` (microseconds), `ms` (milliseconds), and `s` (seconds). The data type of timestamps written by this API is `TimestampNanosecond`, so the default precision is `ns` (nanoseconds). If you use timestamps with other precisions in the request body, you need to specify the precision using this parameter. This parameter ensures that timestamp values are accurately interpreted and stored with nanosecond precision. + +You can also omit the timestamp when sending requests. GreptimeDB will use the current system time (in UTC) of the host machine as the timestamp. For example: + + + + + +```shell +curl -i -XPOST "http://localhost:4000/v1/influxdb/api/v2/write?db=public" \ + -H "authorization: token {{greptime_user:greptimedb_password}}" \ + --data-binary \ + 'monitor,host=127.0.0.1 cpu=0.1,memory=0.4 + monitor,host=127.0.0.2 cpu=0.2,memory=0.3 + monitor,host=127.0.0.1 cpu=0.5,memory=0.2' +``` + + + + +```shell +curl -i -XPOST "http://localhost:4000/v1/influxdb/write?db=public&u={{greptime_user}}&p={{greptimedb_password}}" \ +--data-binary \ +'monitor,host=127.0.0.1 cpu=0.1,memory=0.4 + monitor,host=127.0.0.2 cpu=0.2,memory=0.3 + monitor,host=127.0.0.1 cpu=0.5,memory=0.2' +``` + + + + +#### Authentication + +GreptimeDB is compatible with InfluxDB's line protocol authentication format, both V1 and V2. +If you have [configured authentication](/user-guide/deployments-administration/authentication/overview.md) in GreptimeDB, you need to provide the username and password in the HTTP request. + + + + + +InfluxDB's [V2 protocol](https://docs.influxdata.com/influxdb/v1.8/tools/api/?t=Auth+Enabled#apiv2query-http-endpoint) uses a format much like HTTP's standard basic authentication scheme. + +```shell +curl 'http://localhost:4000/v1/influxdb/api/v2/write?db=public' \ + -H 'authorization: token {{username:password}}' \ + -d 'monitor,host=127.0.0.1 cpu=0.1,memory=0.4' +``` + + + + + +For the authentication format of InfluxDB's [V1 protocol](https://docs.influxdata.com/influxdb/v1.8/tools/api/?t=Auth+Enabled#query-string-parameters-1). Add `u` for user and `p` for password to the HTTP query string as shown below: + +```shell +curl 'http://localhost:4000/v1/influxdb/write?db=public&u=&p=' \ + -d 'monitor,host=127.0.0.1 cpu=0.1,memory=0.4' +``` + + + + +### Telegraf + +GreptimeDB's support for the [InfluxDB line protocol](../for-iot/influxdb-line-protocol.md) ensures its compatibility with Telegraf. +To configure Telegraf, simply add GreptimeDB URL into Telegraf configurations: + + + + + +```toml +[[outputs.influxdb_v2]] + urls = ["http://:4000/v1/influxdb"] + token = ":" + bucket = "" + ## Leave empty + organization = "" +``` + + + + + +```toml +[[outputs.influxdb]] + urls = ["http://:4000/v1/influxdb"] + database = "" + username = "" + password = "" +``` + + + + + +## Data model + +While you may already be familiar with [InfluxDB key concepts](https://docs.influxdata.com/influxdb/v2/reference/key-concepts/), the [data model](/user-guide/concepts/data-model.md) of GreptimeDB is something new to explore. +Here are the similarities and differences between the data models of GreptimeDB and InfluxDB: + +- Both solutions are [schemaless](/user-guide/ingest-data/overview.md#automatic-schema-generation), eliminating the need to define a schema before writing data. +- The GreptimeDB table is automatically created with the [`merge_mode` option](/reference/sql/create.md#create-a-table-with-merge-mode) set to `last_non_null`. +That means the table merges rows with the same tags and timestamp by keeping the latest value of each field, which is the same behavior as InfluxDB. +- In InfluxDB, a point represents a single data record with a measurement, tag set, field set, and a timestamp. +In GreptimeDB, it is represented as a row of data in the time-series table, +where the table name aligns with the measurement, +and the columns are divided into three types: Tag, Field, and Timestamp. +- GreptimeDB uses `TimestampNanosecond` as the data type for timestamp data from the [InfluxDB line protocol API](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md). +- GreptimeDB uses `Float64` as the data type for numeric data from the InfluxDB line protocol API. + +Consider the following [sample data](https://docs.influxdata.com/influxdb/v2/reference/key-concepts/data-elements/#sample-data) borrowed from InfluxDB docs as an example: + +|_time|_measurement|location|scientist|_field|_value| +|---|---|---|---|---|---| +|2019-08-18T00:00:00Z|census|klamath|anderson|bees|23| +|2019-08-18T00:00:00Z|census|portland|mullen|ants|30| +|2019-08-18T00:06:00Z|census|klamath|anderson|bees|28| +|2019-08-18T00:06:00Z|census|portland|mullen|ants|32| + +The data mentioned above is formatted as follows in the InfluxDB line protocol: + + +```shell +census,location=klamath,scientist=anderson bees=23 1566086400000000000 +census,location=portland,scientist=mullen ants=30 1566086400000000000 +census,location=klamath,scientist=anderson bees=28 1566086760000000000 +census,location=portland,scientist=mullen ants=32 1566086760000000000 +``` + +In the GreptimeDB data model, the data is represented as follows in the `census` table: + +```sql ++---------------------+----------+-----------+------+------+ +| greptime_timestamp | location | scientist | bees | ants | ++---------------------+----------+-----------+------+------+ +| 2019-08-18 00:00:00 | klamath | anderson | 23 | NULL | +| 2019-08-18 00:06:00 | klamath | anderson | 28 | NULL | +| 2019-08-18 00:00:00 | portland | mullen | NULL | 30 | +| 2019-08-18 00:06:00 | portland | mullen | NULL | 32 | ++---------------------+----------+-----------+------+------+ +``` + +The schema of the `census` table is as follows: + +```sql ++--------------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+----------------------+------+------+---------+---------------+ +| location | String | PRI | YES | | TAG | +| scientist | String | PRI | YES | | TAG | +| bees | Float64 | | YES | | FIELD | +| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| ants | Float64 | | YES | | FIELD | ++--------------------+----------------------+------+------+---------+---------------+ +``` + +## Reference + +- [InfluxDB Line protocol](https://docs.influxdata.com/influxdb/v2.7/reference/syntax/line-protocol/) + diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/kafka.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/kafka.md new file mode 100644 index 0000000000..192e088ab2 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/kafka.md @@ -0,0 +1,8 @@ +--- +keywords: [Kafka, Data Ingestion] +description: Write data from Kafka to GreptimeDB. +--- + +# Kafka + +Please refer to the [Kafka documentation](/user-guide/ingest-data/for-observability/kafka.md) for instructions on how to ingest data from Kafka into GreptimeDB. diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/opentsdb.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/opentsdb.md new file mode 100644 index 0000000000..e7efde6cf9 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/opentsdb.md @@ -0,0 +1,65 @@ +--- +keywords: [OpenTSDB, HTTP API, metrics, data ingestion, insert data, multiple metric points] +description: Instructions on ingesting OpenTSDB metrics into GreptimeDB via HTTP API, including examples of inserting single and multiple metric points. +--- + +# OpenTSDB + +GreptimeDB supports ingesting OpenTSDB via HTTP API. + +GreptimeDB also supports inserting OpenTSDB metrics via HTTP endpoints. We use the request and +response format described in OpenTSDB's `/api/put`. + +The HTTP endpoint in GreptimeDB for handling metrics is `/opentsdb/api/put` + +> Note: remember to prefix the path with GreptimeDB's http API version, `v1`. + +Starting GreptimeDB, the HTTP server is listening on port `4000` by default. + +Use curl to insert one metric point: + +```shell +curl -X POST http://127.0.0.1:4000/v1/opentsdb/api/put \ + -H 'Authorization: Basic {{authentication}}' \ + -d ' + { + "metric": "sys.cpu.nice", + "timestamp": 1667898896, + "value": 18, + "tags": { + "host": "web01", + "dc": "hz" + } + } + ' +``` + +Or insert multiple metric points: + +```shell +curl -X POST http://127.0.0.1:4000/v1/opentsdb/api/put \ + -H 'Authorization: Basic {{authentication}}' \ + -d ' + [ + { + "metric": "sys.cpu.nice", + "timestamp": 1667898896, + "value": 1, + "tags": { + "host": "web02", + "dc": "hz" + } + }, + { + "metric": "sys.cpu.nice", + "timestamp": 1667898897, + "value": 9, + "tags": { + "host": "web03", + "dc": "sh" + } + } + ] + ' +``` + diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/overview.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/overview.md new file mode 100644 index 0000000000..d249a6a42f --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/overview.md @@ -0,0 +1,19 @@ +--- +keywords: [data ingestion, IoT, SQL INSERT, gRPC SDK, InfluxDB Line Protocol, EMQX, OpenTSDB] +description: Overview of data ingestion methods in GreptimeDB for IoT, including SQL INSERT, gRPC SDK, InfluxDB Line Protocol, EMQX, and OpenTSDB. +--- + +import DocCardList from '@theme/DocCardList'; + +# Ingest Data for IoT + +The data ingestion is a critical part of the IoT data pipeline. +It is the process of collecting data from various sources, such as sensors, devices, and applications, and storing it in a central location for further processing and analysis. +The data ingestion is essential for ensuring that the data is accurate, reliable, and secure. + +GreptimeDB can handle large volumes of data, process it in real-time, and store it efficiently for future analysis. +It also supports various data formats, protocols, and interfaces, +making it easy to integrate with different IoT devices and systems. + + + diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/sql.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/sql.md new file mode 100644 index 0000000000..a7371e0533 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-iot/sql.md @@ -0,0 +1,121 @@ +--- +keywords: [pg, pgsql, SQL, MySQL, PostgreSQL, create table, insert data, timestamp, time zone, data ingestion] +description: Guide on executing SQL statements to create tables and insert data into GreptimeDB, with examples using the `monitor` table. +--- + +# SQL + +You can execute SQL statements using [MySQL](/user-guide/protocols/mysql.md) or [PostgreSQL](/user-guide/protocols/postgresql.md) clients, +and access GreptimeDB using the MySQL or PostgreSQL protocol with any programming language of your preference, such as Java JDBC. +We will use the `monitor` table as an example to show how to write data. + +## Create a table + +Before inserting data, you need to create a table. For example, create a table named `monitor`: + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64 DEFAULT 0, + memory FLOAT64, + PRIMARY KEY(host)); +``` + +The above statement will create a table with the following schema: + +```sql ++--------+----------------------+------+------+---------------------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------+----------------------+------+------+---------------------+---------------+ +| host | String | PRI | YES | | TAG | +| ts | TimestampMillisecond | PRI | NO | current_timestamp() | TIMESTAMP | +| cpu | Float64 | | YES | 0 | FIELD | +| memory | Float64 | | YES | | FIELD | ++--------+----------------------+------+------+---------------------+---------------+ +4 rows in set (0.01 sec) +``` + +For more information about the `CREATE TABLE` statement, +please refer to [table management](/user-guide/deployments-administration/manage-data/basic-table-operations.md#create-a-table). + +## Insert data + +Let's insert some testing data to the `monitor` table. You can use the `INSERT INTO` SQL statements: + +```sql +INSERT INTO monitor +VALUES + ("127.0.0.1", 1702433141000, 0.5, 0.2), + ("127.0.0.2", 1702433141000, 0.3, 0.1), + ("127.0.0.1", 1702433146000, 0.3, 0.2), + ("127.0.0.2", 1702433146000, 0.2, 0.4), + ("127.0.0.1", 1702433151000, 0.4, 0.3), + ("127.0.0.2", 1702433151000, 0.2, 0.4); +``` + +```sql +Query OK, 6 rows affected (0.01 sec) +``` + +You can also insert data by specifying the column names: + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +VALUES + ("127.0.0.1", 1702433141000, 0.5, 0.2), + ("127.0.0.2", 1702433141000, 0.3, 0.1), + ("127.0.0.1", 1702433146000, 0.3, 0.2), + ("127.0.0.2", 1702433146000, 0.2, 0.4), + ("127.0.0.1", 1702433151000, 0.4, 0.3), + ("127.0.0.2", 1702433151000, 0.2, 0.4); +``` + +Through the above statement, we have inserted six rows into the `monitor` table. + +For more information about the `INSERT` statement, please refer to [`INSERT`](/reference/sql/insert.md). + +## Time zone + +The time zone specified in the SQL client will affect the timestamp with a string format that does not have time zone information. +The timestamp value will automatically have the client's time zone information added. + +For example, the following SQL set the time zone to `+8:00`: + +```sql +SET time_zone = '+8:00'; +``` + +Then insert values into the `monitor` table: + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +VALUES + ("127.0.0.1", "2024-01-01 00:00:00", 0.4, 0.1), + ("127.0.0.2", "2024-01-01 00:00:00+08:00", 0.5, 0.1); +``` + +The first timestamp value `2024-01-01 00:00:00` does not have time zone information, so it will automatically have the client's time zone information added. +After inserting, it will be equivalent to the second value `2024-01-01 00:00:00+08:00`. + +The result in the `+8:00` time zone client is as follows: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-01-01 00:00:00 | 0.4 | 0.1 | +| 127.0.0.2 | 2024-01-01 00:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +``` + +The result in the `UTC` time zone client is as follows: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2023-12-31 16:00:00 | 0.4 | 0.1 | +| 127.0.0.2 | 2023-12-31 16:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +``` diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/alloy.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/alloy.md new file mode 100644 index 0000000000..4e3cd16ec0 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/alloy.md @@ -0,0 +1,119 @@ +--- +keywords: [Grafana Alloy, Prometheus Remote Write, OpenTelemetry, data pipeline] +description: Instructions on integrating GreptimeDB with Grafana Alloy for Prometheus Remote Write and OpenTelemetry. +--- + +# Grafana Alloy + +[Grafana Alloy](https://grafana.com/docs/alloy/latest/) is an observability data pipeline for OpenTelemetry (OTel), Prometheus, Pyroscope, Loki, and many other metrics, logs, traces, and profiling tools. +You can integrate GreptimeDB as a data sink for Alloy. + +## Prometheus Remote Write + +Configure GreptimeDB as remote write target: + +```hcl +prometheus.remote_write "greptimedb" { + endpoint { + url = "${GREPTIME_SCHEME:=http}://${GREPTIME_HOST:=greptimedb}:${GREPTIME_PORT:=4000}/v1/prometheus/write?db=${GREPTIME_DB:=public}" + + basic_auth { + username = "${GREPTIME_USERNAME}" + password = "${GREPTIME_PASSWORD}" + } + } +} +``` + +- `GREPTIME_HOST`: GreptimeDB host address, e.g., `localhost`. +- `GREPTIME_DB`: GreptimeDB database name, default is `public`. +- `GREPTIME_USERNAME` and `GREPTIME_PASSWORD`: The [authentication credentials](/user-guide/deployments-administration/authentication/static.md) for GreptimeDB. + +For details on the data model transformation from Prometheus to GreptimeDB, refer to the [Data Model](/user-guide/ingest-data/for-observability/prometheus.md#data-model) section in the Prometheus Remote Write guide. + +## OpenTelemetry + +GreptimeDB can also be configured as OpenTelemetry collector. + +### Metrics + +```hcl +otelcol.exporter.otlphttp "greptimedb" { + client { + endpoint = "${GREPTIME_SCHEME:=http}://${GREPTIME_HOST:=greptimedb}:${GREPTIME_PORT:=4000}/v1/otlp/" + headers = { + "X-Greptime-DB-Name" = "${GREPTIME_DB:=public}", + } + auth = otelcol.auth.basic.credentials.handler + } +} + +otelcol.auth.basic "credentials" { + username = "${GREPTIME_USERNAME}" + password = "${GREPTIME_PASSWORD}" +} +``` + +- `GREPTIME_HOST`: GreptimeDB host address, e.g., `localhost`. +- `GREPTIME_DB`: GreptimeDB database name, default is `public`. +- `GREPTIME_USERNAME` and `GREPTIME_PASSWORD`: The [authentication credentials](/user-guide/deployments-administration/authentication/static.md) for GreptimeDB. + +For details on the metrics data model transformation from OpenTelemetry to GreptimeDB, refer to the [Data Model](/user-guide/ingest-data/for-observability/opentelemetry.md#data-model) section in the OpenTelemetry guide. + +### Logs + +The following example setting up a logging pipeline using Loki and OpenTelemetry Collector (otelcol) to forward logs to a GreptimeDB: + +```hcl +loki.source.file "greptime" { + targets = [ + {__path__ = "/tmp/foo.txt"}, + ] + forward_to = [otelcol.receiver.loki.greptime.receiver] +} + +otelcol.receiver.loki "greptime" { + output { + logs = [otelcol.exporter.otlphttp.greptimedb_logs.input] + } +} + +otelcol.auth.basic "credentials" { + username = "${GREPTIME_USERNAME}" + password = "${GREPTIME_PASSWORD}" +} + +otelcol.exporter.otlphttp "greptimedb_logs" { + client { + endpoint = "${GREPTIME_SCHEME:=http}://${GREPTIME_HOST:=greptimedb}:${GREPTIME_PORT:=4000}/v1/otlp/" + headers = { + "X-Greptime-DB-Name" = "${GREPTIME_DB:=public}", + "X-Greptime-Log-Table-Name" = "demo_logs", + "X-Greptime-Log-Extract-Keys" = "filename,log.file.name,loki.attribute.labels", + } + auth = otelcol.auth.basic.credentials.handler + } +} +``` + +- Loki Source Configuration + - The `loki.source.file "greptime"` block defines a source for Loki to read logs from a file located at `/tmp/foo.txt` + - The `forward_to` array indicates that the logs read from this file should be forwarded to the `otelcol.receiver.loki.greptime.receiver` +- OpenTelemetry Collector Receiver Configuration: + - The `otelcol.receiver.loki "greptime"` block sets up a receiver within the OpenTelemetry Collector to receive logs from Loki. + - The `output` section specifies that the received logs should be forwarded to the `otelcol.exporter.otlphttp.greptimedb_logs.input`. +- OpenTelemetry Collector Exporter Configuration: + - The `otelcol.exporter.otlphttp "greptimedb_logs"` block configures an HTTP exporter to send logs to GreptimeDB. + - `GREPTIME_HOST`: GreptimeDB host address, e.g., `localhost`. + - `GREPTIME_DB`: GreptimeDB database name, default is `public`. + - `GREPTIME_USERNAME` and `GREPTIME_PASSWORD`: The [authentication credentials](/user-guide/deployments-administration/authentication/static.md) for GreptimeDB. + - `LOG_TABLE_NAME`: The name of the table to store logs, default table name is `opentelemetry_logs`. + - `EXTRACT_KEYS`: The keys to extract from the attributes, separated by commas (`,`), e.g., `filename,log.file.name,loki.attribute.labels`, see [HTTP API documentation](opentelemetry.md#otlphttp-api-1) for details. + +For details on the log data model transformation from OpenTelemetry to GreptimeDB, refer to the [Data Model](/user-guide/ingest-data/for-observability/opentelemetry.md#data-model-1) section in the OpenTelemetry guide. + +:::tip NOTE +The example codes above may be outdated according to OpenTelemetry. We recommend that you refer to the official OpenTelemetry documentation And Grafana Alloy for the most up-to-date information. +::: + +For more information on the example code, please refer to the official documentation for your preferred programming language. diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/elasticsearch.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/elasticsearch.md new file mode 100644 index 0000000000..f3ce6adeb9 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/elasticsearch.md @@ -0,0 +1,188 @@ +--- +keywords: [Elasticsearch, log storage, API, configuration, data model, telegraf, logstash, filebeat] +description: Use Elasticsearch protocol to ingest log data. +--- + +# Elasticsearch + +## Overview + +GreptimeDB supports data ingestion through Elasticsearch's [`_bulk` API](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html). We map Elasticsearch's Index concept to GreptimeDB's Table, and users can specify the database name using the `db` URL parameter. **Unlike native Elasticsearch, this API only supports data insertion, not modification or deletion**. At the implementation level, both `index` and `create` commands in native Elasticsearch `_bulk` API requests are treated as **creation operations** by GreptimeDB. Additionally, GreptimeDB only parses the `_index` field from native `_bulk` API command requests while ignoring other fields. + +## HTTP API + +In most log collectors(such as Logstash and Filebeat mentioned below), you only need to configure the HTTP endpoint like `http://${db_host}:${db_http_port}/v1/elasticsearch`, for example `http://localhost:4000/v1/elasticsearch`. + +GreptimeDB supports data ingestion through Elasticsearch protocol by implementing the following two HTTP endpoints: + +- **`/v1/elasticsearch/_bulk`**: Users can use the POST method to write data in NDJSON format to GreptimeDB. + + For example, the following request will create a table named `test` and insert two records: + + ```json + POST /v1/elasticsearch/_bulk + + {"create": {"_index": "test", "_id": "1"}} + {"name": "John", "age": 30} + {"create": {"_index": "test", "_id": "2"}} + {"name": "Jane", "age": 25} + ``` + +- **`/v1/elasticsearch/${index}/_bulk`**: Users can use the POST method to write data in NDJSON format to the `${index}` table in GreptimeDB. If the POST request also contains an `_index` field, the `${index}` in the URL will be ignored. + + For example, the following request will create tables named `test` and `another_index`, and insert corresponding data: + + ```json + POST /v1/elasticsearch/test/_bulk + + {"create": {"_id": "1"}} + {"name": "John", "age": 30} + {"create": {"_index": "another_index", "_id": "2"}} + {"name": "Jane", "age": 25} + ``` + +### HTTP Headers + +- `x-greptime-db-name`: Specifies the database name. Defaults to `public` if not specified. +- `x-greptime-pipeline-name`: Specifies the pipeline name. Defaults to GreptimeDB's internal pipeline `greptime_identity` if not specified. +- `x-greptime-pipeline-version`: Specifies the pipeline version. Defaults to the latest version of the corresponding pipeline if not specified. + +For more details about Pipeline, please refer to the [Manage Pipelines](/user-guide/logs/manage-pipelines.md) documentation. + +### URL Parameters + +You can use the following HTTP URL parameters: + +- `db`: Specifies the database name. Defaults to `public` if not specified. +- `pipeline_name`: Specifies the pipeline name. Defaults to GreptimeDB's internal pipeline `greptime_identity` if not specified. +- `version`: Specifies the pipeline version. Defaults to the latest version of the corresponding pipeline if not specified. +- `msg_field`: Specifies the JSON field name containing the original log data. For example, in Logstash and Filebeat, this field is typically `message`. If specified, GreptimeDB will attempt to parse the data in this field as JSON format. If parsing fails, the field will be treated as a string. This configuration option currently only takes effect in URL parameters. + +### Authentication Header + +For detailed information about the authentication header, please refer to the [Authorization](/user-guide/protocols/http.md#authentication) documentation. + +## Usage + +### Use HTTP API to ingest data + +You can create a `request.json` file with the following content: + +```json +{"create": {"_index": "es_test", "_id": "1"}} +{"name": "John", "age": 30} +{"create": {"_index": "es_test", "_id": "2"}} +{"name": "Jane", "age": 25} +``` + +Then use the `curl` command to send this file as a request body to GreptimeDB: + +```bash +curl -XPOST http://localhost:4000/v1/elasticsearch/_bulk \ + -H "Authorization: Basic {{authentication}}" \ + -H "Content-Type: application/json" -d @request.json +``` + +We can use a `mysql` client to connect to GreptimeDB and execute the following SQL to view the inserted data: + +```sql +SELECT * FROM es_test; +``` + +We will see the following results: + +``` +mysql> SELECT * FROM es_test; ++------+------+----------------------------+ +| age | name | greptime_timestamp | ++------+------+----------------------------+ +| 30 | John | 2025-01-15 08:26:06.516665 | +| 25 | Jane | 2025-01-15 08:26:06.521510 | ++------+------+----------------------------+ +2 rows in set (0.13 sec) +``` + +### Logstash + +If you are using [Logstash](https://www.elastic.co/logstash) to collect logs, you can use the following configuration to write data to GreptimeDB: + +``` +output { + elasticsearch { + hosts => ["http://localhost:4000/v1/elasticsearch"] + index => "my_index" + parameters => { + "pipeline_name" => "my_pipeline" + "msg_field" => "message" + } + } +} +``` + +Please pay attention to the following GreptimeDB-related configurations: + +- `hosts`: Specifies the HTTP address of GreptimeDB's Elasticsearch protocol, which is `http://${db_host}:${db_http_port}/v1/elasticsearch`. + +- `index`: Specifies the table name that will be written to. + +- `parameters`: Specifies the URL parameters for writing, where the example above specifies two parameters: `pipeline_name` and `msg_field`. + +### Filebeat + +If you are using [Filebeat](https://github.com/elastic/beats/tree/main/filebeat) to collect logs, you can use the following configuration to write data to GreptimeDB: + +``` +output.elasticsearch: + hosts: ["http://localhost:4000/v1/elasticsearch"] + index: "my_index" + parameters: + pipeline_name: my_pipeline + msg_field: message +``` + +Please pay attention to the following GreptimeDB-related configurations: + +- `hosts`: Specifies the HTTP address of GreptimeDB's Elasticsearch protocol, which is `http://${db_host}:${db_http_port}/v1/elasticsearch`. + +- `index`: Specifies the table name that will be written to. + +- `parameters`: Specifies the URL parameters for writing, where the example above specifies two parameters: `pipeline_name` and `msg_field`. + +### Telegraf + +If you are using [Telegraf](https://github.com/influxdata/telegraf) to collect logs, you can use its Elasticsearch plugin to write data to GreptimeDB, as shown below: + +```toml +[[outputs.elasticsearch]] + urls = [ "http://localhost:4000/v1/elasticsearch" ] + index_name = "test_table" + health_check_interval = "0s" + enable_sniffer = false + flush_interval = "1s" + manage_template = false + template_name = "telegraf" + overwrite_template = false + namepass = ["tail"] + + [outputs.elasticsearch.headers] + "X-GREPTIME-DB-NAME" = "public" + "X-GREPTIME-PIPELINE-NAME" = "greptime_identity" + +[[inputs.tail]] + files = ["/tmp/test.log"] + from_beginning = true + data_format = "value" + data_type = "string" + character_encoding = "utf-8" + interval = "1s" + pipe = false + watch_method = "inotify" +``` + +Please pay attention to the following GreptimeDB-related configurations: + +- `urls`: Specifies the HTTP address of GreptimeDB's Elasticsearch protocol, which is `http://${db_host}:${db_http_port}/v1/elasticsearch`. + +- `index_name`: Specifies the table name that will be written to. + +- `outputs.elasticsearch.header`: Specifies the HTTP Header for writing, where the example above specifies two parameters: `X-GREPTIME-DB-NAME` and `X-GREPTIME-PIPELINE-NAME`. diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/fluent-bit.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/fluent-bit.md new file mode 100644 index 0000000000..571ae5beb3 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/fluent-bit.md @@ -0,0 +1,128 @@ +--- +keywords: [Fluent bit, Prometheus Remote Write, OpenTelemetry, data pipeline] +description: Instructions on integrating GreptimeDB with Fluent bit for Prometheus Remote Write and OpenTelemetry. +--- + +# Fluent Bit + +[Fluent Bit](http://fluentbit.io/) is a fast and lightweight telemetry agent for logs, metrics, and traces for Linux, macOS, Windows, and BSD family operating systems. Fluent Bit has been made with a strong focus on performance to allow the collection and processing of telemetry data from different sources without complexity. + +You can forward Fluent Bit data to GreptimeDB. This document describes how to configure Fluent Bit to send logs, metrics, and traces to GreptimeDB. + +## Http + +Using Fluent Bit's [HTTP Output Plugin](https://docs.fluentbit.io/manual/pipeline/outputs/http), you can send logs to GreptimeDB. +Before configuring Fluent Bit, ensure that you understand the [log ingestion flow](/user-guide/logs/overview.md) and [how to use pipelines](/user-guide/logs/use-custom-pipelines.md). + +```conf +[OUTPUT] + Name http + Match * + Host greptimedb + Port 4000 + Uri /v1/ingest?db=public&table=your_table&pipeline_name=greptime_identity + Format json + Json_date_key scrape_timestamp + Json_date_format iso8601 + compress gzip + http_User + http_Passwd +``` + +- `host`: GreptimeDB host address, e.g., `localhost`. +- `port`: GreptimeDB port, default is `4000`. +- `uri`: The endpoint to send logs to. +- `format`: The format of the logs, needs to be `json`. +- `json_date_key`: The key in the JSON object that contains the timestamp. +- `json_date_format`: The format of the timestamp. +- `compress`: The compression method to use, e.g., `gzip`. +- `header`: The header to send with the request, e.g., `Authorization` for authentication. +- `http_user` and `http_passwd`: The [authentication credentials](/user-guide/deployments-administration/authentication/static.md) for GreptimeDB. + +In params Uri, +- `db` is the database name you want to write logs to. +- `table` is the table name you want to write logs to. +- `pipeline_name` is the pipeline name you want to use for processing logs. + +## OpenTelemetry + +GreptimeDB can also be configured as OpenTelemetry collector. Using Fluent Bit's [OpenTelemetry Output Plugin](https://docs.fluentbit.io/manual/pipeline/outputs/opentelemetry), you can send metrics, logs, and traces to GreptimeDB. + +``` +[OUTPUT] + Name opentelemetry + Match * + Host 127.0.0.1 + Port 4000 + Metrics_uri /v1/otlp/v1/metrics + Logs_uri /v1/otlp/v1/logs + Traces_uri /v1/otlp/v1/traces + Log_response_payload True + Tls Off + Tls.verify Off + logs_body_key message + http_User + http_Passwd +``` + +- `Metrics_uri`, `Logs_uri`, and `Traces_uri`: The endpoint to send metrics, logs, and traces to. +- `http_user` and `http_passwd`: The [authentication credentials](/user-guide/deployments-administration/authentication/static.md) for GreptimeDB. + +We recommend not writing metrics, logs, and traces to a single output simultaneously, as each has specific header options for specifying parameters. We suggest creating a separate OpenTelemetry output for metrics, logs, and traces. for example: + +``` +# Only for metrics +[OUTPUT] + Name opentelemetry + Alias opentelemetry_metrics + Match * + Host 127.0.0.1 + Port 4000 + Metrics_uri /v1/otlp/v1/metrics + Log_response_payload True + Tls Off + Tls.verify Off + +# Only for logs +[OUTPUT] + Name opentelemetry + Alias opentelemetry_logs + Match * + Host 127.0.0.1 + Port 4000 + Logs_uri /v1/otlp/v1/logs + Log_response_payload True + Tls Off + Tls.verify Off + Header X-Greptime-Log-Table-Name "" + Header X-Greptime-Log-Pipeline-Name "" + Header X-Greptime-DB-Name "" +``` + + +In this example, the [OpenTelemetry OTLP/HTTP API](/user-guide/ingest-data/for-observability/opentelemetry.md#opentelemetry-collectors) interface is used. For more information, and extra options, refer to the [OpenTelemetry](/user-guide/ingest-data/for-observability/opentelemetry.md) guide. + +## Prometheus Remote Write + +Configure GreptimeDB as remote write target: + +``` +[OUTPUT] + Name prometheus_remote_write + Match internal_metrics + Host 127.0.0.1 + Port 4000 + Uri /v1/prometheus/write?db= + Tls Off + http_user + http_passwd +``` + +- `Uri`: The endpoint to send metrics to. +- `http_user` and `http_passwd`: The [authentication credentials](/user-guide/deployments-administration/authentication/static.md) for GreptimeDB. + +In params Uri, + +- `db` is the database name you want to write metrics to. + +For details on the data model transformation from Prometheus to GreptimeDB, refer to the [Data Model](/user-guide/ingest-data/for-observability/prometheus.md#data-model) section in the Prometheus Remote Write guide. \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/influxdb-line-protocol.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/influxdb-line-protocol.md new file mode 100644 index 0000000000..74431fe76b --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/influxdb-line-protocol.md @@ -0,0 +1,9 @@ +--- +keywords: [InfluxDB Line Protocol] +description: Write data to GreptimeDB using the InfluxDB Line Protocol +--- + +# InfluxDB Line Protocol + +Please refer to the [InfluxDB Line Protocol documentation](../for-iot/influxdb-line-protocol.md) for instructions on how to write data to GreptimeDB using the InfluxDB Line Protocol. + diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/kafka.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/kafka.md new file mode 100644 index 0000000000..8238d7e882 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/kafka.md @@ -0,0 +1,172 @@ +--- +keywords: [Kafka, data ingestion, observability, metrics, logs, JSON logs, text logs, Vector, InfluxDB line protocol] +description: Learn how to ingest observability data from Kafka into GreptimeDB using Vector. This guide covers metrics and logs ingestion, including JSON and text log formats, with detailed configuration examples. +--- + +# Kafka + +If you are using Kafka or Kafka-compatible message queue for observability data +transporting, it's possible to ingest data into GreptimeDB directly. + +Here we are using Vector as the tool to transport data from Kafka to GreptimeDB. + +## Metrics + +When ingesting metrics from Kafka into GreptimeDB, messages should be formatted in InfluxDB line protocol. For example: + +```txt +census,location=klamath,scientist=anderson bees=23 1566086400000000000 +``` + +Then configure Vector to use the `influxdb` decoding codec to process these messages. + +```toml +[sources.metrics_mq] +# Specifies that the source type is Kafka +type = "kafka" +# The consumer group ID for Kafka +group_id = "vector0" +# The list of Kafka topics to consume messages from +topics = ["test_metric_topic"] +# The address of the Kafka broker to connect to +bootstrap_servers = "kafka:9092" +# The `influxdb` means the messages are expected to be in InfluxDB line protocol format. +decoding.codec = "influxdb" + +[sinks.metrics_in] +inputs = ["metrics_mq"] +# Specifies that the sink type is `greptimedb_metrics` +type = "greptimedb_metrics" +# The endpoint of the GreptimeDB server. +# Replace with the actual hostname or IP address. +endpoint = ":4001" +dbname = "" +username = "" +password = "" +tls = {} +``` + +For details on how InfluxDB line protocol metrics are mapped to GreptimeDB data, please refer to the [Data Model](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md#data-model) section in the InfluxDB line protocol documentation. + + +## Logs + +Developers commonly work with two types of logs: JSON logs and plain text logs. +Consider the following examples sent from Kafka. + +A plain text log: + +```txt +127.0.0.1 - - [25/May/2024:20:16:37 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" +``` + +Or a JSON log: + +```json +{ + "timestamp": "2024-12-23T10:00:00Z", + "level": "INFO", + "message": "Service started" +} +``` + +GreptimeDB transforms these logs into structured data with multiple columns and automatically creates the necessary tables. +A pipeline processes the logs into structured data before ingestion into GreptimeDB. Different log formats require different [Pipelines](/user-guide/logs/quick-start.md#write-logs-by-pipeline) for parsing. See the following sections for details. + +### Logs with JSON format + +For logs in JSON format (e.g., `{"timestamp": "2024-12-23T10:00:00Z", "level": "INFO", "message": "Service started"}`), +you can use the built-in [`greptime_identity`](/user-guide/logs/manage-pipelines.md#greptime_identity) pipeline for direct ingestion. +This pipeline creates columns automatically based on the fields in your JSON log message. + +Simply configure Vector's `transforms` settings to parse the JSON message and use the `greptime_identity` pipeline as shown in the following example: + +```toml +[sources.logs_in] +type = "kafka" +# The consumer group ID for Kafka +group_id = "vector0" +# The list of Kafka topics to consume messages from +topics = ["test_log_topic"] +# The address of the Kafka broker to connect to +bootstrap_servers = "kafka:9092" + +# transform the log to JSON format +[transforms.logs_json] +type = "remap" +inputs = ["logs_in"] +source = ''' +. = parse_json!(.message) +''' + +[sinks.logs_out] +# Specifies that this sink will receive data from the `logs_json` source +inputs = ["logs_json"] +# Specifies that the sink type is `greptimedb_logs` +type = "greptimedb_logs" +# The endpoint of the GreptimeDB server +endpoint = "http://:4000" +compression = "gzip" +# Replace , , and with the actual values +dbname = "" +username = "" +password = "" +# The table name in GreptimeDB, if it doesn't exist, it will be created automatically +table = "demo_logs" +# Use the built-in `greptime_identity` pipeline +pipeline_name = "greptime_identity" +``` + +### Logs with text format + +For logs in text format, such as the access log format below, you'll need to create a custom pipeline to parse them: + +``` +127.0.0.1 - - [25/May/2024:20:16:37 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" +``` + +#### Create a pipeline + +To create a custom pipeline, +please refer to the [using custom pipelines](/user-guide/logs/use-custom-pipelines.md) +documentation for detailed instructions. + +#### Ingest data + +After creating the pipeline, configure it to the `pipeline_name` field in the Vector configuration file. + +```toml +# sample.toml +[sources.log_mq] +# Specifies that the source type is Kafka +type = "kafka" +# The consumer group ID for Kafka +group_id = "vector0" +# The list of Kafka topics to consume messages from +topics = ["test_log_topic"] +# The address of the Kafka broker to connect to +bootstrap_servers = "kafka:9092" + +[sinks.sink_greptime_logs] +# Specifies that the sink type is `greptimedb_logs` +type = "greptimedb_logs" +# Specifies that this sink will receive data from the `log_mq` source +inputs = [ "log_mq" ] +# Use `gzip` compression to save bandwidth +compression = "gzip" +# The endpoint of the GreptimeDB server +# Replace with the actual hostname or IP address +endpoint = "http://:4000" +dbname = "" +username = "" +password = "" +# The table name in GreptimeDB, if it doesn't exist, it will be created automatically +table = "demo_logs" +# The custom pipeline name that you created +pipeline_name = "your_custom_pipeline" +``` + +## Demo + +For a runnable demo of data transformation and ingestion, please refer to the [Kafka Ingestion Demo](https://github.com/GreptimeTeam/demo-scene/tree/main/kafka-ingestion). + diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/loki.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/loki.md new file mode 100644 index 0000000000..fb61b4bdb2 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/loki.md @@ -0,0 +1,267 @@ +--- +keywords: [Loki, log storage, API, configuration, data model] +description: Guide to integrating Loki with GreptimeDB for log storage, including API usage, example configurations, and data model mapping. +--- + +# Loki + +## Usage + +### API + +To send logs to GreptimeDB through the raw HTTP API, use the following information: + +* **URL**: `http{s}:///v1/loki/api/v1/push` +* **Headers**: + * `X-Greptime-DB-Name`: `` + * `Authorization`: `Basic` authentication, which is a Base64 encoded string of `:`. For more information, please refer to [Authentication](https://docs.greptime.com/user-guide/deployments-administration/authentication/static/) and [HTTP API](https://docs.greptime.com/user-guide/protocols/http#authentication). + * `X-Greptime-Log-Table-Name`: `` (optional) - The table name to store the logs. If not provided, the default table name is `loki_logs`. + +The request uses binary protobuf to encode the payload. The defined schema is the same as the [logproto.proto](https://github.com/grafana/loki/blob/main/pkg/logproto/logproto.proto). + +### Example Code + +[Grafana Alloy](https://grafana.com/docs/alloy/latest/) is a vendor-neutral distribution of the OpenTelemetry (OTel) Collector. Alloy uniquely combines the very best OSS observability signals in the community. + +It supplies a Loki exporter that can be used to send logs to GreptimeDB. Here is an example configuration: + +``` +loki.source.file "greptime" { + targets = [ + {__path__ = "/tmp/foo.txt"}, + ] + forward_to = [loki.write.greptime_loki.receiver] +} + +loki.write "greptime_loki" { + endpoint { + url = "${GREPTIME_SCHEME:=http}://${GREPTIME_HOST:=greptimedb}:${GREPTIME_PORT:=4000}/v1/loki/api/v1/push" + headers = { + "x-greptime-db-name" = "${GREPTIME_DB:=public}", + "x-greptime-log-table-name" = "${GREPTIME_LOG_TABLE_NAME:=loki_demo_logs}", + } + } + external_labels = { + "job" = "greptime", + "from" = "alloy", + } +} +``` + +This configuration reads logs from the file `/tmp/foo.txt` and sends them to GreptimeDB. The logs are stored in the table `loki_demo_logs` with the external labels `job` and `from`. + +For more information, please refer to the [Grafana Alloy loki.write documentation](https://grafana.com/docs/alloy/latest/reference/components/loki/loki.write/). + +You can run the following command to check the data in the table: + +```sql +SELECT * FROM loki_demo_logs; ++----------------------------+------------------------+--------------+-------+----------+ +| greptime_timestamp | line | filename | from | job | ++----------------------------+------------------------+--------------+-------+----------+ +| 2024-11-25 11:02:31.256251 | Greptime is very cool! | /tmp/foo.txt | alloy | greptime | ++----------------------------+------------------------+--------------+-------+----------+ +1 row in set (0.01 sec) +``` + +## Data Model + +The Loki logs data model is mapped to the GreptimeDB data model according to the following rules: + +**Default table schema without external labels:** + +```sql +DESC loki_demo_logs; ++--------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+---------------------+------+------+---------+---------------+ +| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| line | String | | YES | | FIELD | ++--------------------+---------------------+------+------+---------+---------------+ +5 rows in set (0.00 sec) +``` + +- `greptime_timestamp`: The timestamp of the log entry +- `line`: The log message content + +If the Loki Push request contains labels, they will be added as tags to the table schema (like `job` and `from` in the above example). + +**Important notes:** +- All labels are treated as tags with string type +- Do not attempt to pre-create the table using SQL to specify tag columns, as this will cause a type mismatch and write failure + +### Example Table Schema + +The following is an example of the table schema with external labels: + +```sql +DESC loki_demo_logs; ++--------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+---------------------+------+------+---------+---------------+ +| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| line | String | | YES | | FIELD | +| filename | String | PRI | YES | | TAG | +| from | String | PRI | YES | | TAG | +| job | String | PRI | YES | | TAG | ++--------------------+---------------------+------+------+---------+---------------+ +5 rows in set (0.00 sec) +``` + +```sql +SHOW CREATE TABLE loki_demo_logs\G +*************************** 1. row *************************** + Table: loki_demo_logs +Create Table: CREATE TABLE IF NOT EXISTS `loki_demo_logs` ( + `greptime_timestamp` TIMESTAMP(9) NOT NULL, + `line` STRING NULL, + `filename` STRING NULL, + `from` STRING NULL, + `job` STRING NULL, + TIME INDEX (`greptime_timestamp`), + PRIMARY KEY (`filename`, `from`, `job`) +) + +ENGINE=mito +WITH( + append_mode = 'true' +) +1 row in set (0.00 sec) +``` + +## Using Pipeline with Loki Push API + +:::warning Experimental Feature +This experimental feature may contain unexpected behavior and have its functionality change in the future. +::: + +Starting from version `v0.15`, GreptimeDB supports using pipelines to process Loki push requests. +You can simply set the HTTP header `x-greptime-pipeline-name` to the target pipeline name to enable pipeline processing. + +**Note:** When request data goes through the pipeline engine, GreptimeDB adds prefixes to the label and metadata column names: +- `loki_label_` before each label name +- `loki_metadata_` before each structured metadata name +- The original Loki log line is named `loki_line` + +### Pipeline Example + +Here is a complete example demonstrating how to use pipelines with Loki push API. + +**Step 1: Prepare the log file** + +Suppose we have a log file named `logs.json` with JSON-formatted log entries: +```json +{"timestamp":"2025-08-21 14:23:17.892","logger":"sdk.tool.DatabaseUtil","level":"ERROR","message":"Connection timeout exceeded for database pool","trace_id":"a7f8c92d1e4b4c6f9d2e5a8b3f7c1d9e","source":"application"} +{"timestamp":"2025-08-21 14:23:18.156","logger":"core.scheduler.TaskManager","level":"WARN","message":"Task queue capacity reached 85% threshold","trace_id":"b3e9f4a6c8d2e5f7a1b4c7d9e2f5a8b3","source":"scheduler"} +{"timestamp":"2025-08-21 14:23:18.423","logger":"sdk.tool.NetworkUtil","level":"INFO","message":"Successfully established connection to remote endpoint","trace_id":"c5d8e7f2a9b4c6d8e1f4a7b9c2e5f8d1","source":"network"} +``` + +Each line is a separate JSON object containing log information. + +**Step 2: Create the pipeline configuration** + +Here is a pipeline configuration that parses the JSON log entries: +```yaml +# pipeline.yaml +version: 2 +processors: + - vrl: + source: | + message = parse_json!(.loki_line) + target = { + "log_time": parse_timestamp!(message.timestamp, "%Y-%m-%d %T%.3f"), + "log_level": message.level, + "log_source": message.source, + "logger": message.logger, + "message": message.message, + "trace_id": message.trace_id, + } + . = target +transform: + - field: log_time + type: time, ms + index: timestamp +``` + +The pipeline content is straightforward: we use `vrl` processor to parse the line into a JSON object, then extract the fields to the root level. +`log_time` is specified as the time index in the transform section, other fields will be auto-inferred by the pipeline engine, see [pipeline version 2](/reference/pipeline/pipeline-config.md#transform-in-version-2) for details. + +Note that the input field name is `loki_line`, which contains the original log line from Loki. + +**Step 3: Configure Grafana Alloy** + +Prepare an Alloy configuration file to read the log file and send it to GreptimeDB: +``` +loki.source.file "greptime" { + targets = [ + {__path__ = "/logs.json"}, + ] + forward_to = [loki.write.greptime_loki.receiver] +} + +loki.write "greptime_loki" { + endpoint { + url = "http://127.0.0.1:4000/v1/loki/api/v1/push" + headers = { + "x-greptime-pipeline-name" = "pp", + } + } + external_labels = { + "job" = "greptime", + "from" = "alloy", + } +} +``` + +In the `greptime_loki`, the `x-greptime-pipeline-name` header is added to indicating the input data should be processed by the pipeline engine. + +**Step 4: Deploy and run** + +1. First, start your GreptimeDB instance. See [here](/getting-started/installation/overview.md) for quick startup. + +2. [Upload](/user-guide/logs/manage-pipelines.md#create-a-pipeline) the pipeline configuration to the database using `curl`: + +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/pp" -F "file=@pipeline.yaml" +``` + +3. Start the Alloy Docker container to process the logs: +```shell +docker run --rm \ + -v ./config.alloy:/etc/alloy/config.alloy \ + -v ./logs.json:/logs.json \ + --network host \ + grafana/alloy:latest \ + run --server.http.listen-addr=0.0.0.0:12345 --storage.path=/var/lib/alloy/data \ + /etc/alloy/config.alloy +``` + +**Step 5: Verify the results** + +After the logs are processed, you can verify that they have been successfully ingested and parsed. The database logs will show the ingestion activity. + +Query the table using a MySQL client to see the parsed log data: +```sql +mysql> show tables; ++-----------+ +| Tables | ++-----------+ +| loki_logs | +| numbers | ++-----------+ +2 rows in set (0.00 sec) + +mysql> select * from loki_logs limit 1 \G +*************************** 1. row *************************** + log_time: 2025-08-21 14:23:17.892000 + log_level: ERROR +log_source: application + logger: sdk.tool.DatabaseUtil + message: Connection timeout exceeded for database pool + trace_id: a7f8c92d1e4b4c6f9d2e5a8b3f7c1d9e +1 row in set (0.01 sec) +``` + +This output demonstrates that the pipeline engine has successfully parsed the original JSON log lines and extracted the structured data into separate columns. + +For more details about pipeline configuration and features, refer to the [pipeline documentation](/reference/pipeline/pipeline-config.md). diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/opentelemetry.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/opentelemetry.md new file mode 100644 index 0000000000..f81e6b6b20 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/opentelemetry.md @@ -0,0 +1,290 @@ +--- +keywords: [OpenTelemetry, OTLP, metrics, logs, traces, integration, data model] +description: Instructions for integrating OpenTelemetry with GreptimeDB, including metrics, logs, and traces data model mapping, example configurations, and supported protocols. +--- + +# OpenTelemetry Protocol (OTLP) + +[OpenTelemetry](https://opentelemetry.io/) is a vendor-neutral open-source observability framework for instrumenting, generating, collecting, and exporting telemetry data such as traces, metrics, logs. The OpenTelemetry Protocol (OTLP) defines the encoding, transport, and delivery mechanism of telemetry data between telemetry sources, intermediate processes such as collectors and telemetry backends. + +## OpenTelemetry Collectors + +You can easily configure GreptimeDB as the target for your OpenTelemetry collector. +For more information, please refer to the [OTel Collector](otel-collector.md) and [Grafana Alloy](alloy.md) example. + +## HTTP Base Endpoint + +[Base endpoint URL](https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/#otel_exporter_otlp_endpoint) for all signal types: `http{s}:///v1/otlp` + +This unified endpoint is useful when sending multiple signal types (metrics, logs, and traces) to the same destination, simplifying your OpenTelemetry configuration. + +## Metrics + +GreptimeDB is an observability backend to consume OpenTelemetry Metrics natively via [OTLP/HTTP](https://opentelemetry.io/docs/specs/otlp/#otlphttp) protocol. + +### OTLP/HTTP API + +To send OpenTelemetry Metrics to GreptimeDB through OpenTelemetry SDK libraries, use the following information: + +- URL: `http{s}:///v1/otlp/v1/metrics` +- Headers: + - `X-Greptime-DB-Name`: `` + - `Authorization`: `Basic` authentication, which is a Base64 encoded string of `:`. For more information, please refer to [Authentication](https://docs.greptime.com/user-guide/deployments-administration/authentication/static/) and [HTTP API](https://docs.greptime.com/user-guide/protocols/http#authentication) + +The request uses binary protobuf to encode the payload, so you need to use packages that support `HTTP/protobuf`. For example, in Node.js, you can use [`exporter-trace-otlp-proto`](https://www.npmjs.com/package/@opentelemetry/exporter-trace-otlp-proto); in Go, you can use [`go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`](https://pkg.go.dev/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp); in Java, you can use [`io.opentelemetry:opentelemetry-exporter-otlp`](https://mvnrepository.com/artifact/io.opentelemetry/opentelemetry-exporter-otlp); and in Python, you can use [`opentelemetry-exporter-otlp-proto-http`](https://pypi.org/project/opentelemetry-exporter-otlp-proto-http/). + +:::tip NOTE +The package names may change according to OpenTelemetry, so we recommend that you refer to the official OpenTelemetry documentation for the most up-to-date information. +::: + +For more information about the OpenTelemetry SDK, please refer to the official documentation for your preferred programming language. + +### Example Code + +Here are some example codes about how to setup the request in different languages: + + + + + +```ts +const auth = Buffer.from(`${username}:${password}`).toString('base64') +const exporter = new OTLPMetricExporter({ + url: `https://${dbHost}/v1/otlp/v1/metrics`, + headers: { + Authorization: `Basic ${auth}`, + 'X-Greptime-DB-Name': db, + }, + timeoutMillis: 5000, +}) +``` + + + + + +```Go +auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", *username, *password))) +exporter, err := otlpmetrichttp.New( + context.Background(), + otlpmetrichttp.WithEndpoint(*dbHost), + otlpmetrichttp.WithURLPath("/v1/otlp/v1/metrics"), + otlpmetrichttp.WithHeaders(map[string]string{ + "X-Greptime-DB-Name": *dbName, + "Authorization": "Basic " + auth, + }), + otlpmetrichttp.WithTimeout(time.Second*5), +) +``` + + + + + +```Java +String endpoint = String.format("https://%s/v1/otlp/v1/metrics", dbHost); +String auth = username + ":" + password; +String b64Auth = new String(Base64.getEncoder().encode(auth.getBytes())); +OtlpHttpMetricExporter exporter = OtlpHttpMetricExporter.builder() + .setEndpoint(endpoint) + .addHeader("X-Greptime-DB-Name", db) + .addHeader("Authorization", String.format("Basic %s", b64Auth)) + .setTimeout(Duration.ofSeconds(5)) + .build(); +``` + + + + + +```python +auth = f"{username}:{password}" +b64_auth = base64.b64encode(auth.encode()).decode("ascii") +endpoint = f"https://{host}/v1/otlp/v1/metrics" +exporter = OTLPMetricExporter( + endpoint=endpoint, + headers={"Authorization": f"Basic {b64_auth}", "X-Greptime-DB-Name": db}, + timeout=5) +``` + + + + + +You can find executable demos on GitHub at the links: [Go](https://github.com/GreptimeCloudStarters/quick-start-go), [Java](https://github.com/GreptimeCloudStarters/quick-start-java), [Python](https://github.com/GreptimeCloudStarters/quick-start-python), and [Node.js](https://github.com/GreptimeCloudStarters/quick-start-node-js). + +:::tip NOTE +The example codes above may be outdated according to OpenTelemetry. We recommend that you refer to the official OpenTelemetry documentation for the most up-to-date information. +::: + +For more information on the example code, please refer to the official documentation for your preferred programming language. + +### Prometheus Compatibility + +Starting from `v0.16`, GreptimeDB is introducing a Prometheus-compatible mode for the OTLP metrics ingestion. +If the metrics data is persisted using the Prometheus-compatible format, you should be able to query them using PromQL, just like any Prometheus metrics. + +If you have not ingested any OTLP metrics before, it will automatically use the Prometheus-compatible format. +Otherwise, it will remain the old data format with the existing table, but use the new data format for any newly created tables. + +GreptimeDB pre-processes the incoming data before persisting them, including: +1. Converting the metric names(table names) and the label names to the Prometheus style(e.g: replace `.` with `_`). See [here](https://opentelemetry.io/docs/specs/otel/compatibility/prometheus_and_openmetrics/#metric-metadata-1) for details. +2. Discarding some resource attributes and all scope attributes by default. The kept resource attributes name list can be found [here](https://prometheus.io/docs/guides/opentelemetry/#promoting-resource-attributes). This behavior is configurable. + +Note, `Sum` and `Histogram` data in OTLP can have delta temporality. +GreptimeDB saves their value directly without calculating the cumulative value. +See [here](https://grafana.com/blog/2023/09/26/opentelemetry-metrics-a-guide-to-delta-vs.-cumulative-temporality-trade-offs/) for some context. + +You can set the HTTP headers to configure the pre-processing behaviors. Here are the options: +1. `x-greptime-otlp-metric-promote-all-resource-attrs`: Persist all resource attributes. Default to `false`. +2. `x-greptime-otlp-metric-promote-resource-attrs`: If not persisting all resource attributes, the attribute name list to be kept. Use `;` to join the name list. +3. `x-greptime-otlp-metric-ignore-resource-attrs`: If persisting all resource attributes, the attribute name list to be ignored. Use `;` to join the name list. +4. `x-greptime-otlp-metric-promote-scope-attrs`: Whether to persist the scope attributes. Default to `false`. + +### Data Model + +The Prometheus-compatible OTLP metrics data model is mapped to the GreptimeDB data model according to the following rules: + +- The name of the Metric will be used as the name of the GreptimeDB table, and the table will be automatically created if it does not exist. +- Only selected resource attributes are kept by default. See above for details and configuration options. Attributes are used as tag columns in the GreptimeDB table. +- You can refer to the [Prometheus Data Model](./prometheus.md#data-model) for other details. +- ExponentialHistogram is not supported yet. + +If you're using OTLP metrics before `v0.16`, you're ingesting the data without the Prometheus compatibility. Here are some mapping differences: + +- All attributes, including resource attributes, scope attributes, and data point attributes, will be used as tag columns of the GreptimeDB table. +- Each quantile of the Summary data type will be used as a separated data column of GreptimeDB, and the column name is `greptime_pxx`, where xx is the quantile, such as 90/99, etc. + +## Logs + +GreptimeDB consumes OpenTelemetry Logs natively via [OTLP/HTTP](https://opentelemetry.io/docs/specs/otlp/#otlphttp) protocol. + +### OTLP/HTTP API + +To send OpenTelemetry Logs to GreptimeDB through OpenTelemetry SDK libraries, use the following information: + +- URL: `http{s}:///v1/otlp/v1/logs` +- Headers: + - `X-Greptime-DB-Name`: `` + - `Authorization`: `Basic` authentication, which is a Base64 encoded string of `:`. For more information, please refer to [Authentication](/user-guide/deployments-administration/authentication/static.md) and [HTTP API](/user-guide/protocols/http.md#authentication). + - `X-Greptime-Log-Table-Name`: `` (optional) - The table name to store the logs. If not provided, the default table name is `opentelemetry_logs`. + - `X-Greptime-Log-Extract-Keys`: `` (optional) - The keys to extract from the attributes. The keys should be separated by commas (`,`). For example, `key1,key2,key3` will extract the keys `key1`, `key2`, and `key3` from the attributes and promote them to the top level of the log, setting them as tags. If the field type is array, float, or object, an error will be returned. If a pipeline is provided, this setting will be ignored. + - `X-Greptime-Log-Pipeline-Name`: `` (optional) - The pipeline name to process the logs. If not provided, the extract keys will be used to process the logs. + - `X-Greptime-Log-Pipeline-Version`: `` (optional) - The pipeline version to process the logs. If not provided, the latest version of the pipeline will be used. + +The request uses binary protobuf to encode the payload, so you need to use packages that support `HTTP/protobuf`. + +:::tip NOTE +The package names may change according to OpenTelemetry, so we recommend that you refer to the official OpenTelemetry documentation for the most up-to-date information. +::: + +For more information about the OpenTelemetry SDK, please refer to the official documentation for your preferred programming language. + +### Example Code + +Please refer to the sample code in [opentelemetry-collector](#opentelemetry-collector), which includes how to send OpenTelemetry logs to GreptimeDB. +You can also refer to the sample code in the [Alloy documentation](alloy.md#logs) to learn how to send OpenTelemetry logs to GreptimeDB. + +### Data Model + +The OTLP logs data model is mapped to the GreptimeDB data model according to the following rules: + +Default table schema: + +```sql ++-----------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-----------------------+---------------------+------+------+---------+---------------+ +| timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| trace_id | String | | YES | | FIELD | +| span_id | String | | YES | | FIELD | +| severity_text | String | | YES | | FIELD | +| severity_number | Int32 | | YES | | FIELD | +| body | String | | YES | | FIELD | +| log_attributes | Json | | YES | | FIELD | +| trace_flags | UInt32 | | YES | | FIELD | +| scope_name | String | PRI | YES | | TAG | +| scope_version | String | | YES | | FIELD | +| scope_attributes | Json | | YES | | FIELD | +| scope_schema_url | String | | YES | | FIELD | +| resource_attributes | Json | | YES | | FIELD | +| resource_schema_url | String | | YES | | FIELD | ++-----------------------+---------------------+------+------+---------+---------------+ +17 rows in set (0.00 sec) +``` + +- You can use `X-Greptime-Log-Table-Name` to specify the table name for storing the logs. If not provided, the default table name is `opentelemetry_logs`. +- All attributes, including resource attributes, scope attributes, and log attributes, will be stored as a JSON column in the GreptimeDB table. +- The timestamp of the log will be used as the timestamp index in GreptimeDB, with the column name `timestamp`. It is preferred to use `time_unix_nano` as the timestamp column. If `time_unix_nano` is not provided, `observed_time_unix_nano` will be used instead. + +### Append Only + +By default, log table created by OpenTelemetry API are in [append only +mode](/user-guide/deployments-administration/performance-tuning/design-table.md#when-to-use-append-only-tables). + +## Traces + +GreptimeDB supports writing OpenTelemetry traces data directly via the [OTLP/HTTP](https://opentelemetry.io/docs/specs/otlp/#otlphttp) protocol, and it also provides a table model of OpenTelemetry traces for users to query and analyze traces data conveniently. + +### OTLP/HTTP API + +You can use [OpenTelemetry SDK](https://opentelemetry.io/docs/languages/) or other similar technologies to add traces data to your application. You can also use [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) to collect traces data and use GreptimeDB as the backend storage. + +To send OpenTelemetry traces data to GreptimeDB through OpenTelemetry SDK libraries, please use the following information: + +- URL: `http{s}:///v1/otlp/v1/traces` +- Headers: The headers section is the same as the [Logs](#Logs) section, you can refer to the [Logs](#Logs) section for more information. + +By default, GreptimeDB will write traces data to the `opentelemetry_traces` table in the `public` database. If you want to write traces data to a different table, you can use the `X-Greptime-DB-Name` and `X-Greptime-Trace-Table-Name` headers to specify the database and table name. + +GreptimeDB will accept **protobuf encoded traces data** via **HTTP protocol** and the following headers are required: + +- `content-type` should be configured as `application/x-protobuf`; +- `x-greptime-pipeline-name` should be configured as `greptime_trace_v1`; + +### Example Code + +You can directly send OpenTelemetry traces data to GreptimeDB, or use OpenTelemetry Collector to collect traces data and use GreptimeDB as the backend storage. Please refer to the example code in the [OpenTelemetry Collector documentation](/user-guide/traces/read-write.md#opentelemetry-collector) to learn how to send OpenTelemetry traces data to GreptimeDB. + +### Data Model + +GreptimeDB will map the OTLP traces data model to the following table schema: + +```sql ++------------------------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++------------------------------------+---------------------+------+------+---------+---------------+ +| timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| timestamp_end | TimestampNanosecond | | YES | | FIELD | +| duration_nano | UInt64 | | YES | | FIELD | +| parent_span_id | String | | YES | | FIELD | +| trace_id | String | | YES | | FIELD | +| span_id | String | | YES | | FIELD | +| span_kind | String | | YES | | FIELD | +| span_name | String | | YES | | FIELD | +| span_status_code | String | | YES | | FIELD | +| span_status_message | String | | YES | | FIELD | +| trace_state | String | | YES | | FIELD | +| scope_name | String | | YES | | FIELD | +| scope_version | String | | YES | | FIELD | +| service_name | String | PRI | YES | | TAG | +| span_attributes.net.sock.peer.addr | String | | YES | | FIELD | +| span_attributes.peer.service | String | | YES | | FIELD | +| span_events | Json | | YES | | FIELD | +| span_links | Json | | YES | | FIELD | ++------------------------------------+---------------------+------+------+---------+---------------+ +``` + +- Each row represents a single span +- The core OpenTelemetry fields such as `trace_id`, `span_id`, and `service_name` are promoted as dedicated table columns +- Resource attributes and span attributes are automatically flattened into separate columns, with column names being their JSON keys (using `.` to connect multiple levels of nesting) +- `span_events` and `span_links` are stored as JSON data types by default + +Note: +1. The `greptime_trace_v1` process uses the `trace_id` field to divide data into partitions for better performance. **Please make sure the first letter of the `trace_id` is evenly distributed**. +2. For non-test scenarios, you might want to set a `ttl` to the trace table to avoid data overload. Set the HTTP header `x-greptime-hints: ttl=7d` would set a `ttl` of 7 days during the table creation, see [here](/reference/sql/create.md#table-options) for more details about `ttl` in table option. + +### Append Only + +By default, log table created by OpenTelemetry API are in [append only +mode](/user-guide/deployments-administration/performance-tuning/design-table.md#when-to-use-append-only-tables). diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/otel-collector.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/otel-collector.md new file mode 100644 index 0000000000..8ed3189fbe --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/otel-collector.md @@ -0,0 +1,80 @@ +--- +keywords: [OpenTelemetry, OTLP, metrics, logs, traces, integration, 'otel-collector'] +description: Instructions for integrating OpenTelemetry Collector with GreptimeDB. +--- + +# OTel Collector + +[OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) offers a vendor-agnostic implementation of how to receive, process and export telemetry data. It can act as an intermediate layer to send data from different sources to GreptimeDB. +Below is a sample configuration for sending data to GreptimeDB using OpenTelemetry Collector. + +```yaml +extensions: + basicauth/client: + client_auth: + username: + password: + +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +exporters: + otlphttp/traces: + endpoint: 'http://127.0.0.1:4000/v1/otlp' + # auth: + # authenticator: basicauth/client + headers: + # x-greptime-db-name: '' + x-greptime-pipeline-name: 'greptime_trace_v1' + tls: + insecure: true + otlphttp/logs: + endpoint: 'http://127.0.0.1:4000/v1/otlp' + # auth: + # authenticator: basicauth/client + headers: + # x-greptime-db-name: '' + # x-greptime-log-table-name: '' + # x-greptime-pipeline-name: '' + tls: + insecure: true + + otlphttp/metrics: + endpoint: 'http://127.0.0.1:4000/v1/otlp' + # auth: + # authenticator: basicauth/client + headers: + # x-greptime-db-name: '' + tls: + insecure: true + +service: + # extensions: [basicauth/client] + pipelines: + traces: + receivers: [otlp] + exporters: [otlphttp/traces] + logs: + receivers: [otlp] + exporters: [otlphttp/logs] + metrics: + receivers: [otlp] + exporters: [otlphttp/metrics] +``` + +In the above configuration, we define a receiver `otlp` that can receive data from OpenTelemetry. We also define three exporters: `otlphttp/traces`, `otlphttp/logs`, and `otlphttp/metrics`, which send data to the OTLP endpoint of GreptimeDB. + +Based on the otlphttp protocol, we have added some headers to specify certain parameters, such as `x-greptime-pipeline-name` and `x-greptime-log-table-name`: +* The `x-greptime-pipeline-name` header is used to specify the pipeline name to use, and, +* the `x-greptime-log-table-name` header is used to specify the table name in GreptimeDB where the data will be written. + +If you have enabled [authentication](/user-guide/deployments-administration/authentication/overview.md) in GreptimeDB, you need to use the `basicauth/client` extension to handle basic authentication. + +Here, we strongly recommend using different exporters to handle traces, logs, and metrics separately. On one hand, GreptimeDB supports some specific headers to customize processing flows; on the other hand, this also helps with data isolation. + +For more about OpenTelemetry protocols, please read the [doc](/user-guide/ingest-data/for-observability/opentelemetry.md). \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/overview.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/overview.md new file mode 100644 index 0000000000..b1844628a7 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/overview.md @@ -0,0 +1,17 @@ +--- +keywords: [observability, integration, Prometheus, Vector, OpenTelemetry, InfluxDB, Loki] +description: Overview of integrating GreptimeDB with observability tools like Prometheus, Vector, OpenTelemetry, InfluxDB, and Loki for real-time monitoring and analysis. +--- + +# Ingest Data for Observability + +In observability scenarios, +the ability to monitor and analyze system performance in real-time is crucial. +GreptimeDB integrates seamlessly with leading observability tools to provide a comprehensive view of your system's health and performance metrics. + +- [Store and analyze trillions of logs in GreptimeDB and gain insights within minutes](/user-guide/logs/overview.md). +- [Prometheus Remote Write](prometheus.md): Integrate GreptimeDB as remote storage for Prometheus, suitable for real-time monitoring and alerting. +- [Vector](vector.md): Use GreptimeDB as a sink for Vector, ideal for complex data pipelines and diverse data sources. +- [OpenTelemetry](opentelemetry.md): Collect and export telemetry data to GreptimeDB for detailed observability insights. +- [InfluxDB Line Protocol](influxdb-line-protocol.md): A widely-used protocol for time-series data, facilitating migration from InfluxDB to GreptimeDB. The Telegraf integration method is also introduced in this document. +- [Loki](loki.md): A widely-used log write protocol, facilitating migration from Loki to GreptimeDB. The Alloy integration method is also introduced in this document. diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/prometheus.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/prometheus.md new file mode 100644 index 0000000000..82508948ba --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/prometheus.md @@ -0,0 +1,343 @@ +--- +keywords: [Prometheus, integration, remote write, data model, efficiency] +description: Guide to integrating Prometheus with GreptimeDB for long-term storage, including configuration, data model mapping, and efficiency improvements. +--- + +# Prometheus + +GreptimeDB can serve as a long-term storage solution for Prometheus, +providing a seamless integration experience. + +## Remote write configuration + +### Prometheus configuration file + +To configure Prometheus with GreptimeDB, +update your [Prometheus configuration file](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#configuration-file) (`prometheus.yml`) as follows: + +```yaml +remote_write: +- url: http://localhost:4000/v1/prometheus/write?db=public +# Uncomment and set credentials if authentication is enabled +# basic_auth: +# username: greptime_user +# password: greptime_pwd + +remote_read: +- url: http://localhost:4000/v1/prometheus/read?db=public +# Uncomment and set credentials if authentication is enabled +# basic_auth: +# username: greptime_user +# password: greptime_pwd +``` + +- The host and port in the URL represent the GreptimeDB server. In this example, the server is running on `localhost:4000`. You can replace it with your own server address. For the HTTP protocol configuration in GreptimeDB, please refer to the [protocol options](/user-guide/deployments-administration/configuration.md#protocol-options). +- The `db` parameter in the URL represents the database to which we want to write data. It is optional. By default, the database is set to `public`. +- `basic_auth` is the authentication configuration. Fill in the username and password if GreptimeDB authentication is enabled. Please refer to the [authentication document](/user-guide/deployments-administration/authentication/overview.md). + +### Grafana Alloy configuration file + +If you are using Grafana Alloy, configure the remote write endpoint in the Alloy configuration file (`config.alloy`). For more information, refer to the [Alloy documentation](alloy.md#prometheus-remote-write). + +### Vector configuration file + +If you use Vector, configure Remote Write in Vector's configuration file (vector.toml). For more information, see the [Vector documentation](vector.md#using-prometheus-remote-write-protocol). + +## Data Model + +In the [data model](/user-guide/concepts/data-model.md) of GreptimeDB, data is organized into tables with columns for tags, time index, and fields. +GreptimeDB can be thought of as a multi-value data model, +automatically grouping multiple Prometheus metrics into corresponding tables. +This allows for efficient data management and querying. + +![Data Model](/PromQL-multi-value-data-model.png) + +When the metrics are written into GreptimeDB by remote write endpoint, they will be transformed as +follows: + +| Sample Metrics | In GreptimeDB | GreptimeDB Data Types | +| -------------- | ------------------------- | --------------------- | +| Name | Table (Auto-created) Name | String | +| Value | Column (Field) | Double | +| Timestamp | Column (Time Index) | Timestamp | +| Label | Column (Tag) | String | + +For example, the following Prometheus metric: + +```txt +prometheus_remote_storage_samples_total{instance="localhost:9090", job="prometheus", +remote_name="648f0c", url="http://localhost:4000/v1/prometheus/write"} 500 +``` + +will be transformed as a row in the table `prometheus_remote_storage_samples_total`: + +| Column | Value | Column Data Type | +| :----------------- | :------------------------------------------ | :----------------- | +| instance | localhost:9090 | String | +| job | prometheus | String | +| remote_name | 648f0c | String | +| url | `http://localhost:4000/v1/prometheus/write` | String | +| greptime_value | 500 | Double | +| greptime_timestamp | The sample's unix timestamp | Timestamp | + + +## Improve efficiency by using metric engine + +The Prometheus remote writing always creates a large number of small tables. +These tables are classified as logical tables in GreptimeDB. +However, having a large number of small tables can be inefficient for both data storage and query performance. +To address this, GreptimeDB introduces the [metric engine](/contributor-guide/datanode/metric-engine.md) feature, +which stores the data represented by the logical tables in a single physical table. +This approach reduces storage overhead and improves columnar compression efficiency. + +The metric engine is enabled by default in GreptimeDB, +and you don't need to specify any additional configuration. +By default, the physical table used is `greptime_physical_table`. +If you want to use a specific physical table, you can specify the `physical_table` parameter in the remote write URL. +If the specified physical table doesn't exist, it will be automatically created. + +```yaml +remote_write: +- url: http://localhost:4000/v1/prometheus/write?db=public&physical_table=greptime_physical_table +``` + + +Data is stored in the physical table, +while queries are performed on logical tables to provide an intuitive view from a metric perspective. +For instance, when successfully writing data, you can use the following command to display the logical tables: + +```sql +show tables; +``` + +```sql ++---------------------------------------------------------------+ +| Tables | ++---------------------------------------------------------------+ +| prometheus_remote_storage_enqueue_retries_total | +| prometheus_remote_storage_exemplars_pending | +| prometheus_remote_storage_read_request_duration_seconds_count | +| prometheus_rule_group_duration_seconds | +| ...... | ++---------------------------------------------------------------+ +``` + +The physical table itself can also be queried. +It contains columns from all the logical tables, +making it convenient for multi-join analysis and computation. + +To view the schema of the physical table, use the `DESC TABLE` command: + +```sql +DESC TABLE greptime_physical_table; +``` + +The physical table includes all the columns from the logical tables: + +```sql ++--------------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+----------------------+------+------+---------+---------------+ +| greptime_timestamp | TimestampMillisecond | PRI | NO | | TIMESTAMP | +| greptime_value | Float64 | | YES | | FIELD | +| __table_id | UInt32 | PRI | NO | | TAG | +| __tsid | UInt64 | PRI | NO | | TAG | +| device | String | PRI | YES | | TAG | +| instance | String | PRI | YES | | TAG | +| job | String | PRI | YES | | TAG | +| error | String | PRI | YES | | TAG | +... +``` + +You can use the `SELECT` statement to filter data from the physical table as needed. +For example, you can filter data based on the `device` condition from logical table A and the `job` condition from logical table B: + +```sql +SELECT * +FROM greptime_physical_table +WHERE greptime_timestamp > "2024-08-07 03:27:26.964000" + AND device = "device1" + AND job = "job1"; +``` + +### GreptimeDB cluster with metric engine + +If you are using GreptimeDB cluster for Prometheus remote write, you may notice +that only 1 datanode taking all the workload and other datanodes receives no +traffic. This is because with default settings, there is only 1 metric engine +physical table, and only 1 partition(region) in that table. The datanode that +serves the partition will take all the data ingestion. + +Why we are not creating more partitions by default? [GreptimeDB's table +partition](/user-guide/deployments-administration/manage-data/table-sharding.md) +is based pre-configured partition columns. However, in Prometheus ecosystem, +there is no common column (label, as in Prometheus) that is suitable for good +partition rules. + +To fix this, we recommend you to define your own partition rule based on your +data model. For example, it can be `namespace` if your are monitoring a +kubernetes cluster. The partition columns should have enough cardinality to +divide data. Also we recommend you to create 2x-3x partitions on initial +datanode count, so when you scaling more datanodes in your cluster, just migrate +those partitions to new ones. + +An example DDL of partitioned physical table based on `namespace` label: + +```sql +CREATE TABLE greptime_physical_table ( + greptime_timestamp TIMESTAMP(3) NOT NULL, + greptime_value DOUBLE NULL, + namespace STRING PRIMARY KEY, + TIME INDEX (greptime_timestamp), +) +PARTITION ON COLUMNS (namespace) ( + namespace <'g', + namespace >= 'g' AND namespace < 'n', + namespace >= 'n' AND namespace < 't', + namespace >= 't' +) +ENGINE = metric +with ( + "physical_metric_table" = "", +); +``` + +Note that you won't have need add all possible *PRIMARY KEY* (label) here, +metric engine will add them automatically. Only labels you use for partitioning +are required to be defined ahead of time. + +## Special labels for ingestion options + +:::warning Experimental Feature +This experimental feature may contain unexpected behavior, have its functionality change in the future. +::: + +Normally, the complete dataset of a remote write request is ingested into the database under the same option, for example, a default physical table with metric engine enabled. +All the logical tables (i.e, the metrics) is backed with the same physical table, even when the number of metrics grows. +It's probably fine for data ingestion. However, this set-up might slow down the query speed if you just want to query for a small group of metrics, but the database have to scan the complete dataset because they are all in the same physical table. + +If you can foresee a large data volume and incremental queries upon a small group of metrics each time, then it might be useful to split the storage during the ingestion to reduce the query overhead later. This fine-grade level of control can be achieved using ingest options for each metric within a remote request. + +Starting from `v0.15`, GreptimeDB is adding support for special labels. +There labels (along with there values) will turn into ingest options during the parsing phase, allowing individual metric within a request to be more precisely controlled. +The labels are not mutually exclusive, so they can be combined together to produce more versatile controlling. + +Here is a representative diagram of special labels for a metric. Note this is not the actual data model of a metric. +| `__name__` | `__database__` | `__physical_table__` | `pod_name_label` | `__normal_label_with_underscore_prefix__` | `timestamp` | `value` | +|------------------|----------------|----------------------|---------------------|-------------------------------------------|-------------------------|---------| +| some_metric_name | public | p_1 | random_k8s_pod_name | true | 2025-06-17 16:31:52.000 | 12.1 | + +The special labels you see above are just normal valid labels in Prometheus. +GreptimeDB recognizes some of the label names and turns them into ingest options. +It's much like the custom HTTP headers, where you just set a valid HTTP header and its value to indicate following operations, only the header pair means nothing outside your program. + +Here is a list of supported label names: +- `__database__` +- `__physical_table__` + +### Setting labels + +How to set labels to the metrics is very dependent on the tools (or code) that collects the metrics and send them over to the database. + +If you're using Prometheus to scrape metrics from the source and send them to GreptimeDB using remote write, you can add `external_labels` in the global config. +Refer to the [docs](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#configuration-file) here. +It's the same for other collecting tools. You may have to find the relevant configuration for your tool of choice. + +### `__database__` + +This option decides which database the metric goes into. Note, the database should be created in advance(for instance, using `create database xxx` SQL). + +Metrics from the same tech stack can have same metric names. +For example, if you have two Kubernetes clusters with very different content, and you deploy a single collector on both clusters, they will generate metrics with same names but with different labels or values. +If the metrics are collected and ingested into the same database, then on a Grafana dashboard you will have to manually set every label selection on every diagram to view the two clusters' metrics separately. This can be very tedious and painful. + +In this case, you might want to store the metrics on different databases during ingestion and use two dashboards to view the metrics separately. + +### `__physical_table__` + +If the metric is storing using the metric engine, then there is a physical table behind each metric's logical table. +By default, all metrics using the same physical table. +With the number of the metrics growing, this physical table becomes a super wide table. +If the metric frequency is different, then the table will be sparse. +Finding a certain metric or a certain label in the complete metrics dataset would be very time-consuming since the database have to scan all the 'irrelevant' data. + +In this case, you might want to split the metrics into different physical tables to ease the pressure on a single physical table. +It can also be helpful to group metrics by their frequency. + +Note, each metric's logical table is bound to a physical table upon creation. +So setting different physical table for the same metric within the same database won't work. + +## Using pipeline in remote write + +:::warning Experimental Feature +This experimental feature may contain unexpected behavior, have its functionality change in the future. +::: + +Starting from `v0.15`, GreptimeDB supports using pipeline to process Prometheus remote write requests. +You can simply set the HTTP header `x-greptime-pipeline-name` to the target pipeline name to enable pipeline processing. + +Here is a very simple pipeline configuration, using `vrl` processor to add a `source` label to each metric: +```YAML +version: 2 +processors: + - vrl: + source: | + .source = "local_laptop" + . + +transform: + - field: greptime_timestamp + type: time, ms + index: timestamp +``` + +The result looks something like this +``` +mysql> select * from `go_memstats_mcache_inuse_bytes`; ++----------------------------+----------------+--------------------+---------------+--------------+ +| greptime_timestamp | greptime_value | instance | job | source | ++----------------------------+----------------+--------------------+---------------+--------------+ +| 2025-07-11 07:42:03.064000 | 1200 | node_exporter:9100 | node-exporter | local_laptop | +| 2025-07-11 07:42:18.069000 | 1200 | node_exporter:9100 | node-exporter | local_laptop | ++----------------------------+----------------+--------------------+---------------+--------------+ +2 rows in set (0.01 sec) +``` + +You can refer to the [pipeline's documentation](/user-guide/logs/use-custom-pipelines.md) for more details. + +## Performance tuning + +By default, the metric engine will automatically create a physical table named `greptime_physical_table` if it does not already exist. For performance optimization, you may choose to create a physical table with customized configurations. + +### Enable skipping index + +By default, the metric engine won't create indexes for columns. You can enable it by setting the `index.type` to `skipping`. + +Create a physical table with a skipping index; all automatically added columns will have this index applied. + +```sql +CREATE TABLE greptime_physical_table ( + greptime_timestamp TIMESTAMP(3) NOT NULL, + greptime_value DOUBLE NULL, + TIME INDEX (greptime_timestamp), +) +engine = metric +with ( + "physical_metric_table" = "", + "index.type" = "skipping" +); +``` +For more configurations, please refer to the [create table](/reference/sql/create.md#create-table) section. + +## VictoriaMetrics remote write + +VictoriaMetrics slightly modified Prometheus remote write protocol for better +compression. The protocol is automatically enabled when you are using `vmagent` +to send data to a compatible backend. + +GreptimeDB has this variant supported, too. Just configure GreptimeDB's remote +write url for `vmagent`. For example, if you have GreptimeDB installed locally: + +```shell +vmagent -remoteWrite.url=http://localhost:4000/v1/prometheus/write +``` diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/vector.md b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/vector.md new file mode 100644 index 0000000000..39c9104f07 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/for-observability/vector.md @@ -0,0 +1,201 @@ +--- +keywords: [Vector, integration, configuration, data model, metrics] +description: Instructions for integrating Vector with GreptimeDB, including configuration, data model mapping, and example configurations. +--- + +# Vector + +:::tip NOTE +This document is based on Vector v0.49.0. All example configurations below are based on this version. Please adjust the host and port configurations for each sink according to your actual GreptimeDB instance. All port values below are defaults. +::: + +Vector is a high-performance observability data pipeline. It natively supports GreptimeDB as a metrics data receiver. Through Vector, you can receive metrics data from various sources including Prometheus, OpenTelemetry, StatsD, etc. GreptimeDB can serve as a sink component for Vector to receive metrics data. + +## Writing Metrics Data + +GreptimeDB supports multiple ways to write metrics data: + +- Using [`greptimedb_metrics` sink](https://vector.dev/docs/reference/configuration/sinks/greptimedb_metrics/) +- Using InfluxDB line protocol format +- Using Prometheus Remote Write protocol + +### Using `greptimedb_metrics` sink + +#### Example + +Below is an example configuration using `greptimedb_metrics` sink to write host metrics: + +```toml +# sample.toml + +[sources.in] +type = "host_metrics" + +[sinks.my_sink_id] +inputs = ["in"] +type = "greptimedb_metrics" +endpoint = ":4001" +dbname = "" +username = "" +password = "" +new_naming = true +``` + +Vector uses gRPC to communicate with GreptimeDB, so the default port for Vector sink is `4001`. If you changed the default gRPC port when starting GreptimeDB with [custom configuration](/user-guide/deployments-administration/configuration.md#configuration-file), please use your own port. + +For more requirements, please visit [Vector GreptimeDB Configuration](https://vector.dev/docs/reference/configuration/sinks/greptimedb_metrics/) to view more configuration options. + +### Data Model + +The following rules are used when storing Vector metrics into GreptimeDB: + +- Use `_` as the table name in GreptimeDB, for example, `host_cpu_seconds_total`; +- Use the timestamp of the metric as the time index of GreptimeDB, the column name is `ts`; +- Use the tags of the metric as GreptimeDB tags; +- For Vector metrics which have multiple subtypes: + - For Counter and Gauge metrics, the values are stored in the `val` column; + - For Set metrics, the number of data points are stored in the `val` column; + - For Distribution metrics, the values of each percentile are stored in the `pxx` column, where xx is the percentile, and the `min/max/avg/sum/count` columns are also stored; + - For AggregatedHistogram metrics, the values of each bucket are stored in the `bxx` column, where xx is the upper limit of the bucket, and the `sum/count` columns are also stored; + - For AggregatedSummary metrics, the values of each percentile are stored in the `pxx` column, where xx is the percentile, and the `sum/count` columns are also stored; + - For Sketch metrics, the values of each percentile are stored in the `pxx` column, where xx is the percentile, and the `min/max/avg/sum` columns are also stored; + +### Using InfluxDB Line Protocol Format + +You can use the `influx` sink to write metrics data. We recommend using v2 version of InfluxDB line protocol format. + +Below is an example configuration using `influx` sink to write host metrics: + +```toml +# sample.toml + +[sources.my_source_id] +type = "internal_metrics" + +[sinks.my_sink_id] +type = "influxdb_metrics" +inputs = [ "my_source_id" ] +bucket = "public" +endpoint = "http://:4000/v1/influxdb" +org = "" +token = "" +``` + +The above configuration uses v2 version of InfluxDB line protocol. Vector determines the InfluxDB protocol version based on fields in the TOML configuration, so please ensure the configuration contains `bucket`, `org`, and `token` fields. Specific field explanations: + +- `type`: Value for InfluxDB line protocol is `influxdb_metrics`. +- `bucket`: Database name in GreptimeDB. +- `org`: Organization name in GreptimeDB (needs to be empty). +- `token`: Token for authentication (needs to be empty). Since Influx line protocol token has special format and must start with `Token `, this differs from GreptimeDB's authentication method and is currently not compatible. If using GreptimeDB instance with authentication, please use `greptimedb_metrics`. + +For more details, please refer to [InfluxDB Line Protocol documentation](../for-iot/influxdb-line-protocol.md) to learn how to write data to GreptimeDB using InfluxDB Line Protocol. + +### Using Prometheus Remote Write Protocol + +Below is an example configuration using Prometheus Remote Write protocol to write host metrics: + +```toml +# sample.toml + +[sources.my_source_id] +type = "internal_metrics" + +[sinks.prometheus_remote_write] +type = "prometheus_remote_write" +inputs = [ "my_source_id" ] +endpoint = "http://:4000/v1/prometheus/write?db=" +compression = "snappy" +auth = { strategy = "basic", username = "", password = "" } +``` + +## Writing Logs Data + +GreptimeDB supports multiple ways to write logs data: + +- Using [`greptimedb_logs` sink](https://vector.dev/docs/reference/configuration/sinks/greptimedb_logs/) to write logs data to GreptimeDB. +- Using Loki protocol to write logs data to GreptimeDB. + +We strongly recommend all users to use `greptimedb_logs` sink to write logs data, as it is optimized for GreptimeDB and better supports GreptimeDB features. We also recommend enabling compression for various protocols to improve data transmission efficiency. + +### Using `greptimedb_logs` sink (recommended) + +```toml +# sample.toml + +[sources.my_source_id] +type = "demo_logs" +count = 10 +format = "apache_common" +interval = 1 + +[sinks.my_sink_id] +type = "greptimedb_logs" +inputs = [ "my_source_id" ] +compression = "gzip" +dbname = "public" +endpoint = "http://:4000" +extra_headers = { "skip_error" = "true" } +pipeline_name = "greptime_identity" +table = "
" +username = "" +password = "" + +[sinks.my_sink_id.extra_params] +source = "vector" +x-greptime-pipeline-params = "max_nested_levels=10" +``` + +This example demonstrates how to use `greptimedb_logs` sink to write generated demo logs data to GreptimeDB. For more information, please refer to [Vector greptimedb_logs sink](https://vector.dev/docs/reference/configuration/sinks/greptimedb_logs/) documentation. + +### Using Loki Protocol + +#### Example + +```toml +[sources.generate_syslog] +type = "demo_logs" +format = "syslog" +count = 100 +interval = 1 + +[transforms.remap_syslog] +inputs = ["generate_syslog"] +type = "remap" +source = """ +.labels = { + "host": .host, + "service": .service, +} +.structured_metadata = { + "source_type": .source_type +} +""" + +[sinks.my_sink_id] +type = "loki" +inputs = ["remap_syslog"] +compression = "snappy" +endpoint = "http://:4000" +out_of_order_action = "accept" +path = "/v1/loki/api/v1/push" +encoding = { codec = "raw_message" } +labels = { "*" = "{{labels}}" } +structured_metadata = { "*" = "{{structured_metadata}}" } +auth = {strategy = "basic", user = "", password = ""} +``` + +The above configuration writes logs data to GreptimeDB using Loki protocol. Specific configuration item explanations: + +- `compression`: Sets compression algorithm for data transmission, using `snappy` here. +- `endpoint`: Specifies Loki's receiving address. +- `out_of_order_action`: Sets how to handle out-of-order logs, choosing `accept` here to accept out-of-order logs. GreptimeDB supports writing out-of-order logs. +- `path`: Specifies Loki's API path. +- `encoding`: Sets data encoding method, using `raw_message` here. +- `labels`: Specifies log labels, mapping `labels` content to `{{labels}}` here. That is the `labels` field in remap_syslog. +- `structured_metadata`: Specifies structured metadata, mapping `structured_metadata` content to `{{structured_metadata}}` here. That is the `structured_metadata` field in remap_syslog. + +For meanings of `labels` and `structured_metadata`, please refer to [Loki documentation](https://grafana.com/docs/loki/latest/get-started/labels/bp-labels/). + +For Loki protocol, `labels` will use Tag type in time series scenarios by default, please avoid using high-cardinality fields for these fields. `structured_metadata` will be stored as a complete JSON field. + +Note that since Vector's configuration doesn't allow setting headers, you cannot specify pipeline. If you need to use pipeline functionality, please consider using `greptimedb_logs` sink. diff --git a/versioned_docs/version-1.0/user-guide/ingest-data/overview.md b/versioned_docs/version-1.0/user-guide/ingest-data/overview.md new file mode 100644 index 0000000000..0e74078e0a --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/ingest-data/overview.md @@ -0,0 +1,29 @@ +--- +keywords: [data ingestion, automatic schema generation, observability, IoT, real-time monitoring] +description: Overview of data ingestion methods in GreptimeDB, including automatic schema generation and recommended methods for different scenarios. +--- + +# Ingest Data + +GreptimeDB supports automatic schema generation and flexible data ingestion methods, +enabling you to easily write data tailored to your specific scenarios. + +## Automatic Schema Generation + +GreptimeDB supports schemaless writing, automatically creating tables and adding necessary columns as data is ingested. +This capability ensures that you do not need to manually define schemas beforehand, making it easier to manage and integrate diverse data sources seamlessly. + +This feature is supported for all protocols and integrations, except [SQL](./for-iot/sql.md). + +## Recommended Data Ingestion Methods + +GreptimeDB supports various data ingestion methods for specific scenarios, ensuring optimal performance and integration flexibility. + +- [For Observability Scenarios](./for-observability/overview.md): Suitable for real-time monitoring and alerting. +- [For IoT Scenarios](./for-iot/overview.md): Suitable for real-time data and complex IoT infrastructures. + +## Next Steps + +- [Query Data](/user-guide/query-data/overview.md): Learn how to explore your data by querying your GreptimeDB database. +- [Manage Data](/user-guide/manage-data/overview.md): Learn how to update and delete data, etc., to ensure data integrity and efficient data management. + diff --git a/versioned_docs/version-1.0/user-guide/integrations/alloy.md b/versioned_docs/version-1.0/user-guide/integrations/alloy.md new file mode 100644 index 0000000000..766904eabd --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/alloy.md @@ -0,0 +1,10 @@ +--- +keywords: [Alloy, Grafana Alloy, GreptimeDB, Ingest Data] +description: Integrate GreptimeDB with Grafana Alloy. +--- + +# Grafana Alloy + +GreptimeDB can be set up as a data sink for Grafana Alloy. +For more information, please refer to the [Ingest Data through Grafana Alloy](/user-guide/ingest-data/for-observability/alloy.md) guide. + diff --git a/versioned_docs/version-1.0/user-guide/integrations/coroot.md b/versioned_docs/version-1.0/user-guide/integrations/coroot.md new file mode 100644 index 0000000000..f96cae4b02 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/coroot.md @@ -0,0 +1,42 @@ +--- +keywords: [Coroot, APM, Observability, Prometheus, integration] +description: Integrate GreptimeDB with Coroot. +--- + +# Coroot + +Coroot is an open-source APM & Observability tool, +a DataDog and NewRelic alternative. Metrics, logs, traces, continuous profiling, +and SLO-based alerting, supercharged with predefined dashboards and inspections. + +GreptimeDB can be configured as a Prometheus data sink for Coroot. +To integrate GreptimeDB with Coroot, navigate to `Settings` in the Coroot Dashboard, +select the `Prometheus` configuration, and enter the following information: + +- Prometheus URL: `http{s}:///v1/prometheus` +- If you have [enabled authentication](/user-guide/deployments-administration/authentication/static.md) on GreptimeDB, check the HTTP basic auth option and enter GreptimeDB username and password. Otherwise, leave it unchecked. +- Remote Write URL: `http{s}:///v1/prometheus/write?db=` + +## Example Configuration + +If your GreptimeDB host is `localhost` with port `4000` for the HTTP service and authentication is enabled, +and you want to use the default database `public`, +use the following configuration: + +- Prometheus URL: `http://localhost:4000/v1/prometheus` +- Enable the HTTP basic auth option and enter GreptimeDB username and password +- Remote Write URL: `http://localhost:4000/v1/prometheus/write?db=public` + +The image below shows the Coroot configuration example: + +

+ Coroot Configuration Example +

+ + +Once the configuration is saved successfully, +you can begin using Coroot to monitor your instances. +The image below shows an example of a Coroot dashboard using GreptimeDB as a data source: + +![coroot-cpu](/coroot-cpu.png) + diff --git a/versioned_docs/version-1.0/user-guide/integrations/dbeaver.md b/versioned_docs/version-1.0/user-guide/integrations/dbeaver.md new file mode 100644 index 0000000000..74724a4dc4 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/dbeaver.md @@ -0,0 +1,26 @@ +--- +keywords: [DBeaver, database tool, MySQL drivers, connection settings, verification] +description: Guide to connecting GreptimeDB to DBeaver using MySQL database drivers, including connection settings and verification steps. +--- + +# DBeaver + +[DBeaver](https://dbeaver.io/) is a free, open-source, and cross-platform database tool that supports all popular databases. It is a popular choice among developers and database administrators for its ease of use and extensive feature set. + +You can use DBeaver to connect to GreptimeDB via MySQL database drivers. +Click the "New Database Connection" button in the DBeaver toolbar to create a new connection to GreptimeDB. + +Select MySQL and click "Next" to configure the connection settings. +Install the MySQL driver if you haven't already. +Input the following connection details: + +- Connect by Host +- Host: `localhost` if GreptimeDB is running on your local machine +- Port: `4002` if you use the default GreptimeDB configuration +- Database: `public`, you can use any other database name you have created +- Enter the username and password if authentication is enabled on GreptimeDB; otherwise, leave them blank. + +Click "Test Connection" to verify the connection settings and click "Finish" to save the connection. + +For more information on interacting with GreptimeDB using MySQL, refer to the [MySQL protocol documentation](/user-guide/protocols/mysql.md). + diff --git a/versioned_docs/version-1.0/user-guide/integrations/emqx.md b/versioned_docs/version-1.0/user-guide/integrations/emqx.md new file mode 100644 index 0000000000..3dc9ab59ad --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/emqx.md @@ -0,0 +1,4 @@ +# EMQX + +GreptimeDB can be used as a data system for EMQX. +For more information, please refer to the [Ingest Data through EMQX](/user-guide/ingest-data/for-iot/emqx.md) guide. diff --git a/versioned_docs/version-1.0/user-guide/integrations/fluent-bit.md b/versioned_docs/version-1.0/user-guide/integrations/fluent-bit.md new file mode 100644 index 0000000000..1d9ab6e4ac --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/fluent-bit.md @@ -0,0 +1,9 @@ +--- +keywords: [Fluent bit, Prometheus Remote Write, OpenTelemetry, data pipeline] +description: Integrate GreptimeDB with Fluent Bit. +--- + +# Fluent Bit + +You can set GreptimeDB as a Output for Fluent Bit. +For more information, please refer to the [Writing Data with Fluent Bit](../ingest-data/for-observability/fluent-bit.md) guide. \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/integrations/grafana.md b/versioned_docs/version-1.0/user-guide/integrations/grafana.md new file mode 100644 index 0000000000..22bb607cd5 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/grafana.md @@ -0,0 +1,181 @@ +--- +keywords: [Grafana, data source, plugin, installation, connection settings, Prometheus, MySQL] +description: Steps to configure GreptimeDB as a data source in Grafana using different plugins and data sources, including installation and connection settings. +--- + +# Grafana + +GreptimeDB can be configured as a [Grafana data source](https://grafana.com/docs/grafana/latest/datasources/add-a-data-source/). +You have the option to connect GreptimeDB with Grafana using one of three data sources: [GreptimeDB](#greptimedb-data-source-plugin), [Prometheus](#prometheus-data-source), or [MySQL](#mysql-data-source). + +## GreptimeDB data source plugin + +The [GreptimeDB data source plugin (v2.0)](https://github.com/GreptimeTeam/greptimedb-grafana-datasource) is based on the ClickHouse data source and adds GreptimeDB-specific features. +The plugin adapts perfectly to the GreptimeDB data model, +thus providing a better user experience. +In addition, it also solves some compatibility issues compared to using the Prometheus data source directly. + +### Installation + +The GreptimeDB Data source plugin can currently only be installed on a local Grafana instance. +Make sure Grafana is installed and running before installing the plugin. + +You can choose one of the following installation methods: +- Download the installation package and unzip it to the relevant directory: Grab the latest release from [release +page](https://github.com/GreptimeTeam/greptimedb-grafana-datasource/releases/latest/), +Unzip the file to your [grafana plugin +directory](https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#plugins). +- Use grafana cli to download and install: + ```shell + grafana cli --pluginUrl https://github.com/GreptimeTeam/greptimedb-grafana-datasource/releases/latest/download/info8fcc-greptimedb-datasource.zip plugins install info8fcc + ``` +- Use our [prebuilt Grafana docker + image](https://hub.docker.com/r/greptime/grafana-greptimedb), which ships the + plugin by default: `docker run -p 3000:3000 + greptime/grafana-greptimedb:latest` + +Note that you may need to restart your grafana server after installing the plugin. + + + +### Connection settings + +Click the Add data source button and select GreptimeDB as the type. + +![grafana-add-greptimedb-data-source](/grafana-add-greptimedb-data-source.png) + +Fill in the following URL in the GreptimeDB server URL: + +```txt +http://:4000 +``` + +In the Auth section, click basic auth, and fill in the username and password for GreptimeDB in the Basic Auth Details section (not set by default, no need to fill in). +- User: `` +- Password: `` + +Then click the Save & Test button to test the connection. + +### General Query Settings +Before selecting any query type, you first need to configure the **Database** and **Table** to query from. + +| Setting | Description | +| :-------- | :---------------------------------------- | +| **Database** | Select the database you want to query. | +| **Table** | Select the table you want to query from. | + +![DB Table Config](/grafana/dbtable.png) + +--- + +### Table Query + +Choose the `Table` query type when your query results **do not include a time column**. This is suitable for displaying tabular data. + + +| Setting | Description | +| :-------- | :---------------------------------------------- | +| **Columns** | Select the columns you want to retrieve. Multiple selections are allowed. | +| **Filters** | Set conditions to filter your data. | + +![Table Query](/grafana/table.png) + +--- + +### Metrics Query + +Select the `Time Series` query type when your query results **include both a time column and a numerical value column**. This is ideal for visualizing metrics over time. + +| Main Setting | Description | +| :----------- | :-------------------- | +| **Time** | Select the time column. | +| **Columns** | Select the numerical value column(s). | + +![Time Series](/grafana/series1.png) + +--- + +### Logs Query + +Choose the `Logs` query type when you want to query log data. You'll need to specify a **Time** column and a **Message** column. + +| Main Setting | Description | +| :----------- | :---------------------------- | +| **Time** | Select the timestamp column for your logs. | +| **Message** | Select the column containing the log content. | +| **Log Level**| (Optional) Select the column representing the log level. | + +![Logs](/grafana/logs.png) + +#### logs Context Query +Logs Context Query +Performs an approximate time range query based on the value of context columns in a log row. + +* First, set the context column in Connection Page. +![Context Config](/grafana/context2.png) +* Then, when making a query, include the context column in the query. +![Query Config](/grafana/context1.png) +--- + +### Traces Query + +Select the `Traces` query type when you want to query distributed tracing data. + +| Main Setting | Description | +| :-------------------- | :------------------------------------------------------------------------------------------------------ | +| **Trace Model** | Select `Trace Search` to query a list of traces. | +| **Trace Id Column** | Default value: `trace_id` | +| **Span Id Column** | Default value: `span_id` | +| **Parent Span ID Column** | Default value: `parent_span_id` | +| **Service Name Column** | Default value: `service_name` | +| **Operation Name Column** | Default value: `span_name` | +| **Start Time Column** | Default value: `timestamp` | +| **Duration Time Column** | Default value: `duration_nano` | +| **Duration Unit** | Default value: `nano_seconds` | +| **Tags Column** | Multiple selections allowed. Corresponds to columns starting with `span_attributes` (e.g., `span_attributes.http.method`). | +| **Service Tags Column** | Multiple selections allowed. Corresponds to columns starting with `resource_attributes` (e.g., `resource_attributes.host.name`). | + +![Traces](/grafana/traceconfig.png) + + +## Prometheus data source + +Click the "Add data source" button and select Prometheus as the type. + +Fill in Prometheus server URL in HTTP: + +```txt +http://:4000/v1/prometheus +``` + +Click basic auth in the Auth section and fill in your GreptimeDB username and password in Basic Auth Details: + +- User: `` +- Password: `` + +Click Custom HTTP Headers and add one header: + +- Header: `x-greptime-db-name` +- Value: `` + +Then click "Save & Test" button to test the connection. + +For how to query data with PromQL, please refer to the [Prometheus Query Language](/user-guide/query-data/promql.md) document. + +## MySQL data source + +Click the "Add data source" button and select MySQL as the type. Fill in the following information in MySQL Connection: + +- Host: `:4002` +- Database: `` +- User: `` +- Password: `` +- Session timezone: `UTC` + +Then click "Save & Test" button to test the connection. + +Note that you need to use raw SQL editor for panel creation. SQL Builder is not +supported due to timestamp data type difference between GreptimeDB and vanilla +MySQL. + +For how to query data with SQL, please refer to the [Query Data with SQL](/user-guide/query-data/sql.md) document. diff --git a/versioned_docs/version-1.0/user-guide/integrations/kafka.md b/versioned_docs/version-1.0/user-guide/integrations/kafka.md new file mode 100644 index 0000000000..a7c4f151a6 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/kafka.md @@ -0,0 +1,10 @@ +--- +keywords: [Kafka, data ingestion, observability, metrics, logs] +description: Learn how to ingest observability data from Kafka into GreptimeDB using Vector. +--- + +# Kafka + +Vector can be used as a tool to transport data from Kafka to GreptimeDB. +For more information, please refer to the [Ingest Data via Kafka](/user-guide/ingest-data/for-observability/kafka.md) guide. + diff --git a/versioned_docs/version-1.0/user-guide/integrations/mcp.md b/versioned_docs/version-1.0/user-guide/integrations/mcp.md new file mode 100644 index 0000000000..dbc914d12d --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/mcp.md @@ -0,0 +1,69 @@ +--- +keywords: [MCP, Model Context Protocol, AI assistant, Claude, database integration] +description: Learn how to integrate GreptimeDB with Model Context Protocol (MCP) for AI assistants to explore and analyze your time-series data. +--- + +# Model Context Protocol (MCP) + +:::warning Experimental Feature +The GreptimeDB MCP Server is currently in experimental stage and under active development. APIs and features may change without notice. Please use with caution in production environments. +::: + +The [GreptimeDB MCP Server](https://github.com/GreptimeTeam/greptimedb-mcp-server) provides a Model Context Protocol implementation that enables AI assistants like Claude to securely explore and analyze your GreptimeDB databases. + +Watch our [demo video on YouTube](https://www.youtube.com/watch?v=EBTc46yamFI) to see the MCP Server in action and get a better understanding of its capabilities. + +## What is MCP? + +Model Context Protocol (MCP) is a standard protocol that allows AI assistants to interact with external data sources and tools. With the GreptimeDB MCP Server, you can enable AI assistants to: + +- List and explore database tables +- Read table data and schemas +- Execute SQL queries +- Analyze time-series data through natural language + +## Installation + +Install the GreptimeDB MCP Server using pip: + +```bash +pip install greptimedb-mcp-server +``` + +## Configuration + +The MCP server can be configured through environment variables or command-line arguments. Key configuration options include: + +- Database connection settings (host, port, username, password) +- Database name +- Timezone settings + +### Example: Claude Desktop Integration + +To integrate with Claude Desktop, add the following configuration to your `claude_desktop_config.json`: + +```json +{ + "mcpServers": { + "greptimedb": { + "command": "python", + "args": ["-m", "greptimedb_mcp_server"], + "env": { + "GREPTIMEDB_HOST": "localhost", + "GREPTIMEDB_PORT": "4002", + "GREPTIMEDB_USERNAME": "your_username", + "GREPTIMEDB_PASSWORD": "your_password", + "GREPTIMEDB_DATABASE": "your_database" + } + } + } +} +``` + +## Learn More + +For detailed configuration options, advanced usage, and troubleshooting, refer to the [GreptimeDB MCP Server documentation](https://github.com/GreptimeTeam/greptimedb-mcp-server). + +:::note +The GreptimeDB MCP Server is an experimental project still under development. Exercise caution when using it with sensitive data. +::: \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/integrations/metabase.md b/versioned_docs/version-1.0/user-guide/integrations/metabase.md new file mode 100644 index 0000000000..2f04ccf6d3 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/metabase.md @@ -0,0 +1,33 @@ +--- +keywords: [Metabase, BI tool, data source, driver plugin, connection settings] +description: Instructions for configuring GreptimeDB as a data source in Metabase, including installation of the driver plugin and connection settings. +--- + +# Metabase + +[Metabase](https://github.com/metabase/metabase) is an open source BI tool that +written in Clojure. You can configure GreptimeDB as a metabase data source from +a community driver plugin. + +## Installation + +Download the driver plugin file `greptimedb.metabase-driver.jar` from its +[release +page](https://github.com/greptimeteam/greptimedb-metabase-driver/releases/latest/). Copy +the jar file to `plugins/` of metabase's working directory. It will be +discovered by Metabase automatically. + +## Add GreptimeDB as database + +To add GreptimeDB database, select *Settings* / *Admin Settings* / *Databases*, +click *Add Database* button and select GreptimeDB from *Database type*. + +You will be asked to provide host, port, database name and authentication +information. + +- Use Greptime's Postgres protocol port `4003` as port. If you changed the + defaults, use you own settings. +- Username and password are optional if you didn't enable + [authentication](/user-guide/deployments-administration/authentication/overview.md). +- Use `public` as default *Database name*. When using GreptimeCloud instance, + use the database name from your instance. diff --git a/versioned_docs/version-1.0/user-guide/integrations/mindsdb.md b/versioned_docs/version-1.0/user-guide/integrations/mindsdb.md new file mode 100644 index 0000000000..16f3308f3b --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/mindsdb.md @@ -0,0 +1,35 @@ +--- +keywords: [MindsDB, machine learning, data source, configuration, SQL] +description: Guide on configuring GreptimeCloud as a data source in MindsDB for machine learning capabilities. +--- + +# MindsDB + +[MindsDB](https://mindsdb.com/) is an open-source machine learning platform that +enables developers to easily incorporate advanced machine learning capabilities +with existing databases. + +Your GreptimeDB instance work out of box as using GreptimeDB extension with +MindsDB. You can configure GreptimeDB as a data source in MindsDB using MySQL protocol: + +```sql +CREATE DATABASE greptime_datasource +WITH ENGINE = 'greptimedb', +PARAMETERS = { + "host": "", + "port": 4002, + "database": "", + "user": "", + "password": "", + "ssl": True +}; + +``` + +- `` is the hostname or IP address of your GreptimeDB instance. +- `` is the name of the database you want to connect to. +- `` and `` are your [GreptimeDB credentials](/user-guide/deployments-administration/authentication/static.md). + +MindsDB is a great gateway for many machine learning features, including +time-series forecasting, for your time series data stored in our instance. See +[MindsDB docs](https://docs.mindsdb.com/what-is-mindsdb) for more information. diff --git a/versioned_docs/version-1.0/user-guide/integrations/overview.md b/versioned_docs/version-1.0/user-guide/integrations/overview.md new file mode 100644 index 0000000000..1959e1a93a --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/overview.md @@ -0,0 +1,14 @@ +--- +keywords: [data ingestion, querying, visualization, Prometheus, Vector, Grafana, Superset, Metabase, EMQX] +description: Provides an overview of integrating GreptimeDB with popular tools for data ingestion, querying, and visualization, including Prometheus, Vector, Grafana, Superset, Metabase, and EMQX. +--- + +# Integrations + +GreptimeDB can be seamlessly integrated with popular tools for data ingestion, querying, and visualization. +The subsequent sections offer comprehensive guidance on integrating GreptimeDB with the following tools: + +import DocCardList from '@theme/DocCardList'; + + + diff --git a/versioned_docs/version-1.0/user-guide/integrations/prometheus.md b/versioned_docs/version-1.0/user-guide/integrations/prometheus.md new file mode 100644 index 0000000000..1b916527a5 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/prometheus.md @@ -0,0 +1,18 @@ +--- +keywords: [Prometheus, remote storage, remote write, PromQL, query metrics] +description: Describes how to use GreptimeDB as a remote storage backend for Prometheus and how to query metrics using Prometheus Query Language (PromQL). +--- + +# Prometheus + +## Remote Write + +GreptimeDB can be used as a remote storage backend for Prometheus. +For detailed information, +please refer to the [Ingest Data with Prometheus Remote Write](/user-guide/ingest-data/for-observability/prometheus.md) document. + +## Prometheus Query Language (PromQL) + +GreptimeDB supports the Prometheus Query Language (PromQL) for querying metrics. +For more information, +please refer to the [Query Data with Prometheus Query Language](/user-guide/query-data/promql.md) document. diff --git a/versioned_docs/version-1.0/user-guide/integrations/streamlit.md b/versioned_docs/version-1.0/user-guide/integrations/streamlit.md new file mode 100644 index 0000000000..38fd231492 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/streamlit.md @@ -0,0 +1,33 @@ +--- +keywords: [Streamlit, data apps, SQL connection, MySQL protocol, Python] +description: Instructions for using GreptimeCloud with Streamlit to build data apps, including creating a SQL connection and running SQL queries. +--- + +# Streamlit + +[Streamlit](https://streamlit.io/) is a faster way to build and share data apps. +It's possible to build streamlit based data apps based on GreptimeDB. + +To use GreptimeDB data in your application, you will need to create a SQL +connection. Thanks to GreptimeDB's [MySQL protocol compatibility](/user-guide/protocols/mysql.md), +you can treat GreptimeDB as MySQL when connecting to it. + +Here is an example code snippet to connect to GreptimeDB from Streamlit: + +```python +import streamlit as st + +st.title('GreptimeDB Streamlit Demo') +conn = st.connection("greptimedb", type="sql", url="mysql://:@:4002/") + +df = conn.query("SELECT * FROM ...") +``` + +- The `` is the hostname or IP address of your GreptimeDB instance. +- The `` is the name of the database you want to connect to. +- The `` and `` are your [GreptimeDB credentials](/user-guide/deployments-administration/authentication/static.md). + +Once you have created the connection, you can run SQL query against your +GreptimeDB instance. The resultset is automatically converted to Pandas +dataframe just like normal data source in streamlit. + diff --git a/versioned_docs/version-1.0/user-guide/integrations/superset.md b/versioned_docs/version-1.0/user-guide/integrations/superset.md new file mode 100644 index 0000000000..86fcda3c10 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/superset.md @@ -0,0 +1,58 @@ +--- +keywords: [Apache Superset, BI tool, database configuration, installation steps, connection settings] +description: Guide to configuring GreptimeDB as a database in Apache Superset, including installation steps and connection settings. +--- + +# Superset + +[Apache Superset](https://superset.apache.org) is an open source BI tool that +written in Python. To configure GreptimeDB as a database in Superset, you can +follow this guide. + +## Installation + +### Running Superset with Docker Compose + +[Docker compose](https://superset.apache.org/docs/installation/docker-compose) +is the recommended way to run Superset. To add GreptimeDB extension, create a +`requirements-local.txt` file in `docker/` of Superset codebase. + +Add GreptimeDB dependency in `requirements-local.txt`: + +```txt +greptimedb-sqlalchemy +``` + +Start Superset services: + +```bash +docker compose -f docker-compose-non-dev.yml up +``` + +### Running Superset Locally + +If you are [running Superset from +pypi](https://superset.apache.org/docs/installation/pypi), install our extension +to the same environment. + +```bash +pip install greptimedb-sqlalchemy +``` + +## Add GreptimeDB as database + +To add GreptimeDB database, select *Settings* / *Database Connections*. + +Add database and select *GreptimeDB* from list of supported databases. + +Follow the SQLAlchemy URI pattern to provide your connection information: + +``` +greptimedb://:@:/ +``` + +- Ignore `:@` if you don't have + [authentication](/user-guide/deployments-administration/authentication/overview.md) enabled. +- Use `4003` for default port (this extension uses Postgres protocol). +- Use `public` as default `database`. When using GreptimeCloud instance, use the + database name from your instance. diff --git a/versioned_docs/version-1.0/user-guide/integrations/telegraf.md b/versioned_docs/version-1.0/user-guide/integrations/telegraf.md new file mode 100644 index 0000000000..ba98928e9e --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/telegraf.md @@ -0,0 +1,9 @@ +--- +keywords: [Telegraf, Telegraf integration, InfluxDB Line Protocol] +description: Guide on using Telegraf to send data to GreptimeDB +--- + +# Telegraf + +For instructions on how to write data to GreptimeDB using Telegraf, please refer to the [Telegraf section](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md#telegraf) in the InfluxDB Line Protocol documentation. + diff --git a/versioned_docs/version-1.0/user-guide/integrations/vector.md b/versioned_docs/version-1.0/user-guide/integrations/vector.md new file mode 100644 index 0000000000..685e73b7db --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/integrations/vector.md @@ -0,0 +1,8 @@ +--- +keywords: [Vector, Vector sink] +description: Guide on using Vector to sink data to GreptimeDB. +--- + +# Vector + +Please refer to the [Ingest Data with Vector](/user-guide/ingest-data/for-observability/vector.md) document for instructions on how to sink data to GreptimeDB using Vector. diff --git a/versioned_docs/version-1.0/user-guide/logs/fulltext-search.md b/versioned_docs/version-1.0/user-guide/logs/fulltext-search.md new file mode 100644 index 0000000000..466392abd1 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/logs/fulltext-search.md @@ -0,0 +1,165 @@ +--- +keywords: [query logs, pattern matching, matches_term, query statements, log analysis] +description: Provides a guide on using GreptimeDB's query language for effective searching and analysis of log data, including pattern matching and query statements. +--- + +# Full-Text Search + +This document provides a guide on how to use GreptimeDB's query language for effective searching and analysis of log data. + +GreptimeDB allows for flexible querying of data using SQL statements. This section introduces specific search functions and query statements designed to enhance your log querying capabilities. + +## Pattern Matching Using the `matches_term` Function + +In SQL statements, you can use the `matches_term` function to perform exact term/phrase matching, which is especially useful for log analysis. The `matches_term` function supports pattern matching on `String` type columns. You can also use the `@@` operator as a shorthand for `matches_term`. Here's an example of how it can be used: + +```sql +-- Using matches_term function +SELECT * FROM logs WHERE matches_term(message, 'error') OR matches_term(message, 'fail'); + +-- Using @@ operator (shorthand for matches_term) +SELECT * FROM logs WHERE message @@ 'error' OR message @@ 'fail'; +``` + +The `matches_term` function is designed for exact term/phrase matching and uses the following syntax: + +- `text`: The text column to search, which should contain textual data of type `String`. +- `term`: The search term or phrase to match exactly, following these rules: + - Case-sensitive matching + - Matches must have non-alphanumeric boundaries (start/end of text or any non-alphanumeric character) + - Supports whole-word matching and phrase matching + +## Query Statements + +### Simple Term Matching + +The `matches_term` function performs exact word matching, which means it will only match complete words that are properly bounded by non-alphanumeric characters or the start/end of the text. This is particularly useful for finding specific error messages, status codes, version numbers, or paths in logs. + +Error messages: +```sql +-- Using matches_term function +SELECT * FROM logs WHERE matches_term(message, 'error'); + +-- Using @@ operator +SELECT * FROM logs WHERE message @@ 'error'; +``` + +Examples of matches and non-matches: +- ✅ "An error occurred!" - matches because "error" is a complete word +- ✅ "Critical error: system failure" - matches because "error" is bounded by space and colon +- ✅ "error-prone" - matches because "error" is bounded by hyphen +- ❌ "errors" - no match because "error" is part of a larger word +- ❌ "error123" - no match because "error" is followed by numbers +- ❌ "errorLogs" - no match because "error" is part of a camelCase word + +File paths and commands: +```sql +-- Find specific command with path +SELECT * FROM logs WHERE matches_term(message, '/start'); +``` + +Examples of matches and non-matches for '/start': +- ✅ "GET /app/start" - matches because "/start" is a complete term +- ✅ "Command: /start-process" - matches because "/start" is bounded by hyphen +- ✅ "Command: /start" - matches because "/start" is at the end of the message +- ❌ "start" - no match because it's missing the leading slash +- ❌ "start/stop" - no match because "/start" is not a complete term + +### Multiple Term Searches + +You can combine multiple `matches_term` conditions using the `OR` operator to search for logs containing any of several terms. This is useful when you want to find logs that might contain different variations of an error or different types of issues. + +```sql +-- Using matches_term function +SELECT * FROM logs WHERE matches_term(message, 'critical') OR matches_term(message, 'error'); + +-- Using @@ operator +SELECT * FROM logs WHERE message @@ 'critical' OR message @@ 'error'; +``` + +This query will find logs containing either "critical" or "error" as complete words. Each term is matched independently, and the results include logs that match either condition. + +Examples of matches and non-matches: +- ✅ "critical error: system failure" - matches both terms +- ✅ "An error occurred!" - matches "error" +- ✅ "critical failure detected" - matches "critical" +- ❌ "errors" - no match because "error" is part of a larger word +- ❌ "critical_errors" - no match because terms are part of larger words + +### Exclusion Searches + +You can use the `NOT` operator with `matches_term` to exclude certain terms from your search results. This is useful when you want to find logs containing one term but not another. + +```sql +-- Using matches_term function +SELECT * FROM logs WHERE matches_term(message, 'error') AND NOT matches_term(message, 'critical'); + +-- Using @@ operator +SELECT * FROM logs WHERE message @@ 'error' AND NOT message @@ 'critical'; +``` + +This query will find logs containing the word "error" but not containing the word "critical". This is particularly useful for filtering out certain types of errors or focusing on specific error categories. + +Examples of matches and non-matches: +- ✅ "An error occurred!" - matches because it contains "error" but not "critical" +- ❌ "critical error: system failure" - no match because it contains both terms +- ❌ "critical failure detected" - no match because it contains "critical" + +### Required Term Searches + +You can use the `AND` operator to require that multiple terms be present in the log message. This is useful for finding logs that contain specific combinations of terms. + +```sql +-- Using matches_term function +SELECT * FROM logs WHERE matches_term(message, 'critical') AND matches_term(message, 'error'); + +-- Using @@ operator +SELECT * FROM logs WHERE message @@ 'critical' AND message @@ 'error'; +``` + +This query will find logs containing both "critical" and "error" as complete words. Both conditions must be satisfied for a log to be included in the results. + +Examples of matches and non-matches: +- ✅ "critical error: system failure" - matches because it contains both terms +- ❌ "An error occurred!" - no match because it only contains "error" +- ❌ "critical failure detected" - no match because it only contains "critical" + +### Phrase Matching + +The `matches_term` function can also match exact phrases, including those with spaces. This is useful for finding specific error messages or status updates that contain multiple words. + +```sql +-- Using matches_term function +SELECT * FROM logs WHERE matches_term(message, 'system failure'); + +-- Using @@ operator +SELECT * FROM logs WHERE message @@ 'system failure'; +``` + +This query will find logs containing the exact phrase "system failure" with proper boundaries. The entire phrase must match exactly, including the space between words. + +Examples of matches and non-matches: +- ✅ "Alert: system failure detected" - matches because the phrase is properly bounded +- ✅ "system failure!" - matches because the phrase is properly bounded +- ❌ "system-failure" - no match because the words are separated by a hyphen instead of a space +- ❌ "system failure2023" - no match because the phrase is followed by numbers + +### Case-Insensitive Matching + +While `matches_term` is case-sensitive by default, you can achieve case-insensitive matching by converting the text to lowercase before matching. + +```sql +-- Using matches_term function +SELECT * FROM logs WHERE matches_term(lower(message), 'warning'); + +-- Using @@ operator +SELECT * FROM logs WHERE lower(message) @@ 'warning'; +``` + +This query will find logs containing the word "warning" regardless of its case. The `lower()` function converts the entire message to lowercase before matching. + +Examples of matches and non-matches: +- ✅ "Warning: high temperature" - matches after case conversion +- ✅ "WARNING: system overload" - matches after case conversion +- ❌ "warned" - no match because it's a different word +- ❌ "warnings" - no match because it's a different word diff --git a/versioned_docs/version-1.0/user-guide/logs/manage-pipelines.md b/versioned_docs/version-1.0/user-guide/logs/manage-pipelines.md new file mode 100644 index 0000000000..b870c5e40e --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/logs/manage-pipelines.md @@ -0,0 +1,455 @@ +--- +keywords: [manage pipelines, create pipeline, delete pipeline, built-in pipelines, pipeline debugging] +description: Guides on creating, deleting, and managing pipelines in GreptimeDB for parsing and transforming log data, including built-in pipelines and debugging. +--- + +# Manage Pipelines + +In GreptimeDB, each `pipeline` is a collection of data processing units used for parsing and transforming the ingested log content. This document provides guidance on creating and deleting pipelines to efficiently manage the processing flow of log data. + +For specific pipeline configurations, please refer to the [Pipeline Configuration](/reference/pipeline/pipeline-config.md) documentation. + +## Authentication + +The HTTP API for managing pipelines requires authentication. +For more information, see the [Authentication](/user-guide/protocols/http.md#authentication) documentation. + +## Upload a Pipeline + +GreptimeDB provides a dedicated HTTP interface for creating pipelines. +Assuming you have prepared a pipeline configuration file `pipeline.yaml`, use the following command to upload the configuration file, where `test` is the name you specify for the pipeline: + +```shell +## Upload the pipeline file. 'test' is the name of the pipeline +curl -X "POST" "http://localhost:4000/v1/pipelines/test" \ + -H "Authorization: Basic {{authentication}}" \ + -F "file=@pipeline.yaml" +``` + +The created Pipeline is shared for all databases. + +## Pipeline Versions + +You can upload multiple versions of a pipeline with the same name. +Each time you upload a pipeline with an existing name, a new version is created automatically. +You can specify which version to use when [ingesting logs](/reference/pipeline/write-log-api.md#http-api), [querying](#query-pipelines), or [deleting](#delete-a-pipeline) a pipeline. +The last uploaded version is used by default if no version is specified. + +After successfully uploading a pipeline, the response will include version information: + +```json +{"name":"nginx_pipeline","version":"2024-06-27 12:02:34.257312110Z"} +``` + +The version is a timestamp in UTC format that indicates when the pipeline was created. +This timestamp serves as a unique identifier for each pipeline version. + + +## Delete a Pipeline + +You can use the following HTTP interface to delete a pipeline: + +```shell +## 'test' is the name of the pipeline +curl -X "DELETE" "http://localhost:4000/v1/pipelines/test?version=2024-06-27%2012%3A02%3A34.257312110Z" \ + -H "Authorization: Basic {{authentication}}" +``` + +In the above example, we deleted a pipeline named `test`. The `version` parameter is required to specify the version of the pipeline to be deleted. + +## Query Pipelines + +Querying a pipeline with a name through HTTP interface as follow: + +```shell +## 'test' is the name of the pipeline, it will return a pipeline with latest version if the pipeline named `test` exists. +curl "http://localhost:4000/v1/pipelines/test" \ + -H "Authorization: Basic {{authentication}}" +``` + +```shell +## with the version parameter, it will return the specify version pipeline. +curl "http://localhost:4000/v1/pipelines/test?version=2025-04-01%2006%3A58%3A31.335251882%2B0000" \ + -H "Authorization: Basic {{authentication}}" +``` + + If the pipeline exists, the output should be: + +```json +{ + "pipelines": [ + { + "name": "test", + "version": "2025-04-01 06:58:31.335251882", + "pipeline": "version: 2\nprocessors:\n - dissect:\n fields:\n - message\n patterns:\n - '%{ip_address} - - [%{timestamp}] \"%{http_method} %{request_line}\" %{status_code} %{response_size} \"-\" \"%{user_agent}\"'\n ignore_missing: true\n - date:\n fields:\n - timestamp\n formats:\n - \"%d/%b/%Y:%H:%M:%S %z\"\n - select:\n type: exclude\n fields:\n - message\n\ntransform:\n - fields:\n - ip_address\n type: string\n index: inverted\n tag: true\n - fields:\n - status_code\n type: int32\n index: inverted\n tag: true\n - fields:\n - request_line\n - user_agent\n type: string\n index: fulltext\n - fields:\n - response_size\n type: int32\n - fields:\n - timestamp\n type: time\n index: timestamp\n" + } + ], + "execution_time_ms": 7 +} +``` + +In the output above, the `pipeline` field is a YAML-formatted string. Since the JSON format does not display YAML strings well, the `echo` command can be used to present it in a more human-readable way: + +```shell +echo -e "version: 2\nprocessors:\n - dissect:\n fields:\n - message\n patterns:\n - '%{ip_address} - - [%{timestamp}] \"%{http_method} %{request_line}\" %{status_code} %{response_size} \"-\" \"%{user_agent}\"'\n ignore_missing: true\n - date:\n fields:\n - timestamp\n formats:\n - \"%d/%b/%Y:%H:%M:%S %z\"\n - select:\n type: exclude\n fields:\n - message\n\ntransform:\n - fields:\n - ip_address\n type: string\n index: inverted\n tag: true\n - fields:\n - status_code\n type: int32\n index: inverted\n tag: true\n - fields:\n - request_line\n - user_agent\n type: string\n index: fulltext\n - fields:\n - response_size\n type: int32\n - fields:\n - timestamp\n type: time\n index: timestamp\n" +``` + +```yml +version: 2 +processors: + - dissect: + fields: + - message + patterns: + - '%{ip_address} - - [%{timestamp}] "%{http_method} %{request_line}" %{status_code} %{response_size} "-" "%{user_agent}"' + ignore_missing: true + - date: + fields: + - timestamp + formats: + - "%d/%b/%Y:%H:%M:%S %z" + - select: + type: exclude + fields: + - message + +transform: + - fields: + - ip_address + type: string + index: inverted + tag: true + - fields: + - status_code + type: int32 + index: inverted + tag: true + - fields: + - request_line + - user_agent + type: string + index: fulltext + - fields: + - response_size + type: int32 + - fields: + - timestamp + type: time + index: timestamp +``` + +Or you can use SQL to query pipeline information. + +```sql +SELECT * FROM greptime_private.pipelines; +``` + +Please note that if you are using the MySQL or PostgreSQL protocol to connect to GreptimeDB, the precision of the pipeline time information may vary, and nanosecond-level precision may be lost. + +To address this issue, you can cast the `created_at` field to a timestamp to view the pipeline's creation time. For example, the following query displays `created_at` in `bigint` format: + +```sql +SELECT name, pipeline, created_at::bigint FROM greptime_private.pipelines; +``` + +The query result is as follows: + +``` + name | pipeline | greptime_private.pipelines.created_at +------+-----------------------------------+--------------------------------------- + test | processors: +| 1719489754257312110 + | - date: +| + | field: time +| + | formats: +| + | - "%Y-%m-%d %H:%M:%S%.3f"+| + | ignore_missing: true +| + | +| + | transform: +| + | - fields: +| + | - id1 +| + | - id2 +| + | type: int32 +| + | - fields: +| + | - type +| + | - logger +| + | type: string +| + | index: inverted +| + | - fields: +| + | - log +| + | type: string +| + | index: fulltext +| + | - field: time +| + | type: time +| + | index: timestamp +| + | | +(1 row) +``` + +Then, you can use a program to convert the bigint type timestamp from the SQL result into a time string. + +```shell +timestamp_ns="1719489754257312110"; readable_timestamp=$(TZ=UTC date -d @$((${timestamp_ns:0:10}+0)) +"%Y-%m-%d %H:%M:%S").${timestamp_ns:10}Z; echo "Readable timestamp (UTC): $readable_timestamp" +``` + +Output: + +```shell +Readable timestamp (UTC): 2024-06-27 12:02:34.257312110Z +``` + +The output `Readable timestamp (UTC)` represents the creation time of the pipeline and also serves as the version number. + +## Debug + +First, please refer to the [Quick Start example](/user-guide/logs/quick-start.md#write-logs-by-pipeline) to see the correct execution of the Pipeline. + +### Debug creating a Pipeline + +You may encounter errors when creating a Pipeline. For example, when creating a Pipeline using the following configuration: + + +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/test" \ + -H "Content-Type: application/x-yaml" \ + -H "Authorization: Basic {{authentication}}" \ + -d $'processors: + - date: + field: time + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + ignore_missing: true + - gsub: + fields: + - message + pattern: "\\\." + replacement: + - "-" + ignore_missing: true + +transform: + - fields: + - message + type: string + - field: time + type: time + index: timestamp +``` + +The pipeline configuration contains an error. The `gsub` Processor expects the `replacement` field to be a string, but the current configuration provides an array. As a result, the pipeline creation fails with the following error message: + + +```json +{"error":"Failed to parse pipeline: 'replacement' must be a string"} +``` + +Therefore, We need to modify the configuration of the `gsub` Processor and change the value of the `replacement` field to a string type. + +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/test" \ + -H "Content-Type: application/x-yaml" \ + -H "Authorization: Basic {{authentication}}" \ + -d $'processors: + - date: + field: time + formats: + - "%Y-%m-%d %H:%M:%S%.3f" + ignore_missing: true + - gsub: + fields: + - message + pattern: "\\\." + replacement: "-" + ignore_missing: true + +transform: + - fields: + - message + type: string + - field: time + type: time + index: timestamp +``` + +Now that the Pipeline has been created successfully, you can test the Pipeline using the `dryrun` interface. + +### Debug writing logs + +We can test the Pipeline using the `dryrun` interface. We will test it with erroneous log data where the value of the message field is in numeric format, causing the pipeline to fail during processing. + +**This API is only used to test the results of the Pipeline and does not write logs to GreptimeDB.** + + +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/dryrun?pipeline_name=test" \ + -H "Content-Type: application/json" \ + -H "Authorization: Basic {{authentication}}" \ + -d $'{"message": 1998.08,"time":"2024-05-25 20:16:37.217"}' + +{"error":"Failed to execute pipeline, reason: gsub processor: expect string or array string, but got Float64(1998.08)"} +``` + +The output indicates that the pipeline processing failed because the `gsub` Processor expects a string type rather than a floating-point number type. We need to adjust the format of the log data to ensure the pipeline can process it correctly. +Let's change the value of the message field to a string type and test the pipeline again. + +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/dryrun?pipeline_name=test" \ + -H "Content-Type: application/json" \ + -H "Authorization: Basic {{authentication}}" \ + -d $'{"message": "1998.08","time":"2024-05-25 20:16:37.217"}' +``` + +At this point, the Pipeline processing is successful, and the output is as follows: + +```json +{ + "rows": [ + [ + { + "data_type": "STRING", + "key": "message", + "semantic_type": "FIELD", + "value": "1998-08" + }, + { + "data_type": "TIMESTAMP_NANOSECOND", + "key": "time", + "semantic_type": "TIMESTAMP", + "value": "2024-05-25 20:16:37.217+0000" + } + ] + ], + "schema": [ + { + "column_type": "FIELD", + "data_type": "STRING", + "fulltext": false, + "name": "message" + }, + { + "column_type": "TIMESTAMP", + "data_type": "TIMESTAMP_NANOSECOND", + "fulltext": false, + "name": "time" + } + ] +} +``` + +It can be seen that the `.` in the string `1998.08` has been replaced with `-`, indicating a successful processing of the Pipeline. + +## Get Table DDL from a Pipeline Configuration + +When using pipelines, GreptimeDB automatically creates target tables upon first data ingestion by default. +However, you may want to manually create tables beforehand to add custom table options, +such as partition rules for better performance. + +While the auto-created table schema is deterministic for a given pipeline configuration, +manually writing the table DDL (Data Definition Language) according to the configuration can be tedious. +The `/ddl` API endpoint simplifies this process. + +For an existing pipeline, you can use the `/v1/pipelines/{pipeline_name}/ddl` endpoint to generate the `CREATE TABLE` SQL. +This API examines the transform definition in the pipeline configuration and infers the appropriate table schema. +You can use this API to generate the basic table DDL, fine-tune table options and manually create the table before ingesting data. Some common cases would be: +- Add [partition rules](/user-guide/deployments-administration/manage-data/table-sharding.md) +- Modify [index options](/user-guide/manage-data/data-index.md) +- Add other [table options](/reference/sql/create.md#table-options) + +Here is an example demonstrating how to use this API. Consider the following pipeline configuration: +```YAML +# pipeline.yaml +processors: +- dissect: + fields: + - message + patterns: + - '%{ip_address} - %{username} [%{timestamp}] "%{http_method} %{request_line} %{protocol}" %{status_code} %{response_size}' + ignore_missing: true +- date: + fields: + - timestamp + formats: + - "%d/%b/%Y:%H:%M:%S %z" + +transform: + - fields: + - timestamp + type: time + index: timestamp + - fields: + - ip_address + type: string + index: skipping + - fields: + - username + type: string + tag: true + - fields: + - http_method + type: string + index: inverted + - fields: + - request_line + type: string + index: fulltext + - fields: + - protocol + type: string + - fields: + - status_code + type: int32 + index: inverted + tag: true + - fields: + - response_size + type: int64 + on_failure: default + default: 0 + - fields: + - message + type: string +``` + +First, upload the pipeline to the database using the following command: +```bash +curl -X "POST" "http://localhost:4000/v1/pipelines/pp" -F "file=@pipeline.yaml" +``` +Then, query the table DDL using the following command: +```bash +curl -X "GET" "http://localhost:4000/v1/pipelines/pp/ddl?table=test_table" +``` +The API returns the following output in JSON format: +```JSON +{ + "sql": { + "sql": "CREATE TABLE IF NOT EXISTS `test_table` (\n `timestamp` TIMESTAMP(9) NOT NULL,\n `ip_address` STRING NULL SKIPPING INDEX WITH(false_positive_rate = '0.01', granularity = '10240', type = 'BLOOM'),\n `username` STRING NULL,\n `http_method` STRING NULL INVERTED INDEX,\n `request_line` STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'bloom', case_sensitive = 'false', false_positive_rate = '0.01', granularity = '10240'),\n `protocol` STRING NULL,\n `status_code` INT NULL INVERTED INDEX,\n `response_size` BIGINT NULL,\n `message` STRING NULL,\n TIME INDEX (`timestamp`),\n PRIMARY KEY (`username`, `status_code`)\n)\nENGINE=mito\nWITH(\n append_mode = 'true'\n)" + }, + "execution_time_ms": 3 +} +``` +After formatting the `sql` field in the response, you can see the inferred table schema: +```SQL +CREATE TABLE IF NOT EXISTS `test_table` ( + `timestamp` TIMESTAMP(9) NOT NULL, + `ip_address` STRING NULL SKIPPING INDEX WITH(false_positive_rate = '0.01', granularity = '10240', type = 'BLOOM'), + `username` STRING NULL, + `http_method` STRING NULL INVERTED INDEX, + `request_line` STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'bloom', case_sensitive = 'false', false_positive_rate = '0.01', granularity = '10240'), + `protocol` STRING NULL, + `status_code` INT NULL INVERTED INDEX, + `response_size` BIGINT NULL, + `message` STRING NULL, + TIME INDEX (`timestamp`), + PRIMARY KEY (`username`, `status_code`) + ) +ENGINE=mito +WITH( + append_mode = 'true' +) +``` + +You can use the inferred table DDL as a starting point. +After customizing the DDL to meet your requirements, execute it manually before ingesting data through the pipeline. + +**Notes:** +1. The API only infers the table schema from the pipeline configuration; it doesn't check if the table already exists. +2. The API doesn't account for table suffixes. If you're using `dispatcher`, `table_suffix`, or table suffix hints in your pipeline configuration, you'll need to adjust the table name manually. diff --git a/versioned_docs/version-1.0/user-guide/logs/overview.md b/versioned_docs/version-1.0/user-guide/logs/overview.md new file mode 100644 index 0000000000..9c9e2aa1e6 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/logs/overview.md @@ -0,0 +1,108 @@ +--- +keywords: [log service, quick start, pipeline configuration, manage pipelines, query logs] +description: Comprehensive guide to GreptimeDB's log management capabilities, covering log collection architecture, pipeline processing, integration with popular collectors like Vector and Kafka, and advanced querying with full-text search. +--- + +# Logs + +GreptimeDB provides a comprehensive log management solution designed for modern observability needs. +It offers seamless integration with popular log collectors, +flexible pipeline processing, +and powerful querying capabilities, including full-text search. + +Key features include: + +- **Unified Storage**: Store logs alongside metrics and traces in a single database +- **Pipeline Processing**: Transform and enrich raw logs with customizable pipelines, supporting various log collectors and formats +- **Advanced Querying**: SQL-based analysis with full-text search capabilities +- **Real-time Processing**: Process and query logs in real-time for monitoring and alerting + + +## Log Collection Flow + +![log-collection-flow](/log-collection-flow.drawio.svg) + +The diagram above illustrates the comprehensive log collection architecture, +which follows a structured four-stage process: Log Sources, Log Collectors, Pipeline Processing, and Storage in GreptimeDB. + +### Log Sources + +Log sources represent the foundational layer where log data originates within your infrastructure. +GreptimeDB supports ingestion from diverse source types to accommodate comprehensive observability requirements: + +- **Applications**: Application-level logs from microservices architectures, web applications, mobile applications, and custom software components +- **IoT Devices**: Device logs, sensor event logs, and operational status logs from Internet of Things ecosystems +- **Infrastructure**: Cloud platform logs, container orchestration logs (Kubernetes, Docker), load balancer logs, and network infrastructure component logs +- **System Components**: Operating system logs, kernel events, system daemon logs, and hardware monitoring logs +- **Custom Sources**: Any other log sources specific to your environment or applications + +### Log Collectors + +Log collectors are responsible for efficiently gathering log data from diverse sources and reliably forwarding it to the storage backend. GreptimeDB seamlessly integrates with industry-standard log collectors, +including Vector, Fluent Bit, Apache Kafka, OpenTelemetry Collector and more. + +GreptimeDB functions as a powerful sink backend for these collectors, +providing robust data ingestion capabilities. +During the ingestion process, +GreptimeDB's pipeline system enables real-time transformation and enrichment of log data, +ensuring optimal structure and quality before storage. + +### Pipeline Processing + +GreptimeDB's pipeline mechanism transforms raw logs into structured, queryable data: + +- **Parse**: Extract structured data from unstructured log messages +- **Transform**: Enrich logs with additional context and metadata +- **Index**: Configure indexes to optimize query performance and enable efficient searching, including full-text indexes, time indexes, and more + +### Storage in GreptimeDB + +After processing through the pipeline, +the logs are stored in GreptimeDB enabling flexible analysis and visualization: + +- **SQL Querying**: Use familiar SQL syntax to analyze log data +- **Time-based Analysis**: Leverage time-series capabilities for temporal analysis +- **Full-text Search**: Perform advanced text searches across log messages +- **Real-time Analytics**: Query logs in real-time for monitoring and alerting + +## Quick Start + +You can quickly get started by using the built-in `greptime_identity` pipeline for log ingestion. +For more information, please refer to the [Quick Start](./quick-start.md) guide. + +## Integrate with Log Collectors + +GreptimeDB integrates seamlessly with various log collectors to provide a comprehensive logging solution. The integration process follows these key steps: + +1. **Select Appropriate Log Collectors**: Choose collectors based on your infrastructure requirements, data sources, and performance needs +2. **Analyze Output Format**: Understand the log format and structure produced by your chosen collector +3. **Configure Pipeline**: Create and configure pipelines in GreptimeDB to parse, transform, and enrich the incoming log data +4. **Store and Query**: Efficiently store processed logs in GreptimeDB for real-time analysis and monitoring + +To successfully integrate your log collector with GreptimeDB, you'll need to: +- First understand how pipelines work in GreptimeDB +- Then configure the sink settings in your log collector to send data to GreptimeDB + +Please refer to the following guides for detailed instructions on integrating GreptimeDB with log collectors: + +- [Vector](/user-guide/ingest-data/for-observability/vector.md#using-greptimedb_logs-sink-recommended) +- [Kafka](/user-guide/ingest-data/for-observability/kafka.md#logs) +- [Fluent Bit](/user-guide/ingest-data/for-observability/fluent-bit.md#http) +- [OpenTelemetry Collector](/user-guide/ingest-data/for-observability/otel-collector.md) +- [Loki](/user-guide/ingest-data/for-observability/loki.md#using-pipeline-with-loki-push-api) + +## Learn More About Pipelines + +- [Using Custom Pipelines](./use-custom-pipelines.md): Explains how to create and use custom pipelines for log ingestion. +- [Managing Pipelines](./manage-pipelines.md): Explains how to create and delete pipelines. + +## Query Logs + +- [Full-Text Search](./fulltext-search.md): Guide on using GreptimeDB's query language for effective searching and analysis of log data. + +## Reference + +- [Built-in Pipelines](/reference/pipeline/built-in-pipelines.md): Lists and describes the details of the built-in pipelines provided by GreptimeDB for log ingestion. +- [APIs for Writing Logs](/reference/pipeline/write-log-api.md): Describes the HTTP API for writing logs to GreptimeDB. +- [Pipeline Configuration](/reference/pipeline/pipeline-config.md): Provides in-depth information on each specific configuration of pipelines in GreptimeDB. + diff --git a/versioned_docs/version-1.0/user-guide/logs/quick-start.md b/versioned_docs/version-1.0/user-guide/logs/quick-start.md new file mode 100644 index 0000000000..593d6daf13 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/logs/quick-start.md @@ -0,0 +1,123 @@ +--- +keywords: [logs, log service, pipeline, greptime_identity, quick start, json logs] +description: Quick start guide for GreptimeDB log service, including basic log ingestion using the built-in greptime_identity pipeline and integration with log collectors. +--- + +# Quick Start + +This guide will walk you through the essential steps to get started with GreptimeDB's log service. +You'll learn how to ingest logs using the built-in `greptime_identity` pipeline and integrate with log collectors. + +GreptimeDB provides a powerful pipeline-based log ingestion system. +For quick setup with JSON-formatted logs, +you can use the built-in `greptime_identity` pipeline, which: + +- Automatically handles field mapping from JSON to table columns +- Creates tables automatically if they don't exist +- Supports flexible schemas for varying log structures +- Requires minimal configuration to get started + +## Direct HTTP Ingestion + +The simplest way to ingest logs into GreptimeDB is through a direct HTTP request using the `greptime_identity` pipeline. + +For example, you can use `curl` to send a POST request with JSON log data: + +```shell +curl -X POST \ + "http://localhost:4000/v1/ingest?db=public&table=demo_logs&pipeline_name=greptime_identity" \ + -H "Content-Type: application/json" \ + -H "Authorization: Basic {{authentication}}" \ + -d '[ + { + "timestamp": "2024-01-15T10:30:00Z", + "level": "INFO", + "service": "web-server", + "message": "User login successful", + "user_id": 12345, + "ip_address": "192.168.1.100" + }, + { + "timestamp": "2024-01-15T10:31:00Z", + "level": "ERROR", + "service": "database", + "message": "Connection timeout occurred", + "error_code": 500, + "retry_count": 3 + } + ]' +``` + +The key parameters are: + +- `db=public`: Target database name (use your database name) +- `table=demo_logs`: Target table name (created automatically if it doesn't exist) +- `pipeline_name=greptime_identity`: Uses `greptime_identity` identity pipeline for JSON processing +- `Authorization` header: Basic authentication with base64-encoded `username:password`, see the [HTTP Authentication Guide](/user-guide/protocols/http.md#authentication) + +A successful request returns: +```json +{ + "output": [{"affectedrows": 2}], + "execution_time_ms": 15 +} +``` +After successful ingestion, +the corresponding table `demo_logs` is automatically created with columns based on the JSON fields. +The schema is as follows: + +```sql ++--------------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+---------------------+------+------+---------+---------------+ +| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| ip_address | String | | YES | | FIELD | +| level | String | | YES | | FIELD | +| message | String | | YES | | FIELD | +| service | String | | YES | | FIELD | +| timestamp | String | | YES | | FIELD | +| user_id | Int64 | | YES | | FIELD | +| error_code | Int64 | | YES | | FIELD | +| retry_count | Int64 | | YES | | FIELD | ++--------------------+---------------------+------+------+---------+---------------+ +``` + +## Integration with Log Collectors + +For production environments, +you'll typically use log collectors to automatically forward logs to GreptimeDB. +Here is an example about how to configure Vector to send logs to GreptimeDB using the `greptime_identity` pipeline: + +```toml +[sinks.my_sink_id] +type = "greptimedb_logs" +dbname = "public" +endpoint = "http://:4000" +pipeline_name = "greptime_identity" +table = "
" +username = "" +password = "" +# Additional configurations as needed +``` + +The key configuration parameters are: +- `type = "greptimedb_logs"`: Specifies the GreptimeDB logs sink +- `dbname`: Target database name +- `endpoint`: GreptimeDB HTTP endpoint +- `pipeline_name`: Uses `greptime_identity` pipeline for JSON processing +- `table`: Target table name (created automatically if it doesn't exist) +- `username` and `password`: Credentials for HTTP Basic Authentication + +For details about the Vector configuration and options, +refer to the [Vector Integration Guide](/user-guide/ingest-data/for-observability/vector.md#using-greptimedb_logs-sink-recommended). + + +## Next Steps + +You've successfully ingested your first logs, here are the recommended next steps: + +- **Learn more about the behaviours of built-in Pipelines**: Refer to the [Built-in Pipelines](/reference/pipeline/built-in-pipelines.md) guide for detailed information on available built-in pipelines and their configurations. +- **Integrate with Popular Log Collectors**: For detailed instructions on integrating GreptimeDB with various log collectors like Fluent Bit, Fluentd, and others, refer to the [Integrate with Popular Log Collectors](./overview.md#integrate-with-log-collectors) section in the [Logs Overview](./overview.md) guide. +- **Using Custom Pipelines**: To learn more about creating custom pipelines for advanced log processing and transformation, refer to the [Using Custom Pipelines](./use-custom-pipelines.md) guide. + + diff --git a/versioned_docs/version-1.0/user-guide/logs/use-custom-pipelines.md b/versioned_docs/version-1.0/user-guide/logs/use-custom-pipelines.md new file mode 100644 index 0000000000..9519348231 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/logs/use-custom-pipelines.md @@ -0,0 +1,317 @@ +--- +keywords: [quick start, write logs, query logs, pipeline, structured data, log ingestion, log collection, log management tools] +description: A comprehensive guide to quickly writing and querying logs in GreptimeDB, including direct log writing and using pipelines for structured data. +--- + +# Using Custom Pipelines + +GreptimeDB automatically parses and transforms logs into structured, +multi-column data based on your pipeline configuration. +When built-in pipelines cannot handle your specific log format, +you can create custom pipelines to define exactly how your log data should be parsed and transformed. + +## Identify Your Original Log Format + +Before creating a custom pipeline, it's essential to understand the format of original log data. +If you're using log collectors and aren't sure about the log format, +there are two ways to examine your logs: + +1. **Read the collector official documentation**: Configure your collector to output data to console or file to inspect the log format. +2. **Use the `greptime_identity` pipeline**: Ingest sample logs directly into GreptimeDB using the built-in `greptime_identity` pipeline. + The `greptime_identity` pipeline treats the entire text log as a single `message` field, + which makes it very convenient to see the raw log content directly. + +Once understand the log format you want to process, +you can create a custom pipeline. +This document uses the following Nginx access log entry as an example: + +```txt +127.0.0.1 - - [25/May/2024:20:16:37 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" +``` + +## Create a Custom Pipeline + +GreptimeDB provides an HTTP interface for creating pipelines. +Here's how to create one. + +First, create an example pipeline configuration file to process Nginx access logs, +naming it `pipeline.yaml`: + +```yaml +version: 2 +processors: + - dissect: + fields: + - message + patterns: + - '%{ip_address} - - [%{timestamp}] "%{http_method} %{request_line}" %{status_code} %{response_size} "-" "%{user_agent}"' + ignore_missing: true + - date: + fields: + - timestamp + formats: + - "%d/%b/%Y:%H:%M:%S %z" + - select: + type: exclude + fields: + - message + - vrl: + source: | + .greptime_table_ttl = "7d" + . + +transform: + - fields: + - ip_address + type: string + index: inverted + tag: true + - fields: + - status_code + type: int32 + index: inverted + tag: true + - fields: + - request_line + - user_agent + type: string + index: fulltext + - fields: + - response_size + type: int32 + - fields: + - timestamp + type: time + index: timestamp +``` + +The pipeline configuration above uses the [version 2](/reference/pipeline/pipeline-config.md#transform-in-version-2) format, +contains `processors` and `transform` sections that work together to structure your log data: + +**Processors**: Used to preprocess log data before transformation: +- **Data Extraction**: The `dissect` processor uses pattern matching to parse the `message` field and extract structured data including `ip_address`, `timestamp`, `http_method`, `request_line`, `status_code`, `response_size`, and `user_agent`. +- **Timestamp Processing**: The `date` processor parses the extracted `timestamp` field using the format `%d/%b/%Y:%H:%M:%S %z` and converts it to a proper timestamp data type. +- **Field Selection**: The `select` processor excludes the original `message` field from the final output while retaining all other fields. +- **Table Options**: The `vrl` processor sets the table options based on the extracted fields, such as adding a suffix to the table name and setting the TTL. The `greptime_table_ttl = "7d"` line configures the table data to have a time-to-live of 7 days. + +**Transform**: Defines how to convert and index the extracted fields: +- **Field Transformation**: Each extracted field is converted to its appropriate data type with specific indexing configurations. Fields like `http_method` retain their default data types when no explicit configuration is provided. +- **Indexing Strategy**: + - `ip_address` and `status_code` use inverted indexing as tags for fast filtering + - `request_line` and `user_agent` use full-text indexing for optimal text search capabilities + - `timestamp` serves as the required time index column + +For detailed information about pipeline configuration options, +please refer to the [Pipeline Configuration](/reference/pipeline/pipeline-config.md) documentation. + +## Upload the Pipeline + +Execute the following command to upload the pipeline configuration: + +```shell +curl -X "POST" \ + "http://localhost:4000/v1/pipelines/nginx_pipeline" \ + -H 'Authorization: Basic {{authentication}}' \ + -F "file=@pipeline.yaml" +``` + +After successful execution, a pipeline named `nginx_pipeline` will be created and return the following result: + +```json +{"name":"nginx_pipeline","version":"2024-06-27 12:02:34.257312110Z"}. +``` + +You can create multiple versions for the same pipeline name. +All pipelines are stored in the `greptime_private.pipelines` table. +Refer to [Query Pipelines](manage-pipelines.md#query-pipelines) to view pipeline data. + +## Ingest Logs Using the Pipeline + +The following example writes logs to the `custom_pipeline_logs` table using the `nginx_pipeline` pipeline to format and transform the log messages: + +```shell +curl -X POST \ + "http://localhost:4000/v1/ingest?db=public&table=custom_pipeline_logs&pipeline_name=nginx_pipeline" \ + -H "Content-Type: application/json" \ + -H "Authorization: Basic {{authentication}}" \ + -d '[ + { + "message": "127.0.0.1 - - [25/May/2024:20:16:37 +0000] \"GET /index.html HTTP/1.1\" 200 612 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\"" + }, + { + "message": "192.168.1.1 - - [25/May/2024:20:17:37 +0000] \"POST /api/login HTTP/1.1\" 200 1784 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36\"" + }, + { + "message": "10.0.0.1 - - [25/May/2024:20:18:37 +0000] \"GET /images/logo.png HTTP/1.1\" 304 0 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0\"" + }, + { + "message": "172.16.0.1 - - [25/May/2024:20:19:37 +0000] \"GET /contact HTTP/1.1\" 404 162 \"-\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1\"" + } + ]' +``` + +The command will return the following output upon success: + +```json +{"output":[{"affectedrows":4}],"execution_time_ms":79} +``` + +The `custom_pipeline_logs` table content is automatically created based on the pipeline configuration: + +```sql ++-------------+-------------+-------------+---------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+ +| ip_address | http_method | status_code | request_line | user_agent | response_size | timestamp | ++-------------+-------------+-------------+---------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+ +| 10.0.0.1 | GET | 304 | /images/logo.png HTTP/1.1 | Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0 | 0 | 2024-05-25 20:18:37 | +| 127.0.0.1 | GET | 200 | /index.html HTTP/1.1 | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 | 612 | 2024-05-25 20:16:37 | +| 172.16.0.1 | GET | 404 | /contact HTTP/1.1 | Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1 | 162 | 2024-05-25 20:19:37 | +| 192.168.1.1 | POST | 200 | /api/login HTTP/1.1 | Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 | 1784 | 2024-05-25 20:17:37 | ++-------------+-------------+-------------+---------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+ +``` +For more detailed information about the log ingestion API endpoint `/ingest`, +including additional parameters and configuration options, +please refer to the [APIs for Writing Logs](/reference/pipeline/write-log-api.md) documentation. + +## Query Logs + +We use the `custom_pipeline_logs` table as an example to query logs. + +### Query logs by tags + +With the multiple tag columns in `custom_pipeline_logs`, +you can query data by tags flexibly. +For example, query the logs with `status_code` 200 and `http_method` GET. + +```sql +SELECT * FROM custom_pipeline_logs WHERE status_code = 200 AND http_method = 'GET'; +``` + +```sql ++------------+-------------+----------------------+---------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +| ip_address | status_code | request_line | user_agent | response_size | timestamp | http_method | ++------------+-------------+----------------------+---------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +| 127.0.0.1 | 200 | /index.html HTTP/1.1 | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 | 612 | 2024-05-25 20:16:37 | GET | ++------------+-------------+----------------------+---------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +1 row in set (0.02 sec) +``` + +### Full‑Text Search + +For the text fields `request_line` and `user_agent`, you can use `matches_term` function to search logs. +Remember, we created the full-text index for these two columns when [creating a pipeline](#create-a-pipeline). +This allows for high-performance full-text searches. + +For example, query the logs with `request_line` containing `/index.html` or `/api/login`. + +```sql +SELECT * FROM custom_pipeline_logs WHERE matches_term(request_line, '/index.html') OR matches_term(request_line, '/api/login'); +``` + +```sql ++-------------+-------------+----------------------+--------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +| ip_address | status_code | request_line | user_agent | response_size | timestamp | http_method | ++-------------+-------------+----------------------+--------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +| 127.0.0.1 | 200 | /index.html HTTP/1.1 | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 | 612 | 2024-05-25 20:16:37 | GET | +| 192.168.1.1 | 200 | /api/login HTTP/1.1 | Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 | 1784 | 2024-05-25 20:17:37 | POST | ++-------------+-------------+----------------------+--------------------------------------------------------------------------------------------------------------------------+---------------+---------------------+-------------+ +2 rows in set (0.00 sec) +``` + +You can refer to the [Full-Text Search](fulltext-search.md) document for detailed usage of the `matches_term` function. + + +## Benefits of Using Pipelines + +Using pipelines to process logs provides structured data and automatic field extraction, +enabling more efficient querying and analysis. + +You can also write logs directly to the database without pipelines, +but this approach limits high-performance analysis capabilities. + +### Direct Log Insertion (Without Pipeline) + +For comparison, you can create a table to store original log messages: + +```sql +CREATE TABLE `origin_logs` ( + `message` STRING FULLTEXT INDEX, + `time` TIMESTAMP TIME INDEX +) WITH ( + append_mode = 'true' +); +``` + +Use the `INSERT` statement to insert logs into the table. +Note that you need to manually add a timestamp field for each log: + +```sql +INSERT INTO origin_logs (message, time) VALUES +('127.0.0.1 - - [25/May/2024:20:16:37 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"', '2024-05-25 20:16:37.217'), +('192.168.1.1 - - [25/May/2024:20:17:37 +0000] "POST /api/login HTTP/1.1" 200 1784 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36"', '2024-05-25 20:17:37.217'), +('10.0.0.1 - - [25/May/2024:20:18:37 +0000] "GET /images/logo.png HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0"', '2024-05-25 20:18:37.217'), +('172.16.0.1 - - [25/May/2024:20:19:37 +0000] "GET /contact HTTP/1.1" 404 162 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1"', '2024-05-25 20:19:37.217'); +``` + +### Schema Comparison: Pipeline vs Raw + +In the above examples, the table `custom_pipeline_logs` is automatically created by writing logs using pipeline, +and the table `origin_logs` is created by writing logs directly. +Let's explore the differences between these two tables. + +```sql +DESC custom_pipeline_logs; +``` + +```sql ++---------------+---------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++---------------+---------------------+------+------+---------+---------------+ +| ip_address | String | PRI | YES | | TAG | +| status_code | Int32 | PRI | YES | | TAG | +| request_line | String | | YES | | FIELD | +| user_agent | String | | YES | | FIELD | +| response_size | Int32 | | YES | | FIELD | +| timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP | +| http_method | String | | YES | | FIELD | ++---------------+---------------------+------+------+---------+---------------+ +7 rows in set (0.00 sec) +``` + +```sql +DESC origin_logs; +``` + +```sql ++---------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++---------+----------------------+------+------+---------+---------------+ +| message | String | | YES | | FIELD | +| time | TimestampMillisecond | PRI | NO | | TIMESTAMP | ++---------+----------------------+------+------+---------+---------------+ +``` + +Comparing the table structures shows the key differences: + +The `custom_pipeline_logs` table (created with pipeline) automatically structures log data into multiple columns: +- `ip_address`, `status_code` as indexed tags for fast filtering +- `request_line`, `user_agent` with full-text indexing for text search +- `response_size`, `http_method` as regular fields +- `timestamp` as the time index + +The `origin_logs` table (direct insertion) stores everything in a single `message` column. + +### Why Use Pipelines? + +It is recommended to use the pipeline method to split the log message into multiple columns, +which offers the advantage of explicitly querying specific values within certain columns. +Column matching query proves superior to full-text searching for several key reasons: + +- **Performance**: Column-based queries are typically faster than full-text searches +- **Storage Efficiency**: GreptimeDB's columnar storage compresses structured data better; inverted indexes for tags consume less storage than full-text indexes +- **Query Simplicity**: Tag-based queries are easier to write, understand, and debug + +## Next Steps + +- **Full-Text Search**: Explore the [Full-Text Search](fulltext-search.md) guide to learn advanced text search capabilities and query techniques in GreptimeDB +- **Pipeline Configuration**: Explore the [Pipeline Configuration](/reference/pipeline/pipeline-config.md) documentation to learn more about creating and customizing pipelines for various log formats and processing needs + diff --git a/versioned_docs/version-1.0/user-guide/manage-data/data-index.md b/versioned_docs/version-1.0/user-guide/manage-data/data-index.md new file mode 100644 index 0000000000..c1c38a58c4 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/manage-data/data-index.md @@ -0,0 +1,242 @@ +--- +keywords: [index, inverted index, skipping index, full-text index, query performance] +description: Learn about different types of indexes in GreptimeDB, including inverted index, skipping index, and full-text index, and how to use them effectively to optimize query performance. +--- + +# Data Index + +GreptimeDB provides various indexing mechanisms to accelerate query performance. Indexes are essential database structures that help optimize data retrieval operations by creating efficient lookup paths to specific data. + +## Overview + +Indexes in GreptimeDB are specified during table creation and are designed to improve query performance for different types of data and query patterns. The database currently supports these types of indexes: + +- Inverted Index +- Skipping Index +- Fulltext Index + +Notice that in this chapter we are narrowing the word "index" to those related to data value indexing. PRIMARY KEY and TIME INDEX can also be treated as index in some scenarios, but they are not covered here. + +## Index Types + +### Inverted Index + +An inverted index is particularly useful for tag columns. It creates a mapping between unique tag values and their corresponding rows, enabling fast lookups for specific tag values. + +The inverted index is not automatically applied to tag columns. +You need to manually create an inverted index by considering the following typical use cases: +- Querying data by tag values +- Filtering operations on string columns +- Point queries on tag columns + +Example: +```sql +CREATE TABLE monitoring_data ( + host STRING INVERTED INDEX, + region STRING PRIMARY KEY INVERTED INDEX, + cpu_usage DOUBLE, + `timestamp` TIMESTAMP TIME INDEX, +); +``` + +However, when you have a large number of unique tag values (Cartesian product among all columns indexed by inverted index), the inverted index may not be the best choice due to the overhead of maintaining the index. It may bring high memory consumption and large index size. In this case, you may consider using the skipping index. + +### Skipping Index + +Skipping index suits for columnar data systems like GreptimeDB. It maintains metadata about value ranges within data blocks, allowing the query engine to skip irrelevant data blocks during range queries efficiently. This index also has smaller size compare to others. + +**Use Cases:** +- When certain values are sparse, such as MAC address codes in logs. +- Querying specific values that occur infrequently within large datasets + +Example: +```sql +CREATE TABLE sensor_data ( + domain STRING PRIMARY KEY, + device_id STRING SKIPPING INDEX, + temperature DOUBLE, + `timestamp` TIMESTAMP TIME INDEX, +); +``` + +Skipping index supports options by `WITH`: +* `type`: The index type, only supports `BLOOM` type right now. +* `granularity`: (For `BLOOM` type) The size of data chunks covered by each filter. A smaller granularity improves filtering but increases index size. Default is `10240`. +* `false_positive_rate`: (For `BLOOM` type) The probability of misidentifying a block. A lower rate improves accuracy (better filtering) but increases index size. Value is a float between `0` and `1`. Default is `0.01`. + +For example: + +```sql +CREATE TABLE sensor_data ( + domain STRING PRIMARY KEY, + device_id STRING SKIPPING INDEX WITH(type='BLOOM', granularity=1024, false_positive_rate=0.01), + temperature DOUBLE, + `timestamp` TIMESTAMP TIME INDEX, +); +``` + +Skipping index can't handle complex filter conditions, and usually has a lower filtering performance compared to inverted index or full-text index. + +### Full-Text Index + +Full-text index is designed for text search operations on string columns. It enables efficient searching of text content using word-based matching and text search capabilities. You can query text data with flexible keywords, phrases, or pattern matching queries. + +**Use Cases:** +- Text search operations +- Pattern matching queries +- Large text filtering + +Example: +```sql +CREATE TABLE logs ( + message STRING FULLTEXT INDEX, + `level` STRING PRIMARY KEY, + `timestamp` TIMESTAMP TIME INDEX, +); +``` + +#### Configuration Options + +When creating or modifying a full-text index, you can specify the following options using `FULLTEXT INDEX WITH`: + +- `analyzer`: Sets the language analyzer for the full-text index + - Supported values: `English`, `Chinese` + - Default: `English` + - Note: The Chinese analyzer requires significantly more time to build the index due to the complexity of Chinese text segmentation. Consider using it only when Chinese text search is a primary requirement. + +- `case_sensitive`: Determines whether the full-text index is case-sensitive + - Supported values: `true`, `false` + - Default: `false` + - Note: Setting to `true` may slightly improve performance for case-sensitive queries, but will degrade performance for case-insensitive queries. This setting does not affect the results of `matches_term` queries. + +- `backend`: Sets the backend for the full-text index + - Supported values: `bloom`, `tantivy` + - Default: `bloom` + +- `granularity`: (For `bloom` backend) The size of data chunks covered by each filter. A smaller granularity improves filtering but increases index size. + - Supported values: positive integer + - Default: `10240` + +- `false_positive_rate`: (For `bloom` backend) The probability of misidentifying a block. A lower rate improves accuracy (better filtering) but increases index size. + - Supported values: float between `0` and `1` + - Default: `0.01` + +#### Backend Selection + +GreptimeDB provides two full-text index backends for efficient log searching: + +1. **Bloom Backend** + - Best for: General-purpose log searching + - Features: + - Uses Bloom filter for efficient filtering + - Lower storage overhead + - Consistent performance across different query patterns + - Limitations: + - Slightly slower for high-selectivity queries + - Storage Cost Example: + - Original data: ~10GB + - Bloom index: ~1GB + +2. **Tantivy Backend** + - Best for: High-selectivity queries (e.g., unique values like TraceID) + - Features: + - Uses inverted index for fast exact matching + - Excellent performance for high-selectivity queries + - Limitations: + - Higher storage overhead (close to original data size) + - Slower performance for low-selectivity queries + - Storage Cost Example: + - Original data: ~10GB + - Tantivy index: ~10GB + +#### Performance Comparison + +The following table shows the performance comparison between different query methods (using Bloom as baseline): + +| Query Type | High Selectivity (e.g., TraceID) | Low Selectivity (e.g., "HTTP") | +|------------|----------------------------------|--------------------------------| +| LIKE | 50x slower | 1x | +| Tantivy | 5x faster | 5x slower | +| Bloom | 1x (baseline) | 1x (baseline) | + +Key observations: +- For high-selectivity queries (e.g., unique values), Tantivy provides the best performance +- For low-selectivity queries, Bloom offers more consistent performance +- Bloom has significant storage advantage over Tantivy (1GB vs 10GB in test case) + +#### Examples + +**Creating a Table with Full-Text Index** + +```sql +-- Using Bloom backend (recommended for most cases) +CREATE TABLE logs ( + timestamp TIMESTAMP(9) TIME INDEX, + message STRING FULLTEXT INDEX WITH ( + backend = 'bloom', + analyzer = 'English', + case_sensitive = 'false' + ) +); + +-- Using Tantivy backend (for high-selectivity queries) +CREATE TABLE logs ( + timestamp TIMESTAMP(9) TIME INDEX, + message STRING FULLTEXT INDEX WITH ( + backend = 'tantivy', + analyzer = 'English', + case_sensitive = 'false' + ) +); +``` + +**Modifying an Existing Table** + +```sql +-- Enable full-text index on an existing column +ALTER TABLE monitor +MODIFY COLUMN load_15 +SET FULLTEXT INDEX WITH ( + analyzer = 'English', + case_sensitive = 'false', + backend = 'bloom' +); + +-- Change full-text index configuration +ALTER TABLE logs +MODIFY COLUMN message +SET FULLTEXT INDEX WITH ( + analyzer = 'English', + case_sensitive = 'false', + backend = 'tantivy' +); +``` + +Fulltext index usually comes with following drawbacks: + +- Higher storage overhead compared to regular indexes due to storing word tokens and positions +- Increased flush and compaction latency as each text document needs to be tokenized and indexed +- May not be optimal for simple prefix or suffix matching operations + +Consider using full-text index only when you need advanced text search capabilities and flexible query patterns. + +## Modify indexes + +You can always change the index type of columns by the `ALTER TABLE` statement, read the [reference](/reference/sql/alter/#alter-table) for more info. + +## Best Practices + +1. Choose the appropriate index type based on your data type and query patterns +2. Index only the columns that are frequently used in WHERE clauses +3. Consider the trade-off between query performance, ingest performance and resource consumption +4. Monitor index usage and performance to optimize your indexing strategy continuously + +## Performance Considerations + +While indexes can significantly improve query performance, they come with some overhead: + +- Additional storage space required for index structures +- Impact on flush and compaction performance due to index maintenance +- Memory usage for index caching + +Choose indexes carefully based on your specific use case and performance requirements. diff --git a/versioned_docs/version-1.0/user-guide/manage-data/overview.md b/versioned_docs/version-1.0/user-guide/manage-data/overview.md new file mode 100644 index 0000000000..98d5ca9039 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/manage-data/overview.md @@ -0,0 +1,350 @@ +--- +keywords: [update data, delete data, truncate table, data retention, TTL policies] +description: Provides an overview of managing data in GreptimeDB, including updating, deleting, truncating tables, and managing data retention with TTL policies. +--- + +# Manage Data + +## Update data + +### Update data with same tags and time index + +Updates can be efficiently performed by inserting new data. +If rows of data have the same tags and time index, +the old data will be replaced with the new data. +This means that you can only update columns with a field type. +To update data, simply insert new data with the same tag and time index as the existing data. + +For more information about column types, please refer to the [Data Model](../concepts/data-model.md). + +:::warning Note +Excessive updates may negatively impact query performance, even though the performance of updates is the same as insertion. +::: + +#### Update all fields in a table + +By default, when updating data, all fields will be overwritten with the new values, +except for [InfluxDB line protocol](/user-guide/protocols/influxdb-line-protocol.md), which only [updates the specified fields](#overwrite-specific-fields-in-a-table). +The following example using SQL demonstrates the behavior of overwriting all fields in a table. + +Assuming you have a table named `monitor` with the following schema. +The `host` column represents the tag and the `ts` column represents the time index. + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64, + memory FLOAT64, + PRIMARY KEY(host) +); +``` + +Insert a new row into the `monitor` table: + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +VALUES ("127.0.0.1", "2024-07-11 20:00:00", 0.8, 0.1); +``` + +Check the data in the table: + +```sql +SELECT * FROM monitor; +``` + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-07-11 20:00:00 | 0.8 | 0.1 | ++-----------+---------------------+------+--------+ +1 row in set (0.00 sec) +``` + +To update the data, you can use the same `host` and `ts` values as the existing data and set the new `cpu` value to `0.5`: + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +-- The same tag `127.0.0.1` and the same time index 2024-07-11 20:00:00 +VALUES ("127.0.0.1", "2024-07-11 20:00:00", 0.5, 0.1); +``` + +The new data will be: + +```sql +SELECT * FROM monitor; +``` + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-07-11 20:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +1 row in set (0.01 sec) +``` + +With the default merge policy, +if columns are omitted in the `INSERT INTO` statement, +they will be overwritten with the default values. + +For example: + +```sql +INSERT INTO monitor (host, ts, cpu) +VALUES ("127.0.0.1", "2024-07-11 20:00:00", 0.5); +``` + +The default value of the `memory` column in the `monitor` table is `NULL`. Therefore, the new data will be: + +```sql +SELECT * FROM monitor; +``` + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-07-11 20:00:00 | 0.5 | NULL | ++-----------+---------------------+------+--------+ +1 row in set (0.01 sec) +``` + +### Update specific fields in a table + +This update policy is supported by default in the [InfluxDB line protocol](/user-guide/protocols/influxdb-line-protocol.md). +You can also enable this behavior by specifying the `merge_mode` option as `last_non_null` when creating a table using SQL. +Here's an example: + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64, + memory FLOAT64, + PRIMARY KEY(host) +) WITH ('merge_mode'='last_non_null'); +``` + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +VALUES ("127.0.0.1", "2024-07-11 20:00:00", 0.8, 0.1); +``` + +To update specific fields in the `monitor` table, +you can insert new data with only the fields you want to update. +For example: + +```sql +INSERT INTO monitor (host, ts, cpu) +VALUES ("127.0.0.1", "2024-07-11 20:00:00", 0.5); +``` + +This will update the `cpu` field while leaving the `memory` field unchanged. +The result will be: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-07-11 20:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +``` + + +Notice that the `last_non_null` merge mode cannot update the old value to `NULL`. +For example: + + +```sql +INSERT INTO monitor (host, ts, cpu, memory) +VALUES ("127.0.0.1", "2024-07-11 20:00:01", 0.8, 0.1); +``` + +```sql +INSERT INTO monitor (host, ts, cpu) +VALUES ("127.0.0.1", "2024-07-11 20:00:01", NULL); +``` + +That will not update anything: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-07-11 20:00:01 | 0.8 | 0.1 | ++-----------+---------------------+------+--------+ +``` + +For more information about the `merge_mode` option, please refer to the [CREATE TABLE](/reference/sql/create.md#create-a-table-with-merge-mode) statement. + +### Avoid updating data by creating table with `append_mode` option + +GreptimeDB supports an `append_mode` option when creating a table, +which always inserts new data to the table. +This is especially useful when you want to keep all historical data, such as logs. + +You can only create a table with the `append_mode` option using SQL. +After successfully creating the table, +all protocols [ingest data](/user-guide/ingest-data/overview.md) to the table will always insert new data. + +For example, you can create an `app_logs` table with the `append_mode` option as follows. +The `host` and `log_level` columns represent tags, and the `ts` column represents the time index. + +```sql +CREATE TABLE app_logs ( + ts TIMESTAMP TIME INDEX, + host STRING, + api_path STRING FULLTEXT INDEX, + log_level STRING, + log STRING FULLTEXT INDEX, + PRIMARY KEY (host, log_level) +) WITH ('append_mode'='true'); +``` + +Insert a new row into the `app_logs` table: + +```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'); +``` + +Check the data in the table: + +```sql +SELECT * FROM app_logs; +``` + +The output will be: + +```sql ++---------------------+-------+------------------+-----------+--------------------+ +| ts | host | api_path | log_level | log | ++---------------------+-------+------------------+-----------+--------------------+ +| 2024-07-11 20:00:10 | host1 | /api/v1/resource | ERROR | Connection timeout | ++---------------------+-------+------------------+-----------+--------------------+ +1 row in set (0.01 sec) +``` + +You can insert new data with the same tag and time index: + +```sql +INSERT INTO app_logs (ts, host, api_path, log_level, log) +-- The same tag `host1` and `ERROR`, the same time index 2024-07-11 20:00:10 +VALUES ('2024-07-11 20:00:10', 'host1', '/api/v1/resource', 'ERROR', 'Connection reset'); +``` + +Then you will find two rows in the table: + +```sql +SELECT * FROM app_logs; +``` + +```sql ++---------------------+-------+------------------+-----------+--------------------+ +| ts | host | api_path | log_level | log | ++---------------------+-------+------------------+-----------+--------------------+ +| 2024-07-11 20:00:10 | host1 | /api/v1/resource | ERROR | Connection reset | +| 2024-07-11 20:00:10 | host1 | /api/v1/resource | ERROR | Connection timeout | ++---------------------+-------+------------------+-----------+--------------------+ +2 rows in set (0.01 sec) +``` + +## Delete Data + +You can effectively delete data by specifying tags and time index. +Deleting data without specifying the tag and time index columns is not efficient, as it requires two steps: querying the data and then deleting it by tag and time index. +For more information about column types, please refer to the [Data Model](../concepts/data-model.md). + +:::warning Warning +Excessive deletions can negatively impact query performance. +::: + +You can only delete data using SQL. +For example, to delete a row from the `monitor` table with tag `host` and timestamp index `ts`: + +```sql +DELETE FROM monitor WHERE host='127.0.0.2' AND ts=1667446798450; +``` + +The output will be: + +```sql +Query OK, 1 row affected (0.00 sec) +``` + +For more information about the `DELETE` statement, please refer to the [SQL DELETE](/reference/sql/delete.md). + +## Truncate Table + +To delete all data in a table, you can use the `TRUNCATE TABLE` statement in SQL. +For example, to truncate the `monitor` table: + +```sql +TRUNCATE TABLE monitor; +``` + +For more information about the `TRUNCATE TABLE` statement, refer to the [SQL TRUNCATE TABLE](/reference/sql/truncate.md) documentation. + +## Manage data retention with TTL policies + +You can use Time to Live (TTL) policies to automatically remove stale data from your databases. TTL allows you to set policies to periodically delete data from tables. Setting TTL policies has the following benefits: + +- Decrease storage costs by cleaning out obsolete data. +- Reduce the number of rows the database has to scan for some queries, potentially increasing query performance. + +> Please note that the expired data due to TTL policy may not be deleted right after the expiration time. Instead, they are deleted during the compaction, which is a background job run asynchronously. +> If you are testing the TTL policy, be sure to trigger data flush and compaction before querying the data. +> You can use our "[ADMIN](/reference/sql/admin.md)" functions to manually run them. + +You can set TTL for every table when creating it. For example, the following SQL statement creates a table named `monitor` with a TTL policy of 7 days: + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64, + memory FLOAT64, + PRIMARY KEY(host) +) WITH ('ttl'='7d'); +``` + +You can also create a database-level TTL policy. For example, the following SQL statement creates a database named `test` with a TTL policy of 7 days: + +```sql +CREATE DATABASE test WITH ('ttl'='7d'); +``` + +You can set TTL policies at both the table level and the database level simultaneously. +If a table has its own TTL policy, +it will take precedence over the database TTL policy. +Otherwise, the database TTL policy will be applied to the table. + +The value of `'ttl'` can be one of duration (like `1hour 12min 5s`), `instant` or `forever`. See details in [CREATE](/reference/sql/create.md#create-a-table-with-ttl) statement. + +Use [`ALTER`](/reference/sql/alter.md#alter-table-options) to modify the TTL of an existing table or database: + +```sql +-- for table +ALTER TABLE monitor SET 'ttl'='1 month'; +-- for database +ALTER DATABASE test SET 'ttl'='1 month'; +``` + +If you want to remove the TTL policy, you can use the following SQL + +```sql +-- for table +ALTER TABLE monitor UNSET 'ttl'; +-- or for database +ALTER DATABASE test UNSET 'ttl'; +``` + +For more information about TTL policies, please refer to the [CREATE](/reference/sql/create.md) statement. + + +## More data management operations + +For more advanced data management operations, such as basic table operations, table sharding and region migration, please refer to the [Data Management](/user-guide/deployments-administration/manage-data/overview.md) in the administration section. + diff --git a/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-clickhouse.md b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-clickhouse.md new file mode 100644 index 0000000000..4cf6a88922 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-clickhouse.md @@ -0,0 +1,244 @@ +--- +keywords: [migrate from ClickHouse, ClickHouse,GreptimeDB,write data, export data, import data,migration] +description: Step-by-step guide on migrating from ClickHouse to GreptimeDB, including data model adjustments, table structure reconstruction,, exporting and importing data. +--- + +# Migrate from ClickHouse + +This guide provides a detailed explanation on how to smoothly migrate your business from ClickHouse to GreptimeDB. It covers pre-migration preparation, data model adjustments, table structure reconstruction, dual-write assurance, and specific methods for data export and import, aiming to achieve a seamless system transition. + + +## Pre-Migration Notes + +- **Compatibility** + Although GreptimeDB is SQL protocol compatible, the two databases have fundamental differences in data modeling, index design, and compression mechanisms. Be sure to refer to the [SQL compatibility](/reference/sql/compatibility.md) documentation and official [modeling guidelines](/user-guide/deployments-administration/performance-tuning/design-table.md) to refactor table structures and data flows during migration. + +- **Data Model Differences** + ClickHouse is a general-purpose big data analytics engine, while GreptimeDB is optimized for time-series, metrics, and log observability scenarios. There are differences in their data models, index systems, and compression algorithms, so it’s important to take these differences and the actual business scenario into account during model design and compatibility considerations. + +--- + +## Refactoring Data Model and Table Structure + +### Time Index +- ClickHouse tables do not always have a `time index` field. During migration, you need to clearly select the primary time field for your business to serve as the time index and specify it when creating the table in GreptimeDB. For example, typical log or trace print times. +- The time precision (such as second, millisecond, microsecond, etc.) should be assessed based on real-world requirements and cannot be changed once set. + +### Primary Key and Wide Table Recommendations +- Primary Key: Just like the `order by` in ClickHouse without the timestamp column. It’s not recommended to include high-cardinality fields such as log IDs, user IDs or UUIDs to avoid primary key bloat, excessive write amplification, and inefficient queries. +- Wide Table vs. Multiple Tables: For multiple metrics collected at the same observation point (such as on the same host), it’s better to use a wide table, which improves batch write efficiency and compression ratio. + +### Index Planning +- Inverted Index: Build indexes for low-cardinality columns to improve filter efficiency. +- Skipping Index: Use as needed; Used when certain values are sparse or querying specific values that occur infrequently within large datasets. +- Fulltext Index: Use as needed; Designed for text search operations on string columns; avoid building unnecessary indexes on high-cardinality or highly variable fields. +- Read [Data Index](/user-guide/manage-data/data-index.md) for more info. + +### Partitioning Table +ClickHouse supports table partitioning via the `PARTITION BY` syntax. GreptimeDB provides a similar feature with a different syntax; see the [table sharding](/user-guide/deployments-administration/manage-data/table-sharding.md) documentation for details. + +### TTL +GreptimeDB supports TTL (Time-to-live) through the table option `ttl`. For more information, please refer to [Manage data retention with TTL policies](/user-guide/manage-data/overview.md#manage-data-retention-with-ttl-policies). + +### Example Table + +Example ClickHouse table structure: +```sql +CREATE TABLE example ( + timestamp DateTime, + host String, + app String, + metric String, + value Float64 + ) ENGINE = MergeTree() + TTL timestamp + INTERVAL 30 DAY + ORDER BY (timestamp, host, app, metric); +``` + +Recommended table structure after migrating to GreptimeDB: +```sql +CREATE TABLE example ( + `timestamp` TIMESTAMP NOT NULL, + host STRING, + app STRING INVERTED INDEX, + metric STRING INVERTED INDEX, + `value` DOUBLE, + PRIMARY KEY (host, app, metric), + TIME INDEX (`timestamp`) + ) with(ttl='30d'); +``` + +> The choice of primary key and the granularity of the time index should be carefully planned based on your business's data volume and query scenarios. If the host cardinality is high (e.g., hundreds of thousands of monitored hosts), you should remove it from the primary key and consider creating a skipping index for it. + +--- + +### Migrating Typical Log Tables + +> GreptimeDB already provides built-in modeling for otel log ingestion, so please refer to the [official documentation](/user-guide/ingest-data/for-observability/opentelemetry.md#logs). + +Common ClickHouse log table structure: +```sql +CREATE TABLE logs + ( + timestamp DateTime, + host String, + service String, + log_level String, + log_message String, + trace_id String, + span_id String, + INDEX inv_idx(log_message) TYPE ngrambf_v1(4, 1024, 1, 0) GRANULARITY 1 + ) ENGINE = MergeTree + ORDER BY (timestamp, host, service); +``` + +Recommended GreptimeDB table structure: +- Time index: `timestamp` (precision set based on logging frequency) +- Primary key: `host`, `service` (fields often used in queries/aggregations) +- Field columns: `log_message`, `trace_id`, `span_id` (high-cardinality, unique identifiers, or raw content) + +```sql +CREATE TABLE logs ( + `timestamp` TIMESTAMP NOT NULL, + host STRING, + service STRING, + log_level STRING, + log_message STRING FULLTEXT INDEX WITH ( + backend = 'bloom', + analyzer = 'English', + case_sensitive = 'false' + ), + trace_id STRING SKIPPING INDEX, + span_id STRING SKIPPING INDEX, + PRIMARY KEY (host, service), + TIME INDEX (`timestamp`) + ); +``` + +**Notes:** +- `host` and `service` serve as common query filters and are included in the primary key to optimize filtering. If there are very many hosts, you might not want to include `host` in the primary key but instead create a skip index. +- `log_message` is treated as raw content with a full-text index created. If you want the full-text index to take effect during queries, you also need to adjust your SQL query syntax. Please refer to [the log query documentation](/user-guide/logs/fulltext-search.md) for details +- Since `trace_id` and `span_id` are mostly high-cardinality fields, it is not recommended to use them in the primary key, but skip indexes have been added. + +--- + +### Migrating Typical Traces Tables + +> GreptimeDB also provides built-in modeling for otel trace ingestion, please read the [official documentation](/user-guide/ingest-data/for-observability/opentelemetry.md#traces). + +Common ClickHouse trace table structure design: +```sql +CREATE TABLE traces ( + timestamp DateTime, + trace_id String, + span_id String, + parent_span_id String, + service String, + operation String, + duration UInt64, + status String, + tags Map(String, String) + ) ENGINE = MergeTree() + ORDER BY (timestamp, trace_id, span_id); +``` + +Recommended GreptimeDB table structure: +- Time index: `timestamp` (e.g., collection/start time) +- Primary key: `service`, `operation` (commonly filtered/aggregated properties) +- Field columns: `trace_id`, `span_id`, `parent_span_id`, `duration`, `tags` (high-cardinality or Map type) + +```sql +CREATE TABLE traces ( + `timestamp` TIMESTAMP NOT NULL, + service STRING, + operation STRING, + `status` STRING, + trace_id STRING SKIPPING INDEX, + span_id STRING SKIPPING INDEX, + parent_span_id STRING SKIPPING INDEX, + duration DOUBLE, + tags STRING, -- If this is structured JSON, either store it as-is or use the pipeline to parse fields + PRIMARY KEY (service, operation), + TIME INDEX (`timestamp`) + ); +``` + +**Notes:** +- `service` and `operation` serve as primary key, supporting trace scheduling and aggregate queries by service or operations. +- `trace_id`, `span_id`, and `parent_span_id` use skip indexes but are not part of the primary key. +- High-cardinality fields are set as fields for efficient writes. For complex properties like `tags`, [JSON storage](/reference/sql/data-types/#json-type-experimental) or string is recommended, and they can be expanded using GreptimeDB’s ETL - [Pipeline](/user-guide/logs/quick-start.md#write-logs-by-pipeline) if necessary. +- Depending on overall business volume, consider whether to partition traces into multiple tables (such as in massive multi-service environments). + +--- + +## Dual-write Strategy for Safe Migration + +During the migration process, to avoid data loss or inconsistent writes, adopt a dual-write approach: +- The application should write to both ClickHouse and GreptimeDB simultaneously, running the two systems in parallel. +- Validate and compare data using logs and checks to ensure data consistency. Once the data has been fully validated, you can switch fully over. + +--- + +## Exporting and Importing Historical Data + +1. **Enable dual-write before migration** +The application should write to both ClickHouse and GreptimeDB. Check for data consistency to reduce the risk of missing data. + +2. **Data export from ClickHouse** +Use ClickHouse’s native command to export data as CSV, TSV, Parquet, or other formats. For example: +```sh +clickhouse client --query="SELECT * FROM example INTO OUTFILE 'example.csv' FORMAT CSVWithNames" +``` +The exported CSV will look like: +```csv +"timestamp","host","app","metric","value" +"2024-04-25 10:00:00","host01","nginx","cpu_usage",12.7 +"2024-04-25 10:00:00","host02","redis","cpu_usage",8.4 +"2024-04-25 10:00:00","host03","postgres","cpu_usage",15.3 +"2024-04-25 10:01:00","host01","nginx","cpu_usage",12.5 +"2024-04-25 10:01:00","host01","nginx","mem_usage",1034.5 +"2024-04-25 10:01:00","host02","redis","mem_usage",876.2 +"2024-04-25 10:01:00","host03","postgres","mem_usage",1145.2 +"2024-04-25 10:02:00","host01","nginx","disk_io",120.3 +"2024-04-25 10:02:00","host02","redis","disk_io",95.1 +"2024-04-25 10:02:00","host03","postgres","disk_io",134.7 +"2024-04-25 10:03:00","host02","redis","mem_usage",874 +"2024-04-25 10:04:00","host03","postgres","cpu_usage",15.1 +``` + +3. **Data import into GreptimeDB** +> The table must be created in GreptimeDB before importing data. + +GreptimeDB currently supports batch data import via SQL commands or [REST API](/reference/http-endpoints.md#protocol-endpoints). For large datasets, import in batches. +Use the [`COPY FROM` command](/reference/sql/copy.md#copy-from) to import: +```sql + COPY example FROM "/path/to/example.csv" WITH (FORMAT = 'CSV'); +``` +Alternatively, you can convert the CSV to standard INSERT statements for batch import. + +--- + +## Validation and Cutover + +- Once the import is complete, use GreptimeDB’s query interface to compare data with ClickHouse for consistency. +- After data verification and monitoring meet requirements, you can officially switch business writes to GreptimeDB and disable dual-write mode. + +--- + +## Frequently Asked Questions and Optimization Tips + +### What if SQL/types are incompatible? + Before migration, audit all query SQL and rewrite or translate as necessary, referring to the [official documentation](/user-guide/query-data/sql.md) (especially for [log query](/user-guide/logs/fulltext-search.md)) for any incompatible syntax or data types. + +### How do I efficiently import very large datasets in batches? + For large tables or full historical data, export and import by partition or shard as appropriate. Monitor write speed and import progress closely. + +### How should high-cardinality fields be handled? + Avoid using high-cardinality fields as primary key. Store them as fields instead, and split into multiple tables if necessary. + +### How should wide tables be planned? + For each monitoring entity or collection endpoint, consolidate all metrics into a single table. For example, use a `host_metrics` table to store all server statistics. + +--- + +If you need a more detailed migration plan or example scripts, please provide the specific table structure and data volume. The [GreptimeDB official community](https://github.com/orgs/GreptimeTeam/discussions) will offer further support. Welcome to join the [Greptime Slack](http://greptime.com/slack). diff --git a/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-influxdb.md b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-influxdb.md new file mode 100644 index 0000000000..2fffbe069f --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-influxdb.md @@ -0,0 +1,192 @@ +--- +keywords: [migrate from InfluxDB, write data, HTTP API, Telegraf, client libraries] +description: Instructions on migrating from InfluxDB to GreptimeDB, including writing data using HTTP API, Telegraf, and client libraries. +--- + +import DocTemplate from '../../db-cloud-shared/migrate/migrate-from-influxdb.md' + +# Migrate from InfluxDB + + + +
+ + + + +```shell +curl -X POST 'http://{{host}}:4000/v1/influxdb/api/v2/write?db={{db-name}}' \ + -H 'authorization: token {{greptime_user:greptimedb_password}}' \ + -d 'census,location=klamath,scientist=anderson bees=23 1566086400000000000' +``` + + + + + +```shell +curl 'http://{{host}}:4000/v1/influxdb/write?db={{db-name}}&u={{greptime_user}}&p={{greptimedb_password}}' \ + -d 'census,location=klamath,scientist=anderson bees=23 1566086400000000000' +``` + + + + + +
+ +
+ +For detailed configuration instructions, please refer to the [Ingest Data via Telegraf](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md#telegraf) documentation. + +
+ + +
+ + + + +```js [Node.js] +'use strict' +/** @module write +**/ + +import { InfluxDB, Point } from '@influxdata/influxdb-client' + +/** Environment variables **/ +const url = 'http://:4000/v1/influxdb' +const token = ':' +const org = '' +const bucket = '' + +const influxDB = new InfluxDB({ url, token }) +const writeApi = influxDB.getWriteApi(org, bucket) +writeApi.useDefaultTags({ region: 'west' }) +const point1 = new Point('temperature') + .tag('sensor_id', 'TLM01') + .floatField('value', 24.0) +writeApi.writePoint(point1) + +``` + + + + + +```python +import influxdb_client +from influxdb_client.client.write_api import SYNCHRONOUS + +bucket = "" +org = "" +token = ":" +url="http://:4000/v1/influxdb" + +client = influxdb_client.InfluxDBClient( + url=url, + token=token, + org=org +) + +# Write script +write_api = client.write_api(write_options=SYNCHRONOUS) + +p = influxdb_client.Point("my_measurement").tag("location", "Prague").field("temperature", 25.3) +write_api.write(bucket=bucket, org=org, record=p) + +``` + + + + + +```go +bucket := "" +org := "" +token := ":" +url := "http://:4000/v1/influxdb" +client := influxdb2.NewClient(url, token) +writeAPI := client.WriteAPIBlocking(org, bucket) + +p := influxdb2.NewPoint("stat", + map[string]string{"unit": "temperature"}, + map[string]interface{}{"avg": 24.5, "max": 45}, + time.Now()) +writeAPI.WritePoint(context.Background(), p) +client.Close() + +``` + + + + + +```java +private static String url = "http://:4000/v1/influxdb"; +private static String org = ""; +private static String bucket = ""; +private static char[] token = ":".toCharArray(); + +public static void main(final String[] args) { + + InfluxDBClient influxDBClient = InfluxDBClientFactory.create(url, token, org, bucket); + WriteApiBlocking writeApi = influxDBClient.getWriteApiBlocking(); + Point point = Point.measurement("temperature") + .addTag("location", "west") + .addField("value", 55D) + .time(Instant.now().toEpochMilli(), WritePrecision.MS); + + writeApi.writePoint(point); + influxDBClient.close(); +} +``` + + + + + +```php +$client = new Client([ + "url" => "http://:4000/v1/influxdb", + "token" => ":", + "bucket" => "", + "org" => "", + "precision" => InfluxDB2\Model\WritePrecision::S +]); + +$writeApi = $client->createWriteApi(); + +$dateTimeNow = new DateTime('NOW'); +$point = Point::measurement("weather") + ->addTag("location", "Denver") + ->addField("temperature", rand(0, 20)) + ->time($dateTimeNow->getTimestamp()); +$writeApi->write($point); +``` + + + + + +
+ +
+It is recommended using Grafana to visualize data in GreptimeDB. +Please refer to the [Grafana documentation](/user-guide/integrations/grafana.md) for details on configuring GreptimeDB. +
+ +
+ +```shell +for file in data.*; do + curl -i --retry 3 \ + -X POST "http://${GREPTIME_HOST}:4000/v1/influxdb/write?db=${GREPTIME_DB}&u=${GREPTIME_USERNAME}&p=${GREPTIME_PASSWORD}" \ + --data-binary @${file} + sleep 1 +done +``` + +
+ +
diff --git a/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-mysql.md b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-mysql.md new file mode 100644 index 0000000000..7a3d6bdb4a --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-mysql.md @@ -0,0 +1,111 @@ +--- +keywords: [migrate from MySQL, create databases, write data, export data, import data] +description: Step-by-step guide on migrating from MySQL to GreptimeDB, including creating databases, writing data, exporting and importing data. +--- + +# Migrate from MySQL + +This document will guide you through the migration process from MySQL to GreptimeDB. + +## Before you start the migration + +Please be aware that though GreptimeDB supports the wire protocol of MySQL, it does not mean GreptimeDB implements all +MySQL's features. You may refer to: +* The [ANSI Compatibility](/reference/sql/compatibility.md) to see the constraints regarding using SQL in GreptimeDB. +* The [Data Modeling Guide](/user-guide/deployments-administration/performance-tuning/design-table.md) to create proper table schemas. +* The [Data Index Guide](/user-guide/manage-data/data-index.md) for index planning. + +## Migration steps + +### Create the databases and tables in GreptimeDB + +Before migrating the data from MySQL, you first need to create the corresponding databases and tables in GreptimeDB. +GreptimeDB has its own SQL syntax for creating tables, so you cannot directly reuse the table creation SQLs that are produced +by MySQL. + +When you write the table creation SQL for GreptimeDB, it's important to understand +its "[data model](/user-guide/concepts/data-model.md)" first. Then, please take the following considerations in +your create table SQL: + +1. Since the time index column cannot be changed after the table is created, you need to choose the time index column + carefully. The time index is best set to the natural timestamp when the data is generated, as it provides the most + intuitive way to query the data, and the best query performance. For example, in the IOT scenes, you can use the + collection time of sensor data as the time index; or the occurrence time of an event in the observability scenes. +2. In this migration process, it's not recommend to create another synthetic timestamp, such as a new column created + with `DEFAULT current_timestamp()` as the time index column. It's not recommend to use the random timestamp as the + time index either. +3. It's vital to set the most fit timestamp precision for your time index column, too. Like the chosen of time index + column, the precision of it cannot be changed as well. Find the most fit timestamp type for your + data set [here](/reference/sql/data-types#data-types-compatible-with-mysql-and-postgresql). +4. Choose a primary key only when it is truly needed. The primary key in GreptimeDB is different from that in MySQL. You should use a primary key only when: + * Most queries can benefit from the ordering. + * You need to deduplicate (including delete) rows by the primary key and time index. + + Otherwise, setting a primary key is optional and it may hurt performance. Read [Primary Key](/user-guide/deployments-administration/performance-tuning/design-table.md#primary-key) for details. + + Finally please refer to "[CREATE](/reference/sql/create.md)" SQL document for more details for choosing the +right data types and "ttl" or "compaction" options, etc. +5. Choose proper indexes to speed up queries. + * Inverted index: is ideal for filtering by low-cardinality columns and quickly finding rows with specific values. + * Skipping index: works well with sparse data. + * Fulltext index: enables efficient keyword and pattern search in large text columns. + + For details and best practices, refer to the [data index](user-guide/manage-data/data-index.md) documentation. +### Write data to both GreptimeDB and MySQL simultaneously + +Writing data to both GreptimeDB and MySQL simultaneously is a practical strategy to avoid data loss during migration. By +utilizing MySQL's client libraries (JDBC + a MySQL driver), you can set up two client instances - one for GreptimeDB +and another for MySQL. For guidance on writing data to GreptimeDB using SQL, please refer to the [Ingest Data](/user-guide/ingest-data/for-iot/sql.md) section. + +If retaining all historical data isn't necessary, you can simultaneously write data to both GreptimeDB and MySQL for a +specific period to accumulate the required recent data. Subsequently, cease writing to MySQL and continue exclusively +with GreptimeDB. If a complete migration of all historical data is needed, please proceed with the following steps. + +### Export data from MySQL + +[mysqldump](https://dev.mysql.com/doc/refman/8.4/en/mysqldump.html) is a commonly used tool to export data from MySQL. +Using it, we can export the data that can be later imported into GreptimeDB directly. For example, if we want to export +two databases, `db1` and `db2` from MySQL, we can use the following command: + +```bash +mysqldump -h127.0.0.1 -P3306 -umysql_user -p --compact -cnt --skip-extended-insert --databases db1 db2 > /path/to/output.sql +``` + +Replace the `-h`, `-P` and `-u` flags with the appropriate values for your MySQL server. The `--databases` flag is used +to specify the databases to be exported. The output will be written to the `/path/to/output.sql` file. + +The content in the `/path/to/output.sql` file should be like this: + +```plaintext +~ ❯ cat /path/to/output.sql + +USE `db1`; +INSERT INTO `foo` (`ts`, `a`, `b`) VALUES (1,'hello',1); +INSERT INTO ... + +USE `db2`; +INSERT INTO `foo` (`ts`, `a`, `b`) VALUES (2,'greptime',2); +INSERT INTO ... +``` + +### Import data into GreptimeDB + +The [MySQL Command-Line Client](https://dev.mysql.com/doc/refman/8.4/en/mysql.html) can be used to import data into +GreptimeDB. Continuing the above example, say the data is exported to file `/path/to/output.sql`, then we can use the +following command to import the data into GreptimeDB: + +```bash +mysql -h127.0.0.1 -P4002 -ugreptime_user -p -e "source /path/to/output.sql" +``` + +Replace the `-h`, `-P` and `-u` flags with the appropriate values for your GreptimeDB server. The `source` command is +used to execute the SQL commands in the `/path/to/output.sql` file. Add `-vvv` to see the detailed execution results for +debugging purpose. + +To summarize, data migration steps can be illustrate as follows: + +![migrate mysql data steps](/migration-mysql.jpg) + +After the data migration is completed, you can stop writing data to MySQL and continue using GreptimeDB exclusively! + +If you need a more detailed migration plan or example scripts, please provide the specific table structure and data volume. The [GreptimeDB official community](https://github.com/orgs/GreptimeTeam/discussions) will offer further support. Welcome to join the [Greptime Slack](http://greptime.com/slack). \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-postgresql.md b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-postgresql.md new file mode 100644 index 0000000000..52bf0804de --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-postgresql.md @@ -0,0 +1,145 @@ +--- +keywords: [migrate from PostgreSQL, create databases, write data, export data, import data] +description: Step-by-step guide on migrating from PostgreSQL to GreptimeDB, including creating databases, writing data, exporting and importing data. +--- + +# Migrate from PostgreSQL + +This document will guide you through the migration process from PostgreSQL to GreptimeDB. + +## Before you start the migration + +Please be aware that though GreptimeDB supports the wire protocol of PostgreSQL, it does not mean GreptimeDB implements +all +PostgreSQL's features. You may refer to: +* The [ANSI Compatibility](/reference/sql/compatibility.md) to see the constraints regarding using SQL in GreptimeDB. +* The [Data Modeling Guide](/user-guide/deployments-administration/performance-tuning/design-table.md) to create proper table schemas. +* The [Data Index Guide](/user-guide/manage-data/data-index.md) for index planning. + + +## Migration steps + +### Create the databases and tables in GreptimeDB + +Before migrating the data from PostgreSQL, you first need to create the corresponding databases and tables in +GreptimeDB. +GreptimeDB has its own SQL syntax for creating tables, so you cannot directly reuse the table creation SQLs that are +produced +by PostgreSQL. + +When you write the table creation SQL for GreptimeDB, it's important to understand +its "[data model](/user-guide/concepts/data-model.md)" first. Then, please take the following considerations in +your create table SQL: + +1. Since the time index column cannot be changed after the table is created, you need to choose the time index column + carefully. The time index is best set to the natural timestamp when the data is generated, as it provides the most + intuitive way to query the data, and the best query performance. For example, in the IOT scenes, you can use the + collection time of sensor data as the time index; or the occurrence time of an event in the observability scenes. +2. In this migration process, it's not recommend to create another synthetic timestamp, such as a new column created + with `DEFAULT current_timestamp()` as the time index column. It's not recommend to use the random timestamp as the + time index either. +3. It's vital to set the most fit timestamp precision for your time index column, too. Like the chosen of time index + column, the precision of it cannot be changed as well. Find the most fit timestamp type for your + data set [here](/reference/sql/data-types#data-types-compatible-with-mysql-and-postgresql). +4. Choose a primary key only when it is truly needed. The primary key in GreptimeDB is different from that in PostgreSQL. You should use a primary key only when: + * Most queries can benefit from the ordering. + * You need to deduplicate (including delete) rows by the primary key and time index. + + Otherwise, setting a primary key is optional and it may hurt performance. Read [Primary Key](/user-guide/deployments-administration/performance-tuning/design-table.md#primary-key) for details. + + Finally please refer to "[CREATE](/reference/sql/create.md)" SQL document for more details for choosing the +right data types and "ttl" or "compaction" options, etc. +5. Choose proper indexes to speed up queries. + * Inverted index: is ideal for filtering by low-cardinality columns and quickly finding rows with specific values. + * Skipping index: works well with sparse data. + * Fulltext index: enables efficient keyword and pattern search in large text columns. + + For details and best practices, refer to the [data index](user-guide/manage-data/data-index.md) documentation. + +### Write data to both GreptimeDB and PostgreSQL simultaneously + +Writing data to both GreptimeDB and PostgreSQL simultaneously is a practical strategy to avoid data loss during +migration. By utilizing PostgreSQL's client libraries (JDBC + a PostgreSQL driver), you can set up two client +instances - one for GreptimeDB and another for PostgreSQL. For guidance on writing data to GreptimeDB using SQL, please +refer to the [Ingest Data](/user-guide/ingest-data/for-iot/sql.md) section. + +If retaining all historical data isn't necessary, you can simultaneously write data to both GreptimeDB and PostgreSQL +for a specific period to accumulate the required recent data. Subsequently, cease writing to PostgreSQL and continue +exclusively with GreptimeDB. If a complete migration of all historical data is needed, please proceed with the following +steps. + +### Export data from PostgreSQL + +[pg_dump](https://www.postgresql.org/docs/current/app-pgdump.html) is a commonly used tool to export data from +PostgreSQL. Using it, we can export the data that can be later imported into GreptimeDB directly. For example, if we +want to export schemas whose names start with `db` in the database `postgres` from PostgreSQL, we can use the following +command: + +```bash +pg_dump -h127.0.0.1 -p5432 -Upostgres -ax --column-inserts --no-comments -n 'db*' postgres | grep -v "^SE" > /path/to/output.sql +``` + +Replace the `-h`, `-p` and `-U` flags with the appropriate values for your PostgreSQL server. The `-n` flag is used to +specify the schemas to be exported. And the database `postgres` is at the end of the `pg_dump` command line. Note that we pipe the `pg_dump` output through a special +`grep`, to remove some unnecessary `SET` or `SELECT` lines. The final output will be written to the +`/path/to/output.sql` file. + +The content in the `/path/to/output.sql` file should be like this: + +```plaintext +~ ❯ cat /path/to/output.sql + +-- +-- PostgreSQL database dump +-- + +-- Dumped from database version 16.4 (Debian 16.4-1.pgdg120+1) +-- Dumped by pg_dump version 16.4 + + +-- +-- Data for Name: foo; Type: TABLE DATA; Schema: db1; Owner: postgres +-- + +INSERT INTO db1.foo (ts, a) VALUES ('2024-10-31 00:00:00', 1); +INSERT INTO db1.foo (ts, a) VALUES ('2024-10-31 00:00:01', 2); +INSERT INTO db1.foo (ts, a) VALUES ('2024-10-31 00:00:01', 3); +INSERT INTO ... + + +-- +-- Data for Name: foo; Type: TABLE DATA; Schema: db2; Owner: postgres +-- + +INSERT INTO db2.foo (ts, b) VALUES ('2024-10-31 00:00:00', '1'); +INSERT INTO db2.foo (ts, b) VALUES ('2024-10-31 00:00:01', '2'); +INSERT INTO db2.foo (ts, b) VALUES ('2024-10-31 00:00:01', '3'); +INSERT INTO ... + + +-- +-- PostgreSQL database dump complete +-- +``` + +### Import data into GreptimeDB + +The [psql -- PostgreSQL interactive terminal](https://www.postgresql.org/docs/current/app-psql.html) can be used to +import data into GreptimeDB. Continuing the above example, say the data is exported to file `/path/to/output.sql`, then +we can use the following command to import the data into GreptimeDB: + +```bash +psql -h127.0.0.1 -p4003 -d public -f /path/to/output.sql +``` + +Replace the `-h` and `-p` flags with the appropriate values for your GreptimeDB server. The `-d` of the psql command is used to specify the database and cannot be omitted. The value `public` of `-d` is the default database used by GreptimeDB. You can also add `-a` to the end to see every +executed line, or `-s` for entering the single-step mode. + +To summarize, data migration steps can be illustrate as follows: + +![migrate postgresql data steps](/migration-postgresql.jpg) + +After the data migration is completed, you can stop writing data to PostgreSQL and continue using GreptimeDB +exclusively! + +If you need a more detailed migration plan or example scripts, please provide the specific table structure and data volume. The [GreptimeDB official community](https://github.com/orgs/GreptimeTeam/discussions) will offer further support. Welcome to join the [Greptime Slack](http://greptime.com/slack). \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-prometheus.md b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-prometheus.md new file mode 100644 index 0000000000..9feec90198 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/migrate-from-prometheus.md @@ -0,0 +1,30 @@ +--- +keywords: [migrate from Prometheus, remote write configuration, PromQL queries, Grafana integration] +description: Instructions on migrating from Prometheus to GreptimeDB, including remote write configuration, PromQL queries, and Grafana integration. +--- + +import DocTemplate from '../../db-cloud-shared/migrate/_migrate-from-prometheus.md' + +# Migrate from Prometheus + + + +
+ +For information on configuring Prometheus to write data to GreptimeDB, please refer to the [remote write](/user-guide/ingest-data/for-observability/prometheus.md#remote-write-configuration) documentation. + +
+ +
+ +For detailed information on querying data in GreptimeDB using Prometheus query language, please refer to the [HTTP API](/user-guide/query-data/promql.md#prometheus-http-api) section in the PromQL documentation. + +
+ +
+ +To add GreptimeDB as a Prometheus data source in Grafana, please refer to the [Grafana](/user-guide/integrations/grafana.md#prometheus-data-source) documentation. + +
+ +
diff --git a/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/overview.md b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/overview.md new file mode 100644 index 0000000000..8e231955b3 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/migrate-to-greptimedb/overview.md @@ -0,0 +1,14 @@ +--- +keywords: [migrate from MySQL, migrate from InfluxDB, migrate from PostgreSQL, migrate from Prometheus, migrate from ClickHouse] +description: The overview of migrating data to GreptimeDB from various databases, including InfluxDB, MySQL, PostgreSQL, Prometheus, and more. +--- + +# Migrate to GreptimeDB + +import DocCardList from '@theme/DocCardList'; + +You can migrate data from various databases to GreptimeDB, +including InfluxDB, MySQL, PostgreSQL, Prometheus, and more. + + + diff --git a/versioned_docs/version-1.0/user-guide/overview.md b/versioned_docs/version-1.0/user-guide/overview.md new file mode 100644 index 0000000000..1de7fd3575 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/overview.md @@ -0,0 +1,73 @@ +--- +keywords: [metrics, logs, observability, SQL support, range queries, flow computation, data model, protocols] +description: Learn how to use GreptimeDB according to your use case, including data ingestion, querying, and administration. +--- + +# User Guide + +Welcome to the user guide for GreptimeDB. + +GreptimeDB is the unified observability database for metrics, logs, and traces, +providing real-time insights from Edge to Cloud at any scale. + +## Understanding GreptimeDB Concepts + +Before diving into GreptimeDB, +it is recommended to familiarize yourself with its data model, key concepts, and features. +For a comprehensive overview, +refer to the [Concepts Documentation](./concepts/overview.md). + +## Ingesting Data Based on Your Use Case + +GreptimeDB supports [multiple protocols](./protocols/overview.md) and [various integration tools](./integrations/overview.md) to simplify data ingestion tailored to your requirements. + +### For Observability Scenarios + +If you plan to use GreptimeDB as metrics, logs and traces storage for observability purposes, +see the [Observability Documentation](./ingest-data/for-observability/overview.md). +It explains how to ingest data using tools like Otel-Collector, Vector, Kafka, Prometheus, and the InfluxDB line protocol. + +For a log storage solution, +refer to the [Logs Documentation](./logs/overview.md). +It details how to ingest pattern text logs using pipelines. + +For a trace storage solution, +refer to the [Traces Documentation](./traces/overview.md). +It explains how to ingest trace data using OpenTelemetry and query it with Jaeger. + +### For IoT and Edge Computing Scenarios + +For IoT and Edge Computing scenarios, +the [IoT Documentation](./ingest-data/for-iot/overview.md) provides comprehensive guidance on ingesting data from diverse sources. + +## Querying Data for Insights + +GreptimeDB offers robust interfaces for [querying data](./query-data/overview.md). + +### SQL Support + +You can use SQL for range queries, aggregations, and more. +For detailed instructions, see the [SQL Query Documentation](./query-data/sql.md). + +### Prometheus Query Language (PromQL) + +GreptimeDB supports PromQL for querying data. Refer to the [PromQL Documentation](./query-data/promql.md) for guidance. + +### Flow Computation + +For real-time data processing and analysis, GreptimeDB provides [Flow Computation](./flow-computation/overview.md), enabling complex computations on data streams. + +## Accelerating Queries with Indexes + +Indexes such as inverted indexes, skipping indexes, and full-text indexes can significantly enhance query performance. +Learn more about effectively using these indexes in the [Data Index Documentation](./manage-data/data-index.md). + +## Migrating to GreptimeDB from Other Databases + +Migrating data from other databases to GreptimeDB is straightforward. +Follow the step-by-step instructions in the [Migration Documentation](./migrate-to-greptimedb/overview.md). + +## Administering and Deploying GreptimeDB + +When you're ready to deploy GreptimeDB, consult the [Deployment & Administration Documentation](/user-guide/deployments-administration/overview.md) for detailed guidance on deployment and management. + diff --git a/versioned_docs/version-1.0/user-guide/protocols/elasticsearch.md b/versioned_docs/version-1.0/user-guide/protocols/elasticsearch.md new file mode 100644 index 0000000000..b8a6105d85 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/protocols/elasticsearch.md @@ -0,0 +1,8 @@ +--- +keywords: [Elasticsearch, log storage, API, configuration, data model] +description: Use Elasticsearch protocol to ingest log data. +--- + +# Elasticsearch + +Please refer to [Ingest Data with Elasticsearch](/user-guide/ingest-data/for-observability/elasticsearch.md) for detailed information. \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/protocols/grpc.md b/versioned_docs/version-1.0/user-guide/protocols/grpc.md new file mode 100644 index 0000000000..deea831b1b --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/protocols/grpc.md @@ -0,0 +1,10 @@ +--- +keywords: [gRPC SDKs, data ingestion, high-performance, create SDK] +description: Overview of using gRPC SDKs for efficient and high-performance data ingestion in GreptimeDB. +--- + +# gRPC + +GreptimeDB offers [gRPC SDKs](/user-guide/ingest-data/for-iot/grpc-sdks/overview.md) for efficient and high-performance data ingestion. + +If there is no SDK available for your programming language, you have the option to [create your own SDK](/contributor-guide/how-to/how-to-write-sdk.md) by following the guidelines provided in the contributor guide. diff --git a/versioned_docs/version-1.0/user-guide/protocols/http.md b/versioned_docs/version-1.0/user-guide/protocols/http.md new file mode 100644 index 0000000000..171237c8c6 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/protocols/http.md @@ -0,0 +1,617 @@ +--- +keywords: [HTTP API, authentication, timeout settings, health checks, configuration, SQL queries] +description: Guide on using HTTP APIs to interact with GreptimeDB, including authentication, timeout settings, health checks, configuration, and SQL queries. +--- + +# HTTP API + +GreptimeDB provides HTTP APIs for interacting with the database. For a complete list of available APIs, please refer to the [HTTP Endpoint](/reference/http-endpoints.md). + +## Base URL + +The base URL of API is `http(s)://{{host}}:{{port}}/`. + +- For the GreptimeDB instance running on the local machine, + with default port configuration `4000`, + the base URL is `http://localhost:4000/`. + You can change the server host and port in the [configuration](/user-guide/deployments-administration/configuration.md#protocol-options) file. + +- For GreptimeCloud, the base URL is `https://{{host}}/`. + You can find the host in 'Connection Information' at the GreptimeCloud console. + +In the following sections, we use `http://{{API-host}}/` as the base URL to demonstrate the API usage. + +## Common headers + +### Authentication + +Assume that you have already configured the database [authentication](/user-guide/deployments-administration/authentication/overview.md) correctly, +GreptimeDB supports the built-in `Basic` authentication scheme in the HTTP API. To set up authentication, follow these steps: + +1. Encode your username and password using the `:` format and the `Base64` algorithm. +2. Attach your encoded credentials to the one of the following HTTP header: +- `Authorization: Basic ` +- `x-greptime-auth: Basic ` + +Here's an example. If you want to connect to GreptimeDB using the username `greptime_user` and password `greptime_pwd`, use the following command: + +```shell +curl -X POST \ +-H 'Authorization: Basic Z3JlcHRpbWVfdXNlcjpncmVwdGltZV9wd2Q=' \ +-H 'Content-Type: application/x-www-form-urlencoded' \ +-d 'sql=show tables' \ +http://localhost:4000/v1/sql +``` + +In this example, `Z3JlcHRpbWVfdXNlcjpncmVwdGltZV9wd2Q=` represents the Base64-encoded value of `greptime_user:greptime_pwd`. Make sure to replace it with your own configured username and password, and encode them using Base64. + +:::tip NOTE +InfluxDB uses its own authentication format, see [InfluxDB](./influxdb-line-protocol.md) for details. +::: + +### Timeout + +GreptimeDB supports the `X-Greptime-Timeout` header in HTTP requests. +It is used to specify the timeout for the request running in the database server. + +For example, the following request set `120s` timeout for the request: + +```bash +curl -X POST \ +-H 'Authorization: Basic {{authentication}}' \ +-H 'X-Greptime-Timeout: 120s' \ +-H 'Content-Type: application/x-www-form-urlencoded' \ +-d 'sql=show tables' \ +http://localhost:4000/v1/sql +``` + +## Admin APIs + +:::tip NOTE +These endpoint cannot be used in GreptimeCloud. +::: + +Please refer to the [Admin APIs](/reference/http-endpoints.md#admin-apis) documentation for more information. + + +## POST SQL statements + +To submit a SQL query to the GreptimeDB server via HTTP API, use the following format: + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authentication}}' \ + -H 'X-Greptime-Timeout: {{time precision}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d 'sql={{SQL-statement}}' \ +http://{{API-host}}/v1/sql +``` + +### Headers + +- [`Authorization`](#authentication) +- [`X-Greptime-Timeout`](#timeout) +- `Content-Type`: `application/x-www-form-urlencoded`. +- `X-Greptime-Timezone`: The time zone for the current SQL query. Optional. Please refer to [time zone](#time-zone). + +### Query string parameters + +- `db`: The database name. Optional. If not provided, the default database `public` will be used. +- `format`: The output format. Optional. `greptimedb_v1` by default. + In addition to the default JSON format, the HTTP API also allows you to + customize output format by providing the `format` query parameter with following + values: + - `influxdb_v1`: [influxdb query + API](https://docs.influxdata.com/influxdb/v1/tools/api/#query-http-endpoint) + compatible format. Additional parameters: + - `epoch`: `[ns,u,µ,ms,s,m,h]`, returns epoch timestamps with the specified + precision + - `csv`: outputs as comma-separated values + - `csvWithNames`: outputs as comma-separated values with a column names header + - `csvWithNamesAndTypes`: outputs as comma-separated values with column names and data types headers + - `arrow`: [Arrow IPC + format](https://arrow.apache.org/docs/python/feather.html). Additional + parameters: + - `compression`: `zstd` or `lz4`, default: no compression + - `table`: ASCII table format for console output + - `null`: Concise text-only output of the row count and elapsed time, useful for evaluating query performance. + +### Body + +- `sql`: The SQL statement. Required. + +### Response + +The response is a JSON object containing the following fields: + +- `output`: The SQL executed result. Please refer to the examples blow to see the details. +- `execution_time_ms`: The execution time of the statement in milliseconds. + +### Examples + +#### `INSERT` statement + +For example, to insert data into the `monitor` table of database `public`, use the following command: + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d 'sql=INSERT INTO monitor VALUES ("127.0.0.1", 1667446797450, 0.1, 0.4), ("127.0.0.2", 1667446798450, 0.2, 0.3), ("127.0.0.1", 1667446798450, 0.5, 0.2)' \ + http://localhost:4000/v1/sql?db=public +``` + +The response will contain the number of affected rows: + +```shell +{"output":[{"affectedrows":3}],"execution_time_ms":11} +``` + +#### `SELECT` statement + +You can also use the HTTP API to execute other SQL statements. +For example, to retrieve data from the `monitor` table: + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql?db=public +``` + +The response will contain the queried data in JSON format: + +```json +{ + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "host", + "data_type": "String" + }, + { + "name": "ts", + "data_type": "TimestampMillisecond" + }, + { + "name": "cpu", + "data_type": "Float64" + }, + { + "name": "memory", + "data_type": "Float64" + } + ] + }, + "rows": [ + [ + "127.0.0.1", + 1720728000000, + 0.5, + 0.1 + ] + ], + "total_rows": 1 + } + } + ], + "execution_time_ms": 7 +} +``` + +The response contains the following fields: + +- `output`: The execution result. + - `records`: The query result. + - `schema`: The schema of the result, including the schema of each column. + - `rows`: The rows of the query result, where each row is an array containing the corresponding values of the columns in the schema. +- `execution_time_ms`: The execution time of the statement in milliseconds. + +#### Time zone + +GreptimeDB supports the `X-Greptime-Timezone` header in HTTP requests. +It is used to specify the timezone for the current SQL query. + +For example, the following request uses the time zone `+1:00` for the query: + +```bash +curl -X POST \ +-H 'Authorization: Basic {{authentication}}' \ +-H 'X-Greptime-Timezone: +1:00' \ +-H 'Content-Type: application/x-www-form-urlencoded' \ +-d 'sql=SHOW VARIABLES time_zone;' \ +http://localhost:4000/v1/sql +``` + +After the query, the result will be: + +```json +{ + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "TIME_ZONE", + "data_type": "String" + } + ] + }, + "rows": [ + [ + "+01:00" + ] + ] + } + } + ], + "execution_time_ms": 27 +} +``` + +For information on how the time zone affects data inserts and queries, please refer to the SQL documents in the [Ingest Data](../ingest-data/for-iot/sql.md#time-zone) and [Query Data](../query-data/sql.md#time-zone) sections. + +#### Query data with `table` format output + +You can use the `table` format in the query string parameters to get the output in ASCII table format. + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql?db=public&format=table +``` + +Output + +``` +┌─host────────┬─ts────────────┬─cpu─┬─memory─┐ +│ "127.0.0.1" │ 1667446797450 │ 0.1 │ 0.4 │ +│ "127.0.0.1" │ 1667446798450 │ 0.5 │ 0.2 │ +│ "127.0.0.2" │ 1667446798450 │ 0.2 │ 0.3 │ +└─────────────┴───────────────┴─────┴────────┘ +``` + + +#### Query data with `csvWithNames` format output + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql?db=public&format=csvWithNames +``` + +Output: +```csv +host,ts,cpu,memory +127.0.0.1,1667446797450,0.1,0.4 +127.0.0.1,1667446798450,0.5,0.2 +127.0.0.2,1667446798450,0.2,0.3 +``` + +Changes `format` to `csvWithNamesAndTypes`: +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql?db=public&format=csvWithNamesAndTypes +``` + +Output: +```csv +host,ts,cpu,memory +String,TimestampMillisecond,Float64,Float64 +127.0.0.1,1667446797450,0.1,0.4 +127.0.0.1,1667446798450,0.5,0.2 +127.0.0.2,1667446798450,0.2,0.3 +``` + +#### Query data with `influxdb_v1` format output + +You can use the `influxdb_v1` format in the query string parameters to get the output in InfluxDB query API compatible format. + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql?db=public&format=influxdb_v1&epoch=ms +``` + +```json +{ + "results": [ + { + "statement_id": 0, + "series": [ + { + "name": "", + "columns": [ + "host", + "cpu", + "memory", + "ts" + ], + "values": [ + [ + ["127.0.0.1", 0.1, 0.4, 1667446797450], + ["127.0.0.1", 0.5, 0.2, 1667446798450], + ["127.0.0.2", 0.2, 0.3, 1667446798450] + ] + ] + } + ] + } + ], + "execution_time_ms": 2 +} +``` + +### Parse SQL with GreptimeDB's SQL dialect + +To parse and understand queries written in GreptimeDB's SQL dialect for tools like dashboards, etc., you can use the `/v1/sql/parse` endpoint to obtain the structured result of an SQL query: + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d "sql=SELECT * FROM monitor" \ + http://localhost:4000/v1/sql/parse +``` + +```json +[ + { + "Query": { + "inner": { + "with": null, + "body": { + "Select": { + "distinct": null, + "top": null, + "top_before_distinct": false, + "projection": [ + { + "Wildcard": { + "opt_ilike": null, + "opt_exclude": null, + "opt_except": null, + "opt_replace": null, + "opt_rename": null + } + } + ], + "into": null, + "from": [ + { + "relation": { + "Table": { + "name": [ + { + "value": "monitor", + "quote_style": null + } + ], + "alias": null, + "args": null, + "with_hints": [], + "version": null, + "with_ordinality": false, + "partitions": [] + } + }, + "joins": [] + } + ], + "lateral_views": [], + "prewhere": null, + "selection": null, + "group_by": { + "Expressions": [ + [], + [] + ] + }, + "cluster_by": [], + "distribute_by": [], + "sort_by": [], + "having": null, + "named_window": [], + "qualify": null, + "window_before_qualify": false, + "value_table_mode": null, + "connect_by": null + } + }, + "order_by": null, + "limit": null, + "limit_by": [], + "offset": null, + "fetch": null, + "locks": [], + "for_clause": null, + "settings": null, + "format_clause": null + } + } + } +] +``` + +## POST PromQL queries + +### The API returns Prometheus query result format + +GreptimeDB compatible with Prometheus query language (PromQL) and can be used to query data in GreptimeDB. +For all the compatible APIs, please refer to the [Prometheus Query Language](/user-guide/query-data/promql#prometheus-http-api) documentation. + +### The API returns GreptimeDB JSON format + +GreptimeDB also exposes an custom HTTP API for querying with PromQL, and returning +GreptimeDB's data frame output. You can find it on `/promql` path under the +current stable API version `/v1`. +The return value of this API is in GreptimeDB's JSON format, not Prometheus's format. +For example: + +```shell +curl -X GET \ + -H 'Authorization: Basic {{authorization if exists}}' \ + -G \ + --data-urlencode 'query=avg(system_metrics{idc="idc_a"})' \ + --data-urlencode 'start=1667446797' \ + --data-urlencode 'end=1667446799' \ + --data-urlencode 'step=1s' \ + 'http://localhost:4000/v1/promql?db=public' +``` + +The input parameters are similar to the [`range_query`](https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries) in Prometheus' HTTP API: + +- `db=`: Required when using GreptimeDB with authorization, otherwise can be omitted if you are using the default `public` database. Note this parameter should bet set in the query param, or using a HTTP header `--header 'x-greptime-db-name: '`. +- `query=`: Required. Prometheus expression query string. +- `start=`: Required. The start timestamp, which is inclusive. It is used to set the range of time in `TIME INDEX` column. +- `end=`: Required. The end timestamp, which is inclusive. It is used to set the range of time in `TIME INDEX` column. +- `step=`: Required. Query resolution step width in duration format or float number of seconds. +- `format`: The output format. Optional. `greptimedb_v1` by default. + In addition to the default JSON format, the HTTP API also allows you to + customize output format by providing the `format` query parameter with following + values: + - `influxdb_v1`: [influxdb query + API](https://docs.influxdata.com/influxdb/v1/tools/api/#query-http-endpoint) + compatible format. Additional parameters: + - `epoch`: `[ns,u,µ,ms,s,m,h]`, returns epoch timestamps with the specified + precision + - `csv`: outputs as comma-separated values + - `csvWithNames`: outputs as comma-separated values with a column names header + - `csvWithNamesAndTypes`: outputs as comma-separated values with column names and data types headers + - `arrow`: [Arrow IPC + format](https://arrow.apache.org/docs/python/feather.html). Additional + parameters: + - `compression`: `zstd` or `lz4`, default: no compression + - `table`: ASCII table format for console output + - `null`: Concise text-only output of the row count and elapsed time, useful for evaluating query performance. + + +Here are some examples for each type of parameter: + +- rfc3339 + - `2015-07-01T20:11:00Z` (default to seconds resolution) + - `2015-07-01T20:11:00.781Z` (with milliseconds resolution) + - `2015-07-02T04:11:00+08:00` (with timezone offset) +- unix timestamp + - `1435781460` (default to seconds resolution) + - `1435781460.781` (with milliseconds resolution) +- duration + - `1h` (1 hour) + - `5d1m` (5 days and 1 minute) + - `2` (2 seconds) + - `2s` (also 2 seconds) + +The result format is the same as `/sql` interface described in [Post SQL statements](#post-sql-statements) section. + +```json +{ + "code": 0, + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "ts", + "data_type": "TimestampMillisecond" + }, + { + "name": "AVG(system_metrics.cpu_util)", + "data_type": "Float64" + }, + { + "name": "AVG(system_metrics.memory_util)", + "data_type": "Float64" + }, + { + "name": "AVG(system_metrics.disk_util)", + "data_type": "Float64" + } + ] + }, + "rows": [ + [ + 1667446798000, + 80.1, + 70.3, + 90 + ], + [ + 1667446799000, + 80.1, + 70.3, + 90 + ] + ] + } + } + ], + "execution_time_ms": 5 +} +``` + +## Post Influxdb line protocol data + + + + + +```shell +curl -X POST \ + -H 'Authorization: token {{username:password}}' \ + -d '{{Influxdb-line-protocol-data}}' \ + http://{{API-host}}/v1/influxdb/api/v2/write?precision={{time-precision}} +``` + + + + + +```shell +curl -X POST \ + -d '{{Influxdb-line-protocol-data}}' \ + http://{{API-host}}/v1/influxdb/api/v1/write?u={{username}}&p={{password}}&precision={{time-precision}} +``` + + + + +### Headers + +- `Authorization`: **Unlike other APIs**, the InfluxDB line protocol APIs use the InfluxDB authentication format. For V2, it is `token {{username:password}}`. + +### Query string parameters + +- `u`: The username. Optional. It is the authentication username for V1. +- `p`: The password. Optional. It is the authentication password for V1. +- `db`: The database name. Optional. The default value is `public`. +- `precision`: Defines the precision of the timestamp provided in the request body. Please refer to [InfluxDB Line Protocol](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md) in the user guide. + +### Body + +The InfluxDB line protocol data points. Please refer to the [InfluxDB Line Protocol](https://docs.influxdata.com/influxdb/v1/write_protocols/line_protocol_tutorial/#syntax) document. + +### Examples + +Please refer to [InfluxDB Line Protocol](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md) in the user guide. + +## API for managing Pipelines + +When writing logs to GreptimeDB, +you can use HTTP APIs to manage the pipelines. +For detailed information, +please refer to the [Manage Pipelines](/user-guide/logs/manage-pipelines.md) documentation. diff --git a/versioned_docs/version-1.0/user-guide/protocols/influxdb-line-protocol.md b/versioned_docs/version-1.0/user-guide/protocols/influxdb-line-protocol.md new file mode 100644 index 0000000000..8545bbd65e --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/protocols/influxdb-line-protocol.md @@ -0,0 +1,42 @@ +--- +keywords: [InfluxDB Line Protocol, data ingestion, ping API, health API] +description: Instructions on ingesting data to GreptimeDB using InfluxDB Line Protocol and using ping and health APIs. +--- + +# InfluxDB Line Protocol + +## Ingest data + +For how to ingest data to GreptimeDB using InfluxDB Line Protocol, +please refer to the [Ingest Data](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md) document. + +## HTTP API + +Please refer to the [HTTP API](http.md#post-influxdb-line-protocol-data) document for details on the InfluxDB Line Protocol API. + +## PING + +Additionally, GreptimeDB also provides support for the `ping` and `health` APIs of InfluxDB. + +Use `curl` to request `ping` API. + +```shell +curl -i "127.0.0.1:4000/v1/influxdb/ping" +``` + +```shell +HTTP/1.1 204 No Content +date: Wed, 22 Feb 2023 02:29:44 GMT +``` + +Use `curl` to request `health` API. + +```shell +curl -i "127.0.0.1:4000/v1/influxdb/health" +``` + +```shell +HTTP/1.1 200 OK +content-length: 0 +date: Wed, 22 Feb 2023 02:30:46 GMT +``` diff --git a/versioned_docs/version-1.0/user-guide/protocols/loki.md b/versioned_docs/version-1.0/user-guide/protocols/loki.md new file mode 100644 index 0000000000..3a993a9c26 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/protocols/loki.md @@ -0,0 +1,8 @@ +--- +keywords: [Loki, log storage, API, configuration, data model] +description: Learn how to ingest data with Loki. +--- + +# Loki + +Please refer to [Ingest Data with Loki](/user-guide/ingest-data/for-observability/loki.md) for detailed information. \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/protocols/mysql.md b/versioned_docs/version-1.0/user-guide/protocols/mysql.md new file mode 100644 index 0000000000..debe1254cd --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/protocols/mysql.md @@ -0,0 +1,92 @@ +--- +keywords: [MySQL connection, table management, data ingestion, querying data, time zones] +description: Guide on connecting to GreptimeDB using MySQL, managing tables, ingesting and querying data, and handling time zones. +--- + +# MySQL + +## Connect + +You can connect to GreptimeDB using MySQL via port `4002`. + +```shell +mysql -h -P 4002 -u -p +``` + +- For how to setup username and password for GreptimeDB, please refer to [Authentication](/user-guide/deployments-administration/authentication/overview.md). +- If you want to use other ports for MySQL, please refer to [Protocol options](/user-guide/deployments-administration/configuration.md#protocol-options) in the configuration document. + + +## Table management + +Please refer to [Table Management](/user-guide/deployments-administration/manage-data/basic-table-operations.md). + +## Ingest data + +Please refer to [SQL](/user-guide/ingest-data/for-iot/sql.md). + +## Query data + +Please refer to [SQL](/user-guide/query-data/sql.md). + +## Time zone + +GreptimeDB's MySQL protocol interface follows original MySQL on [how to +deal with time zone](https://dev.mysql.com/doc/refman/8.0/en/time-zone-support.html). + +By default, MySQL uses its server time zone for timestamp. To override, you can +set `time_zone` variable for current session using SQL statement `SET time_zone = '';`. +The value of `time_zone` can be any of: + +- The server's time zone: `SYSTEM`. +- Offset to UTC such as `+08:00`. +- Any named time zone like `Europe/Berlin`. + +Some MySQL clients, such as Grafana MySQL data source, allow you to set the time zone for the current session. +You can also use the above values when setting the time zone. + +You can use `SELECT` to check the current time zone settings. For example: + +```sql +SELECT @@system_time_zone, @@time_zone; +``` + +The result shows that both the system time zone and the session time zone are set to `UTC`: + +```SQL ++--------------------+-------------+ +| @@system_time_zone | @@time_zone | ++--------------------+-------------+ +| UTC | UTC | ++--------------------+-------------+ +``` + +Change the session time zone to `+1:00`: + +```SQL +SET time_zone = '+1:00' +``` + +Then you can see the difference between the system time zone and the session time zone: + +```SQL +SELECT @@system_time_zone, @@time_zone; + ++--------------------+-------------+ +| @@system_time_zone | @@time_zone | ++--------------------+-------------+ +| UTC | +01:00 | ++--------------------+-------------+ +``` + +For information on how the time zone affects data inserts and queries, please refer to the SQL documents in the [Ingest Data](/user-guide/ingest-data/for-iot/sql.md#time-zone) and [Query Data](/user-guide/query-data/sql.md#time-zone) sections. + +## Query Timeout + +You can set the `max_execution_time` variable for the current session using SQL statement `SET max_execution_time = ` or `SET MAX_EXECUTION_TIME = `, which specifies the maximum time in milliseconds for a **read-only statement** to execute. The server will terminate the query if it exceeds the specified time. + +For example, to set the maximum query execution time to 10 seconds: + +```SQL +SET max_execution_time=10000; +``` diff --git a/versioned_docs/version-1.0/user-guide/protocols/opentelemetry.md b/versioned_docs/version-1.0/user-guide/protocols/opentelemetry.md new file mode 100644 index 0000000000..35ad743f05 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/protocols/opentelemetry.md @@ -0,0 +1,9 @@ +--- +keywords: [OpenTelemetry, OTLP] +description: Consume OpenTelemetry Metrics natively via OTLP/HTTP protocol +--- + +# OpenTelemetry (OTLP) + +GreptimeDB is an observability backend to consume OpenTelemetry Metrics natively via [OTLP/HTTP](https://opentelemetry.io/docs/specs/otlp/#otlphttp) protocol. +Please refer to the [Ingest Data with OpenTelemetry](/user-guide/ingest-data/for-observability/opentelemetry.md) document for detailed information. diff --git a/versioned_docs/version-1.0/user-guide/protocols/opentsdb.md b/versioned_docs/version-1.0/user-guide/protocols/opentsdb.md new file mode 100644 index 0000000000..d8e74e4809 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/protocols/opentsdb.md @@ -0,0 +1,3 @@ +# OpenTSDB + +Please refer to [Ingest Data with OpenTSDB](/user-guide/ingest-data/for-iot/opentsdb.md) for detailed information. diff --git a/versioned_docs/version-1.0/user-guide/protocols/overview.md b/versioned_docs/version-1.0/user-guide/protocols/overview.md new file mode 100644 index 0000000000..6633f234f0 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/protocols/overview.md @@ -0,0 +1,10 @@ +--- +keywords: [InfluxDB Line Protocol, OpenTelemetry, MySQL, PostgreSQL, HTTP API, gRPC, OpenTSDB, Loki] +description: Overview of supported protocols for data ingestion. +--- + +import DocCardList from '@theme/DocCardList'; + +# Protocols + + diff --git a/versioned_docs/version-1.0/user-guide/protocols/postgresql.md b/versioned_docs/version-1.0/user-guide/protocols/postgresql.md new file mode 100644 index 0000000000..50f5495fb7 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/protocols/postgresql.md @@ -0,0 +1,188 @@ +--- +keywords: [pg, pgsql, PostgreSQL connection, table management, data ingestion, querying data, time zones, foreign data wrapper] +description: Guide on connecting to GreptimeDB using PostgreSQL, managing tables, ingesting and querying data, and handling time zones. +--- + +# PostgreSQL + +## Connect + +You can connect to GreptimeDB using PostgreSQL via port `4003`. +Simply add the `-U` argument to your command, followed by your username and password. Here's an example: + +```shell +psql -h -p 4003 -U -d public +``` + +- For how to setup username and password for GreptimeDB, please refer to [Authentication](/user-guide/deployments-administration/authentication/overview.md). +- If you want to use other ports for PostgreSQL, please refer to [Protocol options](/user-guide/deployments-administration/configuration.md#protocol-options) in the configuration document. + + +## Table management + +Please refer to [Table Management](/user-guide/deployments-administration/manage-data/basic-table-operations.md). + +## Ingest data + +Please refer to [SQL](/user-guide/ingest-data/for-iot/sql.md). + +## Query data + +Please refer to [SQL](/user-guide/query-data/sql.md). + +## Time zone + +GreptimeDB's PostgreSQL protocol interface follows original PostgreSQL on [datatype-timezones](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-TIMEZONES). + +By default, PostgreSQL uses its server time zone for timestamp. To override, you can +set `time_zone` variable for current session using SQL statement `SET TIMEZONE TO '';`. +The value of `time_zone` can be any of: + +- A full time zone name, for example `America/New_York`. +- A time zone abbreviation, for example `PST`. +- Offset to UTC such as `+08:00`. + +You can use `SHOW` to check the current time zone settings. For example: + +```sql +SHOW VARIABLES time_zone; +``` + +```sql + TIME_ZONE +----------- + UTC +``` + +Change the session time zone to `+1:00`: + +```SQL +SET TIMEZONE TO '+1:00' +``` + +For information on how the time zone affects data inserts and queries, please refer to the SQL documents in the [Ingest Data](/user-guide/ingest-data/for-iot/sql.md#time-zone) and [Query Data](/user-guide/query-data/sql.md#time-zone) sections. + +## Foreign Data Wrapper + +GreptimeDB can be configured as a foreign data server for Postgres' built-in +[FDW extension](https://www.postgresql.org/docs/current/postgres-fdw.html). This +allows user to query GreptimeDB tables seamlessly from Postgres server. It's +also possible to join Postgres tables with GreptimeDB tables. + +For example, your IoT metadata, like device information, is stored in a +relational data model in Postgres. It's possible to use filter queries to find +out device IDs and join with time-series data from GreptimeDB. + +### Setup + +To setup GreptimeDB for Postgres FDW, make sure you enabled postgres protocol +support in GreptimeDB and it's accessible from your Postgres server. + +To create and configuration GreptimeDB in Postgres, first enable the +`postgres_fdw` extension. + +```sql +CREATE EXTENSION postgres_fdw; +``` + +Add GreptimeDB instance as remote server. + +```sql +CREATE SERVER greptimedb +FOREIGN DATA WRAPPER postgres_fdw +OPTIONS (host 'greptimedb_host', dbname 'public', port '4003'); +``` + +Configure user mapping for Postgres user and GreptimeDB user. This step is +required. But if you don't have authentication enabled in GreptimeDB OSS +version, just fill the credential with random data. + +```sql +CREATE USER MAPPING FOR postgres +SERVER greptimedb +OPTIONS (user 'greptime', password '...'); +``` + +Create foreign table in Postgres to map GreptimeDB's schema. Note that you will +need to use Postgres' corresponding data types for GreptimeDB's. + +For GreptimeDB's tables + +```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'); + +CREATE TABLE app_logs ( + ts TIMESTAMP TIME INDEX, + host STRING, + api_path STRING FULLTEXT INDEX, + log_level STRING, + log STRING FULLTEXT INDEX, + PRIMARY KEY (host, log_level) +) with('append_mode'='true'); +``` + +The foreign table DDL is like this. You need to run them in Postgres to create +these tables; + +```sql +CREATE FOREIGN TABLE ft_grpc_latencies ( + ts TIMESTAMP, + host VARCHAR, + method_name VARCHAR, + latency DOUBLE precision +) +SERVER greptimedb +OPTIONS (table_name 'grpc_latencies'); + +CREATE FOREIGN TABLE ft_app_logs ( + ts TIMESTAMP, + host VARCHAR, + api_path VARCHAR, + log_level VARCHAR, + log VARCHAR +) +SERVER greptimedb +OPTIONS (table_name 'app_logs'); +``` + +To help you to generate statements in Postgres, we enhanced `SHOW CREATE TABLE` +in GreptimeDB to dump the Postgres DDL for you. For example: + +```sql +SHOW CREATE TABLE grpc_latencies FOR postgres_foreign_table; +``` + +Note that you will need to replace server name `greptimedb` with the name you +defined in `CREATE SERVER` statement. + +### Run Queries + +You can now send query from Postgres. It's also possible to use functions that +are available in both Postgres and GreptimeDB, like `date_trunc`. + +```sql +SELECT * FROM ft_app_logs ORDER BY ts DESC LIMIT 100; + +SELECT + date_trunc('MINUTE', ts) as t, + host, + avg(latency), + count(latency) +FROM ft_grpc_latencies GROUP BY host, t; +``` + +## Statement Timeout + +You can set the `statement_timeout` variable for the current session using SQL statement `SET statement_timeout = ` or `SET STATEMENT_TIMEOUT = `, which specifies the maximum time in milliseconds for a statement to execute. The server will terminate the statement if it exceeds the specified time. + +For example, to set the maximum execution time to 10 seconds: + +```SQL +SET statement_timeout=10000; +``` diff --git a/versioned_docs/version-1.0/user-guide/python-scripts/api.md b/versioned_docs/version-1.0/user-guide/python-scripts/api.md new file mode 100644 index 0000000000..4cae539a48 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/python-scripts/api.md @@ -0,0 +1,93 @@ +# API + +## Builtin modules and functions + +We provide a wide range of built-in functions for users to use. The following is a list of built-in functions. Simply write `import greptime` or `from greptime import *` at the beginning of your script to use them. + +## Vector functions + +| Function | Description | +| :--- | :--- | +| `pow(v0, v1)` | Raise a number `v0` to a power of `v1`. | +| `clip(v0, v1, v2)` | Clip all elements in a vector `v0` to a range between vectors `v1` and `v2`. | +| `diff(v0)` | Calculate the difference between adjacent elements in a vector `v0`. | +| `mean(v0)` | Calculate the mean of a vector `v0`. | +| `polyval(v0, v1)` | Evaluate a polynomial `v0` at points `v1`. similar to `numpy.polyval`. | +| `argmax(v0)` | Return the index of the maximum value in a vector `v0`. similar to `numpy.argmax`. | +| `argmin(v0)` | Return the index of the minimum value in a vector `v0`. similar to `numpy.argmin`. | +| `percentile` | Calculate the `q`-th percentile of a vector `v0`. similar to `numpy.percentile`. | +| `scipy_stats_norm_cdf` | Calculate the cumulative distribution function for the normal distribution. similar to `scipy.stats.norm.cdf`. | +| `scipy_stats_norm_pdf` | Calculate the probability density function for the normal distribution. similar to `scipy.stats.norm.pdf`. | + +## Math functions + +| Function | Description | +| :--- | :--- | +| `sqrt(v)` | Calculate the square root of a number `v`. | +| `sin(v)` | Calculate the sine of a number `v`. | +| `cos(v)` | Calculate the cosine of a number `v`. | +| `tan(v)` | Calculate the tangent of a number `v`. | +| `asin(v)` | Calculate the arcsine of a number `v`. | +| `acos(v)` | Calculate the arccosine of a number `v`. | +| `atan(v)` | Calculate the arctangent of a number `v`. | +| `floor(v)` | Calculate the floor of a number `v`. | +| `ceil(v)` | Calculate the ceiling of a number `v`. | +| `round(v)` | Calculate the nearest integer of a number `v`. | +| `trunc(v)` | Calculate the truncated integer of a number `v`. | +| `abs(v)` | Calculate the absolute value of a number `v`. | +| `signum(v)` | Calculate the sign(gives 1.0/-1.0) of a number `v`. | +| `exp(v)` | Calculate the exponential of a number `v`. | +| `ln(v)` | Calculate the natural logarithm of a number `v`. | +| `log2(v)` | Calculate the base-2 logarithm of a number `v`. | +| `log10(v)` | Calculate the base-10 logarithm of a number `v`. | + +## Utility functions & Aggregation functions + +These Functions are bound from `DataFusion` +| Function | Description | +| :--- | :--- | +| `random(len)` | Generate a random vector with length `len`. | +| `approx_distinct(v0)` | Calculate the approximate number of distinct values in a vector `v0`. | +| `median(v0)` | Calculate the median of a vector `v0`. | +| `approx_percentile_cont(values, percent)` | Calculate the approximate percentile of a vector `values` at a given percentage `percent`. | +| `array_agg(v0)` | Aggregate values into an array. | +| `avg(v0)` | Calculate the average of a vector `v0`. | +| `correlation(v0, v1)` | Calculate the Pearson correlation coefficient of a vector `v0` and a vector `v1`. | +| `count(v0)` | Calculate the count of a vector `v0`. | +| `covariance(v0, v1)` | Calculate the covariance of a vector `v0` and a vector `v1`. | +| `covariance_pop(v0, v1)` | Calculate the population covariance of a vector `v0` and a vector `v1`. | +| `max(v0)` | Calculate the maximum of a vector `v0`. | +| `min(v0)` | Calculate the minimum of a vector `v0`. | +| `stddev(v0)` | Calculate the sample standard deviation of a vector `v0`. | +| `stddev_pop(v0)` | Calculate the population standard deviation of a vector `v0`. | +| `sum(v0)` | Calculate the sum of a vector `v0`. | +| `variance(v0)` | Calculate the sample variance of a vector `v0`. | +| `variance_pop(v0)` | Calculate the population variance of a vector `v0`. | + +## DataFrame's methods + +| Method | Description | +| --- | --- | +| `select_columns(columns: List[str])` | select columns from DataFrame | +| `select(columns: List[Expr]])` | select columns from DataFrame using `PyExpr` | +| `filter(condition: Expr)` | filter DataFrame using `PyExpr` | +| `aggregate(group_expr: List[Expr], aggr_expr: List[Expr])` | Perform an aggregate query with optional grouping expressions. | +| `limit(skip: int, fetch: Optional[int])` |Limit the number of rows returned from this DataFrame. `skip` - Number of rows to skip before fetch any row; `fetch` - Maximum number of rows to fetch, after skipping skip rows. +| `union(other: DataFrame)` | Union two DataFrame | +| `union_distinct(other: DataFrame)` | Union two DataFrame, but remove duplicate rows | +| `distinct()` | Remove duplicate rows | +| `sort(expr: List[Expr])` | Sort DataFrame by `PyExpr`, Sort the DataFrame by the specified sorting expressions. Any expression can be turned into a sort expression by calling its sort method. | +| `join(right: DataFrame, left_cols: List[str], right_cols: List[str], filter: Optional[Expr])` | Join two DataFrame using the specified columns as join keys. Eight Join Types are supported: `inner`, `left`, `right`, `full`, `leftSemi`, `leftAnti`, `rightSemi`, `rightAnti`. | +| `intersect(other: DataFrame)` | Intersect two DataFrame | +| `except(other: DataFrame)` | Except two DataFrame | +| `collect()` | Collect DataFrame to a list of `PyVector` | + +## Expr's methods + +| Method | Description | +| --- | --- | +| `col(name: str)` | Create a `PyExpr` that represents a column | +| `lit(value: Any)` | Create a `PyExpr` that represents a literal value | +| `sort(ascending: bool, null_first: bool)` | Create a `PyExpr` that represents a sort expression | +| comparison operators: `==`, `!=`, `>`, `>=`, `<`, `<=` | Create `PyExpr` from compare two `PyExpr` | +| logical operators: `&`, `\|`, `~` | Create `PyExpr` from logical operation between two `PyExpr` | diff --git a/versioned_docs/version-1.0/user-guide/python-scripts/data-types.md b/versioned_docs/version-1.0/user-guide/python-scripts/data-types.md new file mode 100644 index 0000000000..f6c437ce87 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/python-scripts/data-types.md @@ -0,0 +1,184 @@ +# Data Types + +## DataFrame + +A DataFrame represents a logical set of rows with the same named columns, similar to a [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) or [Spark DataFrame](https://spark.apache.org/docs/latest/sql-programming-guide.html). + +You can create a dataframe from `sql`: + +```python +from greptime import PyDataFrame, col +@copr(returns = ["value"]) +def query_numbers() -> vector[f64]: + df = PyDataFrame.from_sql("select number from numbers") + return df.filter(col('number') <= 5).collect()[0] +``` + +It's the same as `select number from numbers where number <=5`, but uses dataframe API. + +In fact, the coprocessor's dataframe API is a wrapper of Apache Datafusion [DataFrame API](https://arrow.apache.org/datafusion/user-guide/dataframe.html). Please refer to [API](api.md) document to get the full DataFrame API. + +## Vector + +The vector is the major data type in Coprocessor, it's a vector of values in the same type. Usually, it comes from extracting a column from the query result, but you can also construct it in the python script. + +The vector is like the array type in the programming language, `Array` in Apache [Arrow](https://arrow.apache.org/) or `NDArray` in [NumPy](https://numpy.org/doc/stable/reference/arrays.html). + +### Vector Types + +The Coprocessor Engine supports the following vector types: + +| Type | Description | +|---|---| +| `vector[str]` | The string type | +| `vector[bool]` | The boolean type | +| `vector[u8]`| The 8-bit unsigned integer type | +| `vector[u16]` | The 16-bit unsigned integer type | +| `vector[u32]`| The 32-bit unsigned integer type | +| `vector[u64]` | The 64-bit unsigned integer type | +| `vector[i8]` | The 8-bit signed integer type | +| `vector[i16]` | The 16-bit signed integer type | +| `vector[i32]` | The 32-bit signed integer type | +| `vector[i64]` | The 64-bit signed integer type | +| `vector[f32]` | The 32-bit floating point type | +| `vector[f64]` | The 64-bit floating point type | +| `vector[none]` | The any type | + +As we see in [Hello, world](./getting-started.md#hello-world-example), we can define the return vector types for the coprocessor if we want to use it as SQL UDF. Otherwise, we can ignore the return vector types declaration: + +```python +@coprocessor(returns=['msg']) +def hello() -> vector[str]: + return "hello, GreptimeDB" +``` + +The Coprocessor Engine will infer the return vector types by the result. But without the declaration, we can't call it in SQL except by HTTP API. + +### Construct a vector + +We have already seen the example that extracting vectors from the query result by executing the `sql` attribute in `@coprocessor` in [Query Data](./query-data.md). + +We can create a vector from literals: + +```python +@copr(returns=["value"]) +def answer() -> vector[i64]: + return 42 +``` + +The result `42` will be wrapped as a one-element vector of `vector[i64]`. + +```sql +mysql> select answer(); ++----------+ +| answer() | ++----------+ +| 42 | ++----------+ +1 row in set (0.01 sec) +``` + +We can create a vector from a python list: + +```python +from greptime import vector + +@copr(returns=["value"]) +def answer() -> vector[i64]: + return vector([42, 43, 44]) +``` + +The `greptime` is a built-in module, please refer to [API Document](./api.md). + +```sql +mysql> select answer(); ++----------+ +| answer() | ++----------+ +| 42 | +| 43 | +| 44 | ++----------+ +3 rows in set (0.02 sec) +``` + +In fact, the `vector` function can create a vector from any iterable object in python. But it requires all the element types must be the same, and it chooses the first element's type as its vector type. + +### Vector operations + +The vector supports a lot of operations: + +1. Basic arithmetic operators are supported, including `+`, `-`, `*`, `/`. +2. Basic logic operations are supported, including `&`, `|`, `~`. +3. Basic comparison operation including`>`, `<`, `>=`, `<=`, `==`, `!=` are supported too. + +> Note: Here we override bitwise and `&`, bitwise or `|`, bitwise not `~` logical operator because Python doesn't support logical operator override(You can't override `and` `or` `not`). [PEP335](https://peps.python.org/pep-0335/) made a proposal and was eventually rejected. But bitwise operators have higher precedence than comparison operators, so remember to use a pair of parentheses to make sure the result is what you want. +> i.e. if you want to filter a vector that's between 0 and 100, you should use `(vector[i32] >= 0) & (vector[i32] <= 100)` not `vector[i32] >= 0 & vector[i32] <= 100`. The latter one will be evaluated as `vector[i32] >= (0 & vector[i32]) <= 100`. + +For example, you can plus two vectors directly: + +```python +@copr(args=["n1", "n2"], + returns=["value"], + sql="select number as n1,number as n2 from numbers limit 5") +def add_vectors(n1, n2) -> vector[i32]: + return n1 + n2 +``` + +Or do a comparison with a bool array in a Numpy way: + +```python +from greptime import vector + +@copr(returns=["value"]) +def compare() -> vector[bool]: + # This returns a vector([False, False, True]) + return vector([1.0, 2.0, 3.0]) > 2.0 +``` + +And using the boolean array indexing: + +```python +from greptime import vector + +@copr(returns=["value"]) +def boolean_array() -> vector[f64]: + v = vector([1.0, 2.0, 3.0]) + # This returns a vector([2.0]) + return v[(v > 1) & (v< 3)] +``` + +Comparison between two vectors is also supported: + +```python +from greptime import vector + +@copr(returns=["value"]) +def compare_vectors() -> vector[bool]: + # This returns a vector([False, False, True]) + return vector([1.0, 2.0, 3.0]) > vector([1.0, 2.0, 2.0]) +``` + +Using an indexed bool array to select elements from a vector: + +```python +from greptime import vector + +@copr(returns=["value"]) +def select_elements() -> (vector[f64]): + a = vector([1.0, 2.0, 3.0]) + # This returns a vector([2.0, 3.0]) + return a[a>=2.0] +``` + +Of course, we can use list comprehension to construct a new vector: + +```python +from greptime import vector + +@copr(returns=["value"]) +def list_comprehension() -> (vector[f64]): + a = vector([1.0, 2.0, 3.0]) + # This returns a vector([3.0, 4.0]) + return [x+1 for x in a if a >= 2.0] +``` diff --git a/versioned_docs/version-1.0/user-guide/python-scripts/define-function.md b/versioned_docs/version-1.0/user-guide/python-scripts/define-function.md new file mode 100644 index 0000000000..8df8c62cbe --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/python-scripts/define-function.md @@ -0,0 +1,267 @@ +# Define a Function + +## Coprocessor annotation + +The `@coprocessor` annotation specifies a python function as a coprocessor in GreptimeDB and sets some attributes for it. + +The engine allows one and only one function annotated with `@coprocessor`. We can't have more than one coprocessor in one script. + +| Parameter | Description | Example | +| --- | --- | --- | +| `sql` | Optional. The SQL statement that the coprocessor function will query data from the database and assign them to input `args`. | `@copr(sql="select * from cpu", ..)` | +| `args` | Optional. The argument names that the coprocessor function will be taken as input, which are the columns in query results by `sql`. | `@copr(args=["cpu", "mem"], ..)` | +| `returns` | The column names that the coprocessor function will return. The Coprocessor Engine uses it to generate the output schema. | `@copr(returns=["add", "sub", "mul", "div"], ..)` | +| `backend` | Optional. The coprocessor function will run on available engines like `rspy` and `pyo3`, which are associated with `RustPython` Backend and `CPython` Backend respectively. The default engine is set to `rspy`. | `@copr(backend="rspy", ..)` | + +Both `sql` and `args` are optional; they must either be provided together or not at all. They are usually used in Post-Query processing. Please read below. + +The `returns` is required for every coprocessor because the output schema is necessary. + +`backend` is optional, because `RustPython` can't support C APIs and you might want to use `pyo3` backend to use third-party python libraries that only support C APIs. For example, `numpy`, `pandas` etc. + +## Input of the coprocessor function + +```python +@coprocessor(args=["number"], sql="select number from numbers limit 20", returns=["value"]) +def normalize(v) -> vector[i64]: + return [normalize0(x) for x in v] +``` + +The argument `v` is the `number` column(specified by the `args` attribute) in query results that are returned by executing the `sql`. + +Of course, you can have several arguments: + +```python +@coprocessor(args=["number", "number", "number"], + sql="select number from numbers limit 5", + returns=["value"]) +def normalize(n1, n2, n3) -> vector[i64]: + # returns [0,1,8,27,64] + return n1 * n2 * n3 +``` + +Except `args`, we can also pass user-defined parameters into the coprocessor: + +```python +@coprocessor(returns=['value']) +def add(**params) -> vector[i64]: + a = params['a'] + b = params['b'] + return int(a) + int(b) +``` + +And then pass the `a` and `b` from HTTP API: + +```sh +curl -XPOST \ + "http://localhost:4000/v1/run-script?name=add&db=public&a=42&b=99" +``` + +```json +{ + "code": 0, + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "value", + "data_type": "Int64" + } + ] + }, + "rows": [ + [ + 141 + ] + ] + } + } + ], + "execution_time_ms": 0 +} +``` + +We pass `a=42&b=99` as query params into HTTP API, and it returns the result `141`. + +The user-defined parameters must be defined by `**kwargs` in the coprocessor, and all their types are strings. We can pass anything we want such as SQL to run in the coprocessor. + +## Output of the coprocessor function + +As we have seen in the previous examples, the output must be vectors. + +We can return multi vectors: + +```python +from greptime import vector + +@coprocessor(returns=["a", "b", "c"]) +def return_vectors() -> (vector[i64], vector[str], vector[f64]): + a = vector([1, 2, 3]) + b = vector(["a", "b", "c"]) + c = vector([42.0, 43.0, 44.0]) + return a, b, c +``` + +The return types of function `return_vectors` is `(vector[i64], vector[str], vector[f64])`. + +But we must ensure that all these vectors returned by the function have the same length. Because when they are converted into rows, each row must have all the column values presented. + +Of course, we can return literal values, and they will be turned into vectors: + +```python +from greptime import vector + +@coprocessor(returns=["a", "b", "c"]) +def return_vectors() -> (vector[i64], vector[str], vector[i64]): + a = 1 + b = "Hello, GreptimeDB!" + c = 42 + return a, b, c +``` + +## HTTP API + +`/scripts` submits a Python script into GreptimeDB. + +Save a python script such as `test.py`: + +```python +@coprocessor(args = ["number"], + returns = [ "number" ], + sql = "select number from numbers limit 5") +def square(number) -> vector[i64]: + return number * 2 +``` + +Submits it to database: + +```shell +curl --data-binary @test.py -XPOST \ + "http://localhost:4000/v1/scripts?db=default&name=square" +``` + +```json +{"code":0} +``` + +The python script is inserted into the `scripts` table and compiled automatically: + +```shell +curl -G http://localhost:4000/v1/sql --data-urlencode "sql=select * from scripts" +``` + +```json +{ + "code": 0, + "output": [{ + "records": { + "schema": { + "column_schemas": [ + { + "name": "schema", + "data_type": "String" + }, + { + "name": "name", + "data_type": "String" + }, + { + "name": "script", + "data_type": "String" + }, + { + "name": "engine", + "data_type": "String" + }, + { + "name": "timestamp", + "data_type": "TimestampMillisecond" + }, + { + "name": "gmt_created", + "data_type": "TimestampMillisecond" + }, + { + "name": "gmt_modified", + "data_type": "TimestampMillisecond" + } + ] + }, + "rows": [ + [ + "default", + "square", + "@coprocessor(args = [\"number\"],\n returns = [ \"number\" ],\n sql = \"select number from numbers\")\ndef square(number):\n return number * 2\n", + "python", + 0, + 1676032587204, + 1676032587204 + ] + ] + } + }], + "execution_time_ms": 4 +} +``` + +You can also execute the script via `/run-script`: + +```shell +curl -XPOST -G "http://localhost:4000/v1/run-script?db=default&name=square" +``` + +```json +{ + "code": 0, + "output": [{ + "records": { + "schema": { + "column_schemas": [ + { + "name": "number", + "data_type": "Float64" + } + ] + }, + "rows": [ + [ + 0 + ], + [ + 2 + ], + [ + 4 + ], + [ + 6 + ], + [ + 8 + ] + ] + } + }], + "execution_time_ms": 8 +} +``` + +### Parameters and Result for Python scripts + +`/scripts` accepts query parameters `db` which specifies the database, and `name` which names the script. `/scripts` processes the POST method body as the script file content. + +`/run-script` runs the compiled script by `db` and `name`, then returns the output which is the same as the query result in `/sql` API. + +`/run-script` also receives other query parameters as the user params passed into the coprocessor, refer to [Input and Output](#input-of-the-coprocessor-function). + +## Edit scripts in GreptimeDB Dashboard + +[GreptimeDB Dashboard](/getting-started/installation/greptimedb-dashboard.md) provides a convenient editor for users to edit scripts. + +After starting GreptimeDB, you can access the dashboard at `http://localhost:4000/dashboard`. +Click on `Scripts` in the left sidebar to navigate to the script page. +From there, you can create a new script, edit an existing script, or run a script. + +![dashboard-scripts](/db-dashboard-scripts.png) diff --git a/versioned_docs/version-1.0/user-guide/python-scripts/getting-started.md b/versioned_docs/version-1.0/user-guide/python-scripts/getting-started.md new file mode 100644 index 0000000000..c41654a5df --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/python-scripts/getting-started.md @@ -0,0 +1,191 @@ +# Getting Started + +## Installation + +### Create python environment +If you are using Greptime's docker image, no need to set up scripting again—it's ready to go. + +If you want to use the Greptime binary with the pyo3 feature, first figure out which Python version you need. Check by running `ldd greptime | grep 'libpython'` (or `otool -L greptime|grep Python.framework` on Mac), then install the corresponding Python version (e.g., `libpython3.10.so` requires Python 3.10). + +To set up a Python 3 environment using conda, a handy tool for managing Python environments, please refer to the [official documentation](https://docs.conda.io/en/latest/miniconda.html) for more information. + +```shell +conda create --name Greptime python= +conda activate Greptime +``` + +You may have to adjust the correct `LD_LIBRARY_PATH` for your Python shared library. For example, in the conda environment, set `LD_LIBRARY_PATH` (or `DYLD_LIBRARY_PATH`) to `$CONDA_PREFIX/lib`. To ensure the correct Python shared library is in this path, run `ls $CONDA_PREFIX/lib | grep 'libpython'` and verify that the version is correct. + +### Install GreptimeDB + +Please refer to [Installation](/getting-started/installation/overview.md). + +## Hello world example + +Let's begin with a hello world example: + +```python +@coprocessor(returns=['msg']) +def hello() -> vector[str]: + return "Hello, GreptimeDB" +``` + +Save it as `hello.py`, then post it by [HTTP API](./define-function.md#http-api): + +### Submit the Python Script to GreptimeDB + +```sh +curl --data-binary "@hello.py" -XPOST "http://localhost:4000/v1/scripts?name=hello&db=public" +``` + +Then call it in SQL: + +```sql +select hello(); +``` + +```sql ++-------------------+ +| hello() | ++-------------------+ +| Hello, GreptimeDB | ++-------------------+ +1 row in set (1.77 sec) +``` + +Or call it by [HTTP API](./define-function.md#http-api): + +```sh +curl -XPOST "http://localhost:4000/v1/run-script?name=hello&db=public" +``` + +```json +{ + "code": 0, + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "msg", + "data_type": "String" + } + ] + }, + "rows": [["Hello, GreptimeDB"]] + } + } + ], + "execution_time_ms": 1917 +} +``` + +The function `hello` is a coprocessor with an annotation `@coprocessor`. +The `returns` in `@coprocessor` specifies the return column names by the coprocessor and generates the final schema of output: + +```json + "schema": { + "column_schemas": [ + { + "name": "msg", + "data_type": "String" + } + ] + } +``` + +The `-> vector[str]` part after the argument list specifies the return types of the function. They are always vectors with concrete types. The return types are required to generate the output of the coprocessor function. + +The function body of `hello` returns a literal string: `"Hello, GreptimeDB"`.The Coprocessor engine will cast it into a vector of constant string and return it. + +A coprocessor contains three main parts in summary: + +- The `@coprocessor` annotation. +- The function input and output. +- The function body. + +We can call a coprocessor in SQL like a SQL UDF(User Defined Function) or call it by HTTP API. + +## SQL example + +Save your python code for complex analysis (like the following one which determines the load status by cpu/mem/disk usage) into a file (here its named `system_status.py`): + +```python +@coprocessor(args=["host", "idc", "cpu_util", "memory_util", "disk_util"], + returns = ["host", "idc", "status"], + sql = "SELECT * FROM system_metrics") +def system_status(hosts, idcs, cpus, memories, disks)\ + -> (vector[str], vector[str], vector[str]): + statuses = [] + for host, cpu, memory, disk in zip(hosts, cpus, memories, disks): + if cpu > 80 or memory > 80 or disk > 80: + statuses.append("red") + continue + + status = cpu * 0.4 + memory * 0.4 + disk * 0.2 + + if status > 80: + statuses.append("red") + elif status > 50: + statuses.append("yello") + else: + statuses.append("green") + + + return hosts, idcs, statuses + +``` + +The above piece of code evaluates the host status based on the cpu/memory/disk usage. Arguments come from querying data from `system_metrics` specified by parameter `sql` in `@coprocessor` annotation (here is = `"SELECT * FROM system_metrics"`). The query result is assigned to each positional argument with corresponding names in `args=[...]`, then the function returns three variables, which are converted back into three columns `returns = ["host", "idc", "status"]`. + +### Submit the Python Script to GreptimeDB + +You can submit the file to GreptimeDB with a script name so you can refer to it by this name(`system_status`) later and execute it: + +```shell +curl --data-binary "@system_status.py" \ + -XPOST "http://localhost:4000/v1/scripts?name=system_status&db=public" +``` + +Run the script: + +```shell +curl -XPOST \ + "http://localhost:4000/v1/run-script?name=system_status&db=public" +``` + +Getting the results in `json` format: + +```json +{ + "code": 0, + "output": { + "records": { + "schema": { + "column_schemas": [ + { + "name": "host", + "data_type": "String" + }, + { + "name": "idc", + "data_type": "String" + }, + { + "name": "status", + "data_type": "String" + } + ] + }, + "rows": [ + ["host1", "idc_a", "green"], + ["host1", "idc_b", "yello"], + ["host2", "idc_a", "red"] + ] + } + } +} +``` + +For more information about python coprocessor, please refer to [Function](./define-function.md#http-api) for more information. diff --git a/versioned_docs/version-1.0/user-guide/python-scripts/overview.md b/versioned_docs/version-1.0/user-guide/python-scripts/overview.md new file mode 100644 index 0000000000..b6b193908a --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/python-scripts/overview.md @@ -0,0 +1,29 @@ +# Overview + +GreptimeDB supports running Python script inside the database. If the business logic is too complex to express via SQL, you can use python. Python prevails in the data science and AI world. To avoid spending lots of time and effort transferring and transforming data, we provide the capability of executing Python scripts in the database. + +We think the python scripts in GreptimeDB is a perfect replacement for stored procedures in traditional RDMS, and also the user can create SQL UDFs(User Defined Function). + +* [Getting started](./getting-started.md) +* [Function](./define-function.md) +* [Query Data](./query-data.md) +* [Ingest Data](./write-data.md) +* [Data types](./data-types.md) +* [API](./api.md) + +All the examples can be found in [python-coprocessor-examples](https://github.com/GreptimeTeam/python-coprocessor-examples). + +# Note + +The Python scripts is currently in its experimental phase, and the API may undergo some changes. + +You can download [pre-built binaries](https://greptime.com/download) with PyO3 supported whose file names are postfixed by `pyo3`.You can just also use RustPython which doesn't require additional setup by download binary files without `pyo3` postfixed. + +If you have some library link issues, you must set up the correct Python shared library, which can be a bit challenging. In general, you just need to install the `python-dev` package(on most Debian-based system). However, if you are using Homebrew to install Python on macOS, you must create a proper soft link to `Library/Frameworks/Python.framework`. +The recommended way is to utilize `conda` for managing your Python environment. Firstly, create a Python environment with the same version of Python demanded by the binary you download. Alternatively, you can employ a docker container and execute the `greptime` binary within it. +A less recommended way is to manually install the exact version of Python required and set the `LD_LIBRARY_PATH` environment variable to the directory containing the `libpython.so` file. The version number of `` varies according to the version of Python being used. + +There is two backends for Python Scripts: + +1. RustPython Interpreter: this is supported without installing any Python library, but it is not as fast as CPython Backend. The Release Binary without `pyo3` in its name uses RustPython Interpreter. While you can still use Python Syntax in RustPython Interpreter, you can't use any third-parties libs. +2. CPython Interpreter: this is the most commonly used version of Python. It allows you to use all sorts of third-parties libs, but you need to install the correct Python shared library. Any Release Binary with `pyo3` in its name uses CPython Interpreter. diff --git a/versioned_docs/version-1.0/user-guide/python-scripts/query-data.md b/versioned_docs/version-1.0/user-guide/python-scripts/query-data.md new file mode 100644 index 0000000000..623a276ad0 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/python-scripts/query-data.md @@ -0,0 +1,117 @@ +# Query Data + +We provide two ways to easily query data from GreptimeDB in Python Coprocessor: + +* SQL: run a SQL string and return the query result. +* DataFrame API: a builtin module that describes and executes the query similar to a [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) or [Spark DataFrame](https://spark.apache.org/docs/latest/sql-programming-guide.html). + +## SQL + +Use the `greptime` module's `query` method to retrieve a query engine, then call `sql` function to execute a SQL string, for example: + +```python +@copr(returns=["value"]) +def query_numbers()->vector[f64]: + from greptime import query + return query().sql("select number from numbers limit 10")[0] +``` + +Call it via SQL client: + +```sql +SQL > select query_numbers(); ++-----------------+ +| query_numbers() | ++-----------------+ +| 0 | +| 1 | +| 2 | +| 3 | +| 4 | +| 5 | +| 6 | +| 7 | +| 8 | +| 9 | ++-----------------+ +10 rows in set (1.78 sec) +``` + +The `sql` function returns a list of columns, and each column is a vector of values. + +In the above example, `sql("select number from numbers limit 10")` returns a list of vectors. And use `[0]` to retrieve the first column vector which is the `number` column in `select` SQL. + +## Post-Query Processing + +The coprocessor is helpful when processing a query result before it returns to the user. +For example, we want to normalize the value: + +* Return zero instead of null or `NaN` if it misses, +* If it is greater than 5, return 5, +* If it is less than zero, return zero. + +Then we can create a `normalize.py`: + +```python +import math + +def normalize0(x): + if x is None or math.isnan(x): + return 0 + elif x > 5: + return 5 + elif x < 0: + return 0 + else: + return x + +@coprocessor(args=["number"], sql="select number from numbers limit 10", returns=["value"]) +def normalize(v) -> vector[i64]: + return [normalize0(x) for x in v] +``` + +The `normalize0` function behaves as described above. And the `normalize` function is the coprocessor entry point: + +* Execute the SQL `select number from numbers limit 10`, +* Extract the column `number` in the query result and use it as the argument in the `normalize` function. Then invoke the function. +* In function, use list comprehension to process the `number` vector, which processes every element by the `normalize0` function. +* Returns the result named as `value` column. + +The `-> vector[i64]` part specifies the return column types for generating the output schema. + +This example also shows how to import the stdlib and define other functions(the `normalize0`) for invoking. +The `normalize` coprocessor will be called in streaming. The query result may contain several batches, and the engine will call the coprocessor with each batch. +And we should remember that the columns extracted from the query result are all vectors. We will cover vectors in the next chapter. + +Submit and run this script will generate the output: + +```json +{ + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "value", + "data_type": "Int64" + } + ] + }, + "rows": [ + [0], + [1], + [2], + [3], + [4], + [5], + [5], + [5], + [5], + [5] + ] + } + } + ] +} +``` diff --git a/versioned_docs/version-1.0/user-guide/python-scripts/write-data.md b/versioned_docs/version-1.0/user-guide/python-scripts/write-data.md new file mode 100644 index 0000000000..633d02bb11 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/python-scripts/write-data.md @@ -0,0 +1,39 @@ +# Write Data + + +## Insert data + +Of course, you can insert data by `sql` API too: + +```python +from greptime import query +@copr(returns=["affected_rows"]) +def insert() -> vector[i32]: + return query().sql("insert into monitor(host, ts, cpu, memory) values('localhost',1667446807000, 15.3, 66.6)") +``` + +```json +{ + "code": 0, + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "rows", + "data_type": "Int32" + } + ] + }, + "rows": [ + [ + 1 + ] + ] + } + } + ], + "execution_time_ms": 4 +} +``` diff --git a/versioned_docs/version-1.0/user-guide/query-data/cte.md b/versioned_docs/version-1.0/user-guide/query-data/cte.md new file mode 100644 index 0000000000..7c8c32531c --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/query-data/cte.md @@ -0,0 +1,243 @@ +--- +keywords: [Common Table Expressions, CTE, SQL queries, simplify queries, complex queries, temporary result set] +description: Explanation of Common Table Expressions (CTEs) in GreptimeDB, including syntax, examples, and how to use CTEs to simplify complex queries. +--- + +# Common Table Expression (CTE) + +CTEs are similar to [Views](./view.md) in that they help you reduce the complexity of your queries, break down long and complex SQL statements, and improve readability and reusability. + +You already read a CTE in the [quickstart](/getting-started/quick-start.md#correlate-metrics-and-logs) document. + +## What is a Common Table Expression (CTE)? + +A Common Table Expression (CTE) is a temporary result set that you can reference within a `SELECT`, `INSERT`, `UPDATE`, or `DELETE` statement. CTEs help to break down complex queries into more readable parts and can be referenced multiple times within the same query. + +## Basic syntax of CTE + +CTEs are typically defined using the `WITH` keyword. The basic syntax is as follows: + +```sql +WITH cte_name [(column1, column2, ...)] AS ( + QUERY +) +SELECT ... +FROM cte_name; +``` + +## Example explanation + +Next, we'll go through a complete example that demonstrates how to use CTEs, including data preparation, CTE creation, and usage. + +### Step 1: Create example data + +Let's assume we have the following two tables: + +- `grpc_latencies`: Contains gRPC request latency data. +- `app_logs`: Contains application log information. + +```sql +CREATE TABLE grpc_latencies ( + ts TIMESTAMP TIME INDEX, + host VARCHAR(255), + latency FLOAT, + PRIMARY KEY(host), +); + +INSERT INTO grpc_latencies VALUES +('2023-10-01 10:00:00', 'host1', 120), +('2023-10-01 10:00:00', 'host2', 150), +('2023-10-01 10:00:05', 'host1', 130); + +CREATE TABLE app_logs ( + ts TIMESTAMP TIME INDEX, + host VARCHAR(255), + `log` TEXT, + log_level VARCHAR(50), + PRIMARY KEY(host, log_level), +); + +INSERT INTO app_logs VALUES +('2023-10-01 10:00:00', 'host1', 'Error on service', 'ERROR'), +('2023-10-01 10:00:00', 'host2', 'All services OK', 'INFO'), +('2023-10-01 10:00:05', 'host1', 'Error connecting to DB', 'ERROR'); +``` + +### Step 2: Define and use CTEs + +We will create two CTEs to calculate the 95th percentile latency and the number of error logs, respectively. + +```sql +WITH +metrics AS ( + SELECT + ts, + host, + approx_percentile_cont(0.95) WITHIN GROUP (ORDER BY latency) RANGE '5s' AS p95_latency + FROM + grpc_latencies + ALIGN '5s' FILL PREV +), +logs AS ( + SELECT + ts, + host, + COUNT(*) RANGE '5s' AS num_errors + FROM + app_logs + WHERE + log_level = 'ERROR' + ALIGN '5s' BY (host) +) +SELECT + metrics.ts, + metrics.host, + metrics.p95_latency, + COALESCE(logs.num_errors, 0) AS num_errors +FROM + metrics +LEFT JOIN logs ON metrics.host = logs.host AND metrics.ts = logs.ts +ORDER BY + metrics.ts; +``` + +Output: + +```sql ++---------------------+-------+-------------+------------+ +| ts | host | p95_latency | num_errors | ++---------------------+-------+-------------+------------+ +| 2023-10-01 10:00:00 | host2 | 150 | 0 | +| 2023-10-01 10:00:00 | host1 | 120 | 1 | +| 2023-10-01 10:00:05 | host1 | 130 | 1 | ++---------------------+-------+-------------+------------+ +``` + +## Detailed explanation + +1. **Define CTEs**: + - `metrics`: + ```sql + WITH + metrics AS ( + SELECT + ts, + host, + approx_percentile_cont(0.95) WITHIN GROUP (ORDER BY latency) RANGE '5s' AS p95_latency + FROM + grpc_latencies + ALIGN '5s' FILL PREV + ), + ``` + Here we use a [range query](/user-guide/query-data/sql.md#aggregate-data-by-time-window) to calculate the 95th percentile latency for each `host` within every 5-second window. + + - `logs`: + ```sql + logs AS ( + SELECT + ts, + host, + COUNT(*) RANGE '5s' AS num_errors + FROM + app_logs + WHERE + log_level = 'ERROR' + ALIGN '5s' BY (host) + ) + ``` + Similarly, we calculate the number of error logs for each `host` within every 5-second window. + +2. **Use CTEs**: + The final query part: + ```sql + SELECT + metrics.ts, + metrics.host, + metrics.p95_latency, + COALESCE(logs.num_errors, 0) AS num_errors + FROM + metrics + LEFT JOIN logs ON metrics.host = logs.host AND metrics.ts = logs.ts + ORDER BY + metrics.ts; + ``` + We perform a left join on the two CTE result sets to get a comprehensive analysis result. + +## Using TQL in CTEs + +GreptimeDB supports using [TQL](/reference/sql/tql.md) (Telemetry Query Language) within CTEs, allowing you to leverage PromQL-style queries in your SQL workflows. + +### Basic syntax + +```sql +WITH cte_name AS ( + TQL EVAL (start, end, step) promql_expression +) +SELECT * FROM cte_name; +``` + +### Key points + +1. **Column naming**: + - The time index column name varies depending on your table schema (e.g., `ts` for custom tables, `greptime_timestamp` for Prometheus remote write) + - The value column name depends on the PromQL expression and may be unpredictable, so it's better to use value aliasing with `AS` in TQL to ensure predictable column names: `TQL EVAL (...) expression AS my_value` + - **Important**: Avoid using column aliases in CTE definition (e.g., `WITH cte_name (ts, val) AS (...)`) because TQL EVAL results can have variable column count and order, especially in Prometheus scenarios where tags can be dynamically added or removed + +2. **Supported commands**: Only `TQL EVAL` is supported within CTEs. `TQL ANALYZE` and `TQL EXPLAIN` cannot be used in CTEs. + +3. **Lookback parameter**: The optional fourth parameter controls the lookback duration (default: 5 minutes). + +### Examples + +#### Basic TQL CTE with value aliasing + +```sql +-- Use AS clause in TQL to name the value column +WITH metrics_data AS ( + TQL EVAL (0, 40, '10s') metric AS value +) +SELECT * FROM metrics_data WHERE value > 5; +``` + +#### TQL with PromQL functions + +```sql +WITH request_rate AS ( + TQL EVAL (0, 40, '10s') rate(metric[20s]) AS rate_per_sec +) +SELECT * FROM request_rate; +``` + +#### Combining multiple TQL CTEs + +```sql +WITH + current AS ( + TQL EVAL (0, 40, '10s') metric AS current_value + ), + rate AS ( + TQL EVAL (0, 40, '10s') rate(metric[20s]) AS rate_value + ) +SELECT + c.*, + r.rate_value +FROM current c +JOIN rate r ON c.ts = r.ts; -- Note: time column name depends on your table +``` + +#### Hybrid CTE (TQL + SQL) + +```sql +WITH + tql_data AS ( + TQL EVAL (0, 40, '10s') metric AS val + ), + filtered AS ( + SELECT * FROM tql_data WHERE val > 5 + ) +SELECT count(*) FROM filtered; +``` + +## Summary + +With CTEs, you can break down complex SQL queries into more manageable and understandable parts. In this example, we created two CTEs to calculate the 95th percentile latency and the number of error logs separately and then merged them into the final query for analysis. TQL support in CTEs extends this capability by allowing PromQL-style queries to be integrated seamlessly with SQL processing. Read more about [WITH](/reference/sql/with.md) and [TQL](/reference/sql/tql.md). diff --git a/versioned_docs/version-1.0/user-guide/query-data/jaeger.md b/versioned_docs/version-1.0/user-guide/query-data/jaeger.md new file mode 100644 index 0000000000..43c5c7aaf9 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/query-data/jaeger.md @@ -0,0 +1,57 @@ +--- +keywords: [Jaeger, traces, query, experimental, HTTP endpoint] +description: Documentation for how to query traces data in GreptimeDB using Jaeger. +--- + +# Jaeger (Experimental) + +:::warning + +The Jaeger query APIs are currently in the experimental stage and may be adjusted in future versions. + +::: + +GreptimeDB currently supports the following [Jaeger](https://www.jaegertracing.io/) query interfaces: + +- `/api/services`: Get all services. +- `/api/operations?service={service}`: Get all operations for a service. +- `/api/services/{service}/operations`: Get all operations for a service. +- `/api/traces`: Get traces by query parameters. + +You can use [Grafana's Jaeger plugin](https://grafana.com/docs/grafana/latest/datasources/jaeger/)(Recommended) or [Jaeger UI](https://github.com/jaegertracing/jaeger-ui) to query traces data in GreptimeDB. When using Jaeger UI, you can set the `proxyConfig` in `packages/jaeger-ui/vite.config.mts` to the GreptimeDB address, for example: + +```ts +const proxyConfig = { + target: 'http://localhost:4000/v1/jaeger', + secure: false, + changeOrigin: true, + ws: true, + xfwd: true, +}; +``` + +Currently, GreptimeDB exposes the Jaeger HTTP APIs under the `/v1/jaeger` endpoint. + +## Quick Start + +We will use the Jaeger plugin in Grafana as an example to demonstrate how to query traces data in GreptimeDB. Before starting, please ensure that you have properly started GreptimeDB. + +### Start an application to generate traces data and write it to GreptimeDB + +You can refer to the [OpenTelemetry official documentation](https://opentelemetry.io/docs/languages/) to choose any programming language you are familiar with to generate traces data. You can also refer to the [Configure OpenTelemetry Collector](/user-guide/traces/read-write.md#opentelemetry-collector) document. + +### Configure the Grafana Jaeger plugin + +1. Open Grafana and add a Jaeger data source: + + ![Add Jaeger data source](/add-jaeger-data-source.jpg) + +2. Fill in the Jaeger address according to your actual situation, then **Save and Test**. For example: + + ``` + http://localhost:4000/v1/jaeger + ``` + +3. Use Grafana's Jaeger Explore to view the data: + + ![Jaeger Explore](/jaeger-explore.png) diff --git a/versioned_docs/version-1.0/user-guide/query-data/log-query.md b/versioned_docs/version-1.0/user-guide/query-data/log-query.md new file mode 100644 index 0000000000..acfdecff48 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/query-data/log-query.md @@ -0,0 +1,105 @@ +--- +keywords: [log query, logs, search, experimental, HTTP endpoint] +description: Documentation for GreptimeDB's experimental log query endpoint, which provides a dedicated HTTP interface for searching and processing log data. +--- + +# Log Query (Experimental) + +:::warning +The log query endpoint feature is currently experimental and may change in future releases. +::: + +GreptimeDB provides a dedicated HTTP endpoint to query log data. This feature allows you to search and process log entries using a simple query interface. This is an add-on feature to existing GreptimeDB capabilities like SQL queries and Flow computations. You can still use your existing tools and workflows to query log data like before. + +## Endpoint + +```http +POST /v1/logs +``` + +## Headers +- [Authorization](/user-guide/protocols/http.md#authentication) +- `Content-Type`: `application/json` + +## Request Format + +The request body should be a JSON object (this is subject to change in patch version within the experimental phase). For the latest request format, please refer to the [implementation](https://github.com/GreptimeTeam/greptimedb/blob/main/src/log-query/src/log_query.rs): + +## Response + +This endpoint has the same response format as the SQL query endpoint. Please refer to the [SQL query response](/user-guide/protocols/http/#response) for more details. + +## Limitations + +- Maximum result limit: 1000 entries +- Only supports tables with timestamp and string columns + +## Example + +The following example demonstrates how to query log data using the log query endpoint (notice that in this experimental phase the following example might be outdated). + +```shell +curl -X "POST" "http://localhost:4000/v1/logs" \ + -H "Authorization: Basic {{authentication}}" \ + -H "Content-Type: application/json" \ + -d $' + { + "table": { + "catalog_name": "greptime", + "schema_name": "public", + "table_name": "my_logs" + }, + "time_filter": { + "start": "2025-01-23" + }, + "limit": { + "fetch": 1 + }, + "columns": [ + "message" + ], + "filters": [ + { + "column_name": "message", + "filters": [ + { + "Contains": "production" + } + ] + } + ], + "context": "None", + "exprs": [] + } +' +``` + +In this query, we are searching for log entries in the `greptime.public.my_logs` table that contain the word `production` in `message` field. We also specify the time filter to fetch logs in `2025-01-23`, and limit the result to 1 entry. + +The response will be similar to the following: + +```json +{ + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "message", + "data_type": "String" + } + ] + }, + "rows": [ + [ + "Everything is in production" + ] + ], + "total_rows": 1 + } + } + ], + "execution_time_ms": 30 +} +``` diff --git a/versioned_docs/version-1.0/user-guide/query-data/overview.md b/versioned_docs/version-1.0/user-guide/query-data/overview.md new file mode 100644 index 0000000000..ea9332c554 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/query-data/overview.md @@ -0,0 +1,28 @@ +--- +keywords: [query languages, PromQL, SQL, views, CTE, query libraries, external data, log query] +description: Overview of query languages and features supported by GreptimeDB, including PromQL, SQL, and log query capabilities. +--- + +# Query Data + +## Query languages + +- [PromQL](./promql.md) +- [SQL](./sql.md) +- [Log Query](./log-query.md) (Experimental) + +Since v0.9, GreptimeDB supports view and CTE just like other databases, used to simplify queries: + +* [View](./view.md) +* [Common Table Expression (CTE)](./cte.md) + +## Recommended libraries + +Since GreptimeDB uses SQL as its main query language and supports both [MySQL](/user-guide/protocols/mysql.md) and [PostgreSQL](/user-guide/protocols/postgresql.md) protocols, +you can use mature SQL drivers that support MySQL or PostgreSQL to query data. + +For more information, please refer to the [SQL Tools](/reference/sql-tools.md) documentation. + +## Query external data + +GreptimeDB has the capability to query external data files. For more information, please refer to the [Query External Data](./query-external-data.md) documentation. diff --git a/versioned_docs/version-1.0/user-guide/query-data/promql.md b/versioned_docs/version-1.0/user-guide/query-data/promql.md new file mode 100644 index 0000000000..8aff303d6c --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/query-data/promql.md @@ -0,0 +1,292 @@ +--- +keywords: [PromQL, Prometheus Query Language, HTTP API, SQL extensions, Grafana, Prometheus compatibility] +description: Guide on using Prometheus Query Language (PromQL) in GreptimeDB, including HTTP API compatibility, SQL extensions, and supported features and limitations. +--- + +# Prometheus Query Language + +GreptimeDB can be used as a drop-in replacement for Prometheus in Grafana, because GreptimeDB supports PromQL (Prometheus Query Language). GreptimeDB has reimplemented PromQL natively in Rust and exposes the ability to several interfaces, including the HTTP API of Prometheus, the HTTP API of GreptimeDB, and the SQL interface. + +## Prometheus' HTTP API + + + +GreptimeDB has implemented a set of Prometheus compatible APIs under HTTP +context `/v1/prometheus/`: + +- Instant queries `/api/v1/query` +- Range queries `/api/v1/query_range` +- Series `/api/v1/series` +- Label names `/api/v1/labels` +- Label values `/api/v1/label//values` + +It shares same input and output format with original Prometheus HTTP API. You +can also use GreptimeDB as an in-place replacement of Prometheus. For example in +Grafana Prometheus data source, set `http://localhost:4000/v1/prometheus/` as +context root of Prometheus URL. + +Consult [Prometheus +documents](https://prometheus.io/docs/prometheus/latest/querying/api) for usage +of these API. + +You can use additional query parameter `db` to specify GreptimeDB database name. + +For example, the following query will return the CPU usage of the `process_cpu_seconds_total` metric in the `public` database: + +```shell +curl -X POST \ + -H 'Authorization: Basic {{authorization if exists}}' \ + --data-urlencode 'query=irate(process_cpu_seconds_total[1h])' \ + --data-urlencode 'start=2024-11-24T00:00:00Z' \ + --data-urlencode 'end=2024-11-25T00:00:00Z' \ + --data-urlencode 'step=1h' \ + 'http://localhost:4000/v1/prometheus/api/v1/query_range?db=public' +``` +If authentication is enabled in GreptimeDB, the authentication header is required. Refer to the [authentication documentation](/user-guide/protocols/http.md#authentication) for more details. +You need to either set it in the HTTP URL query param `db` like the example above, or set it using `--header 'x-greptime-db-name: '` as HTTP header. + +The query string parameters for the API are identical to those of the original [Prometheus API](https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries), with the exception of the additional `db` parameter, which specifies the GreptimeDB database name. + +The output format is compatible with the Prometheus API: + +```json +{ + "status": "success", + "data": { + "resultType": "matrix", + "result": [ + { + "metric": { + "job": "node", + "instance": "node_exporter:9100", + "__name__": "process_cpu_seconds_total" + }, + "values": [ + [ + 1732618800, + "0.0022222222222222734" + ], + [ + 1732622400, + "0.0009999999999999788" + ], + [ + 1732626000, + "0.0029999999999997585" + ], + [ + 1732629600, + "0.002222222222222175" + ] + ] + } + ] + } +} +``` + +## SQL + +GreptimeDB also extends SQL grammar to support PromQL. You can start with the `TQL` (Time-series Query Language) keyword to write parameters and queries. The grammar looks like this: + +```sql +TQL [EVAL|EVALUATE] (, , ) +``` + +`` specifies the query start range and `` specifies the end time. `` identifies the query resolution step width. All of them can either be an unquoted number (represent UNIX timestamp for `` and ``, and duration in seconds for ``), or a quoted string (represent an RFC3339 timestamp for `` and ``, and duration in string format for ``). + +For example: + +```sql +TQL EVAL (1676738180, 1676738780, '10s') sum(some_metric) +``` + +You can write the above command in all places that support SQL, including the GreptimeDB HTTP API, SDK, PostgreSQL and MySQL client etc. + +## GreptimeDB's extensions to PromQL + +### Specifying value field + +Based on the table model, GreptimeDB supports multiple fields in a single table(or metric, in the context of Prometheus). Queries will run on every fields by default. Or you can use the special filter `__field__` to query a specific field(s): + +```promql +metric{__field__="field1"} +``` + +Exclude or regex are also supported: + +```promql +metric{__field__!="field1"} + +metric{__field__=~"field_1|field_2"} + +metric{__field__!~"field_1|field_2"} +``` + +### Cross-database query + +Greptime has its own database concept. In order to run cross-database query, you +can use `__database__` matcher to specify the database name. + +```promql +metric{__database__="mydatabase"} +``` + +Note that only `=` is supported for database matcher. + +## Limitations + +Though GreptimeDB supports a rich set of data types, the PromQL implementation is still limited to the following types: + +- timestamp: `Timestamp` +- tag: `String` +- value: `Double` + +We have over 90% promql supported in GreptimeDB. Here attaches the compatibility list. You can also check our latest compliance report in this [tracking issue](https://github.com/GreptimeTeam/greptimedb/issues/1042). + +### Literal + +Both string and float literals are supported, with the same [rule](https://prometheus.io/docs/prometheus/latest/querying/basics/#literals) as PromQL. + +### Selector + +Both instant and range selector are supported. But notice that in both Prometheus and GreptimeDB, the label matching on metric name is an exception. Negative matching (e.g. `{__name__!="request_count}"`) is not allowed. Others like equal-matching or regex-matching are supported. + +Time duration and offset are supported, but `@` modifier is not supported yet. + +When selecting non-existent columns, they will be treated as columns filled with empty string values (`""`). This behavior aligns with both Prometheus and VictoriaMetrics. + +For selectors referencing non-existent columns, the behavior aligns with Prometheus: no error is raised, and the selector is silently ignored. However, for `__name__` selectors referencing non-existent metrics (or equivalent forms), GreptimeDB will report an error. + +### Timestamp precision + +The timestamp precision in PromQL is limited by its query syntax, only supporting calculations up to millisecond precision. However, GreptimeDB supports storing high-precision timestamps, such as microseconds and nanoseconds. When using PromQL for calculations, these high-precision timestamps are implicitly converted to millisecond precision. + +### Binary + +- Supported: + | Operator | + | :------- | + | add | + | sub | + | mul | + | div | + | mod | + | eqlc | + | neq | + | gtr | + | lss | + | gte | + | lte | + | power | + | atan2 | + | and | + | or | + | unless | + +- Unsupported: + +None + +### Aggregators + +- Supported: + | Aggregator | Example | + | :----------- | :------------------------------------------- | + | sum | `sum by (foo)(metric)` | + | avg | `avg by (foo)(metric)` | + | min | `min by (foo)(metric)` | + | max | `max by (foo)(metric)` | + | stddev | `stddev by (foo)(metric)` | + | stdvar | `stdvar by (foo)(metric)` | + | topk | `topk(3, rate(instance_cpu_time_ns[5m]))` | + | bottomk | `bottomk(3, rate(instance_cpu_time_ns[5m]))` | + | count_values | `count_values("version", build_version)` | + | count | `count (metric)` | + | quantile | `quantile(0.9, cpu_usage)` | + +- Unsupported: + | Aggregator | Progress | + | :--------- | :------- | + | grouping | TBD | + +### Instant Functions + +- Supported: + | Function | Example | + | :----------------- | :-------------------------------- | + | abs | `abs(metric)` | + | ceil | `ceil(metric)` | + | exp | `exp(metric)` | + | ln | `ln(metric)` | + | log2 | `log2(metric)` | + | log10 | `log10(metric)` | + | sqrt | `sqrt(metric)` | + | acos | `acos(metric)` | + | asin | `asin(metric)` | + | atan | `atan(metric)` | + | sin | `sin(metric)` | + | cos | `cos(metric)` | + | tan | `tan(metric)` | + | acosh | `acosh(metric)` | + | asinh | `asinh(metric)` | + | atanh | `atanh(metric)` | + | sinh | `sinh(metric)` | + | cosh | `cosh(metric)` | + | scalar | `scalar(metric)` | + | tanh | `tanh(metric)` | + | timestamp | `timestamp()` | + | sort | `sort(http_requests_total)` | + | sort_desc | `sort_desc(http_requests_total)` | + | histogram_quantile | `histogram_quantile(phi, metric)` | + | predicate_linear | `predict_linear(metric, 120)` | + | absent | `absent(nonexistent{job="myjob"})`| + | sgn | `sgn(metric)` | + | pi | `pi()` | + | deg | `deg(metric)` | + | rad | `rad(metric)` | + | floor | `floor(metric)` | + | clamp | `clamp(metric, 0, 12)` | + | clamp_max | `clamp_max(metric, 12)` | + | clamp_min | `clamp_min(metric, 0)` | + + +- Unsupported: + | Function | Progress / Example | + | :------------------------- | :----------------- | + | *other multiple input fns* | TBD | + +### Range Functions + +- Supported: + | Function | Example | + | :----------------- | :----------------------------- | + | idelta | `idelta(metric[5m])` | + | \_over_time | `count_over_time(metric[5m])` | + | stddev_over_time | `stddev_over_time(metric[5m])` | + | stdvar_over_time | `stdvar_over_time(metric[5m])` | + | changes | `changes(metric[5m])` | + | delta | `delta(metric[5m])` | + | rate | `rate(metric[5m])` | + | deriv | `deriv(metric[5m])` | + | increase | `increase(metric[5m])` | + | irate | `irate(metric[5m])` | + | reset | `reset(metric[5m])` | + +- Unsupported: + +None + +### Label & Other Functions + +- Supported: + | Function | Example | + | :------------ | :------------------------------------------------------------------------------------------------ | + | label_join | `label_join(up{job="api-server",src1="a",src2="b",src3="c"}, "foo", ",", "src1", "src2", "src3")` | + | label_replace | `label_replace(up{job="api-server",service="a:c"}, "foo", "$1", "service", "(.*):.*")` | + | sort_by_label | `sort_by_label(metric, "foo", "bar")` | + | sort_by_label_desc | `sort_by_label_desc(metric, "foo", "bar")` | + +- Unsupported: + +None \ No newline at end of file diff --git a/versioned_docs/version-1.0/user-guide/query-data/query-external-data.md b/versioned_docs/version-1.0/user-guide/query-data/query-external-data.md new file mode 100644 index 0000000000..b485ca020e --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/query-data/query-external-data.md @@ -0,0 +1,124 @@ +--- +keywords: [query external data, external tables, CSV, Parquet, ORC, NDJson, data files, SQL queries] +description: Instructions on querying external data files in GreptimeDB, including creating external tables and running queries on various file formats like CSV and Parquet. +--- + +# Query External Data + +## Query on a file + +Currently, we support queries on `Parquet`, `CSV`, `ORC`, and `NDJson` format file(s). + +We use the [Taxi Zone Lookup Table](https://d37ci6vzurychx.cloudfront.net/misc/taxi+_zone_lookup.csv) data as an example. + +```bash +curl "https://d37ci6vzurychx.cloudfront.net/misc/taxi+_zone_lookup.csv" -o /tmp/taxi+_zone_lookup.csv +``` + +Create an external table: + +```sql +CREATE EXTERNAL TABLE taxi_zone_lookup with (location='/tmp/taxi+_zone_lookup.csv',format='csv'); +``` + +You can check the schema of the external table like follows: + +```sql +DESC TABLE taxi_zone_lookup; +``` + +```sql ++--------------------+----------------------+------+------+--------------------------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+----------------------+------+------+--------------------------+---------------+ +| LocationID | Int64 | | YES | | FIELD | +| Borough | String | | YES | | FIELD | +| Zone | String | | YES | | FIELD | +| service_zone | String | | YES | | FIELD | +| greptime_timestamp | TimestampMillisecond | PRI | NO | 1970-01-01 00:00:00+0000 | TIMESTAMP | ++--------------------+----------------------+------+------+--------------------------+---------------+ +4 rows in set (0.00 sec) +``` + +:::tip Note +Here, you may notice there is a `greptime_timestamp` column, which doesn't exist in the file. This is because when creating an external table, if we didn't specify a `TIME INDEX` column, the `greptime_timestamp` column is automatically added as the `TIME INDEX` column with a default value of `1970-01-01 00:00:00+0000`. You can find more details in the [create](/reference/sql/create.md#create-external-table) document. +::: + +Now you can query on the external table: + +```sql +SELECT `Zone`, `Borough` FROM taxi_zone_lookup LIMIT 5; +``` + +```sql ++-------------------------+---------------+ +| Zone | Borough | ++-------------------------+---------------+ +| Newark Airport | EWR | +| Jamaica Bay | Queens | +| Allerton/Pelham Gardens | Bronx | +| Alphabet City | Manhattan | +| Arden Heights | Staten Island | ++-------------------------+---------------+ +``` + +## Query on a directory + +Let's download some data: + +```bash +mkdir /tmp/external +curl "https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2022-01.parquet" -o /tmp/external/yellow_tripdata_2022-01.parquet +curl "https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2022-02.parquet" -o /tmp/external/yellow_tripdata_2022-02.parquet +``` + +Verify the download: + +```bash +ls -l /tmp/external +total 165368 +-rw-r--r-- 1 wenyxu wheel 38139949 Apr 28 14:35 yellow_tripdata_2022-01.parquet +-rw-r--r-- 1 wenyxu wheel 45616512 Apr 28 14:36 yellow_tripdata_2022-02.parquet +``` + +Create the external table: + +```sql +CREATE EXTERNAL TABLE yellow_tripdata with(location='/tmp/external/',format='parquet'); +``` + +Run queries: + +```sql +SELECT count(*) FROM yellow_tripdata; +``` + +```sql ++-----------------+ +| COUNT(UInt8(1)) | ++-----------------+ +| 5443362 | ++-----------------+ +1 row in set (0.48 sec) +``` + +```sql +SELECT * FROM yellow_tripdata LIMIT 5; +``` + +```sql ++----------+----------------------+-----------------------+-----------------+---------------+------------+--------------------+--------------+--------------+--------------+-------------+-------+---------+------------+--------------+-----------------------+--------------+----------------------+-------------+---------------------+ +| VendorID | tpep_pickup_datetime | tpep_dropoff_datetime | passenger_count | trip_distance | RatecodeID | store_and_fwd_flag | PULocationID | DOLocationID | payment_type | fare_amount | extra | mta_tax | tip_amount | tolls_amount | improvement_surcharge | total_amount | congestion_surcharge | airport_fee | greptime_timestamp | ++----------+----------------------+-----------------------+-----------------+---------------+------------+--------------------+--------------+--------------+--------------+-------------+-------+---------+------------+--------------+-----------------------+--------------+----------------------+-------------+---------------------+ +| 1 | 2022-02-01 00:06:58 | 2022-02-01 00:19:24 | 1 | 5.4 | 1 | N | 138 | 252 | 1 | 17 | 1.75 | 0.5 | 3.9 | 0 | 0.3 | 23.45 | 0 | 1.25 | 1970-01-01 00:00:00 | +| 1 | 2022-02-01 00:38:22 | 2022-02-01 00:55:55 | 1 | 6.4 | 1 | N | 138 | 41 | 2 | 21 | 1.75 | 0.5 | 0 | 6.55 | 0.3 | 30.1 | 0 | 1.25 | 1970-01-01 00:00:00 | +| 1 | 2022-02-01 00:03:20 | 2022-02-01 00:26:59 | 1 | 12.5 | 1 | N | 138 | 200 | 2 | 35.5 | 1.75 | 0.5 | 0 | 6.55 | 0.3 | 44.6 | 0 | 1.25 | 1970-01-01 00:00:00 | +| 2 | 2022-02-01 00:08:00 | 2022-02-01 00:28:05 | 1 | 9.88 | 1 | N | 239 | 200 | 2 | 28 | 0.5 | 0.5 | 0 | 3 | 0.3 | 34.8 | 2.5 | 0 | 1970-01-01 00:00:00 | +| 2 | 2022-02-01 00:06:48 | 2022-02-01 00:33:07 | 1 | 12.16 | 1 | N | 138 | 125 | 1 | 35.5 | 0.5 | 0.5 | 8.11 | 0 | 0.3 | 48.66 | 2.5 | 1.25 | 1970-01-01 00:00:00 | ++----------+----------------------+-----------------------+-----------------+---------------+------------+--------------------+--------------+--------------+--------------+-------------+-------+---------+------------+--------------+-----------------------+--------------+----------------------+-------------+---------------------+ +5 rows in set (0.11 sec) +``` + +:::tip Note +The query result includes the value of the `greptime_timestamp` column, although it does not exist in the original file. All these column values are `1970-01-01 00:00:00+0000`, because when we create an external table, the `greptime_timestamp` column is automatically added with a default value of `1970-01-01 00:00:00+0000`. You can find more details in the [create](/reference/sql/create.md#create-external-table) document. +::: diff --git a/versioned_docs/version-1.0/user-guide/query-data/sql.md b/versioned_docs/version-1.0/user-guide/query-data/sql.md new file mode 100644 index 0000000000..c652b73368 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/query-data/sql.md @@ -0,0 +1,487 @@ +--- +keywords: [pg, pgsql, SQL queries, data filtering, time zone handling, functions, range queries, aggregations, GreptimeDB SQL] +description: Comprehensive guide on querying data in GreptimeDB using SQL, covering basic queries, filtering, time zone handling, functions, and advanced features like range queries and aggregations. +--- + +# SQL + +GreptimeDB supports full SQL for querying data from a database. + +In this document, we will use the `monitor` table to demonstrate how to query data. +For instructions on creating the `monitor` table and inserting data into it, +Please refer to [table management](/user-guide/deployments-administration/manage-data/basic-table-operations.md#create-a-table) and [Ingest Data](/user-guide/ingest-data/for-iot/sql.md). + +## Basic query + +The query is represented by the `SELECT` statement. +For example, the following query selects all data from the `monitor` table: + +```sql +SELECT * FROM monitor; +``` + +The query result looks like the following: + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2022-11-03 03:39:57 | 0.1 | 0.4 | +| 127.0.0.1 | 2022-11-03 03:39:58 | 0.5 | 0.2 | +| 127.0.0.2 | 2022-11-03 03:39:58 | 0.2 | 0.3 | ++-----------+---------------------+------+--------+ +3 rows in set (0.00 sec) +``` + +Functions are also supported in the `SELECT` field list. +For example, you can use the `count()` function to retrieve the total number of rows in the table: + +```sql +SELECT count(*) FROM monitor; +``` + +```sql ++-----------------+ +| COUNT(UInt8(1)) | ++-----------------+ +| 3 | ++-----------------+ +``` + +The `avg()` function returns the average value of a certain field: + +```sql +SELECT avg(cpu) FROM monitor; +``` + +```sql ++---------------------+ +| AVG(monitor.cpu) | ++---------------------+ +| 0.26666666666666666 | ++---------------------+ +1 row in set (0.00 sec) +``` + +You can also select only the result of a function. +For example, you can extract the day of the year from a timestamp. +The `DOY` in the SQL statement is the abbreviation of `day of the year`: + +```sql +SELECT date_part('DOY', '2021-07-01 00:00:00'); +``` + +Output: + +```sql ++----------------------------------------------------+ +| date_part(Utf8("DOY"),Utf8("2021-07-01 00:00:00")) | ++----------------------------------------------------+ +| 182 | ++----------------------------------------------------+ +1 row in set (0.003 sec) +``` + +The parameters and results of date functions align with the SQL client's time zone. +For example, when the client's time zone is set to `+08:00`, the results of the two queries below are the same: + +```sql +select to_unixtime('2024-01-02 00:00:00'); +select to_unixtime('2024-01-02 00:00:00+08:00'); +``` + +Please refer to [SELECT](/reference/sql/select.md) and [Functions](/reference/sql/functions/overview.md) for more information. + +## Limit the number of rows returned + +Time series data is typically massive. +To save bandwidth and improve query performance, +you can use the `LIMIT` clause to restrict the number of rows returned by the `SELECT` statement. + +For example, the following query limits the number of rows returned to 10: + +```sql +SELECT * FROM monitor LIMIT 10; +``` + +## Filter data + +You can use the `WHERE` clause to filter the rows returned by the `SELECT` statement. + +Filtering data by tags or time index is efficient and common in time series scenarios. +For example, the following query filter data by tag `host`: + +```sql +SELECT * FROM monitor WHERE host='127.0.0.1'; +``` + +The following query filter data by time index `ts`, and returns the data after `2022-11-03 03:39:57`: + +```sql +SELECT * FROM monitor WHERE ts > '2022-11-03 03:39:57'; +``` + +You can also use the `AND` keyword to combine multiple constraints: + +```sql +SELECT * FROM monitor WHERE host='127.0.0.1' AND ts > '2022-11-03 03:39:57'; +``` + +### Filter by time index + +Filtering data by the time index is a crucial feature in time series databases. + +When working with Unix time values, the database treats them based on the type of the column value. +For instance, if the `ts` column in the `monitor` table has a value type of `TimestampMillisecond`, +you can use the following query to filter the data: + +The Unix time value `1667446797000` corresponds to the `TimestampMillisecond` type。 + +```sql +SELECT * FROM monitor WHERE ts > 1667446797000; +``` + +When working with a Unix time value that doesn't have the precision of the column value, +you need to use the `::` syntax to specify the type of the time value. +This ensures that the database correctly identifies the type. + +For example, `1667446797` represents a timestamp in seconds, +which is different from the default millisecond timestamp of the `ts` column. +You need to specify its type as `TimestampSecond` using the `::TimestampSecond` syntax. +This informs the database that the value `1667446797` should be treated as a timestamp in seconds. + +```sql +SELECT * FROM monitor WHERE ts > 1667446797::TimestampSecond; +``` + +For the supported time data types, please refer to [Data Types](/reference/sql/data-types.md#date-and-time-types). + +When using standard `RFC3339` or `ISO8601` string literals, +you can directly use them in the filter condition since the precision is clear. + +```sql +SELECT * FROM monitor WHERE ts > '2022-07-25 10:32:16.408'; +``` + +Time and date functions are also supported in the filter condition. +For example, use the `now()` function and the `INTERVAL` keyword to retrieve data from the last 5 minutes: + +```sql +SELECT * FROM monitor WHERE ts >= now() - '5 minutes'::INTERVAL; +``` + +For date and time functions, please refer to [Functions](/reference/sql/functions/overview.md) for more information. + +### Time zone + +A string literal timestamp without time zone information will be interpreted based on the local time zone of the SQL client. For example, the following two queries are equivalent when the client time zone is `+08:00`: + +```sql +SELECT * FROM monitor WHERE ts > '2022-07-25 10:32:16.408'; +SELECT * FROM monitor WHERE ts > '2022-07-25 10:32:16.408+08:00'; +``` + +All the timestamp column values in query results are formatted based on the client time zone. +For example, the following code shows the same `ts` value formatted in the client time zones `UTC` and `+08:00` respectively. + + + + + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2023-12-31 16:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +``` + + + + + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2024-01-01 00:00:00 | 0.5 | 0.1 | ++-----------+---------------------+------+--------+ +``` + + + + + +### Functions + +GreptimeDB offers an extensive suite of built-in functions and aggregation +capabilities tailored to meet the demands of data analytics. Its features +include: + +- A comprehensive set of functions inherited from Apache Datafusion query + engine, featuring a selection of date/time functions that adhere to Postgres + naming conventions and behaviour. +- Logical data type operations for JSON, Geolocation, and other specialized data + types. +- Advanced full-text matching capabilities. + +See [Functions reference](/reference/sql/functions/overview.md) for more details. + +## Order By + +The order of the returned data is not guaranteed. You need to use the `ORDER BY` clause to sort the returned data. +For example, in time series scenarios, it is common to use the time index column as the sorting key to arrange the data chronologically: + +```sql +-- ascending order by ts +SELECT * FROM monitor ORDER BY ts ASC; +``` + +```sql +-- descending order by ts +SELECT * FROM monitor ORDER BY ts DESC; +``` + +## `CASE` Expression + +You can use the `CASE` statement to perform conditional logic within your queries. +For example, the following query returns the status of the CPU based on the value of the `cpu` field: + +```sql +SELECT + host, + ts, + CASE + WHEN cpu > 0.5 THEN 'high' + WHEN cpu > 0.3 THEN 'medium' + ELSE 'low' + END AS cpu_status +FROM monitor; +``` + +The result is shown below: + +```sql ++-----------+---------------------+------------+ +| host | ts | cpu_status | ++-----------+---------------------+------------+ +| 127.0.0.1 | 2022-11-03 03:39:57 | low | +| 127.0.0.1 | 2022-11-03 03:39:58 | medium | +| 127.0.0.2 | 2022-11-03 03:39:58 | low | ++-----------+---------------------+------------+ +3 rows in set (0.01 sec) +``` + +For more information, please refer to [CASE](/reference/sql/case.md). + +## Aggregate data by tag + +You can use the `GROUP BY` clause to group rows that have the same values into summary rows. +The average memory usage grouped by idc: + +```sql +SELECT host, avg(cpu) FROM monitor GROUP BY host; +``` + +```sql ++-----------+------------------+ +| host | AVG(monitor.cpu) | ++-----------+------------------+ +| 127.0.0.2 | 0.2 | +| 127.0.0.1 | 0.3 | ++-----------+------------------+ +2 rows in set (0.00 sec) +``` + +Please refer to [GROUP BY](/reference/sql/group_by.md) for more information. + +### Find the latest data of time series + +To find the latest point of each time series, you can use `DISTINCT ON` together with `ORDER BY` like in [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select/distinct). + +```sql +SELECT DISTINCT ON (host) * FROM monitor ORDER BY host, ts DESC; +``` + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2022-11-03 03:39:58 | 0.5 | 0.2 | +| 127.0.0.2 | 2022-11-03 03:39:58 | 0.2 | 0.3 | ++-----------+---------------------+------+--------+ +2 rows in set (0.00 sec) +``` + +## Aggregate data by time window + +GreptimeDB supports [Range Query](/reference/sql/range.md) to aggregate data by time window. + +Suppose we have the following data in the [`monitor` table](/user-guide/deployments-administration/manage-data/basic-table-operations.md#create-a-table): + +```sql ++-----------+---------------------+------+--------+ +| host | ts | cpu | memory | ++-----------+---------------------+------+--------+ +| 127.0.0.1 | 2023-12-13 02:05:41 | 0.5 | 0.2 | +| 127.0.0.1 | 2023-12-13 02:05:46 | NULL | NULL | +| 127.0.0.1 | 2023-12-13 02:05:51 | 0.4 | 0.3 | +| 127.0.0.2 | 2023-12-13 02:05:41 | 0.3 | 0.1 | +| 127.0.0.2 | 2023-12-13 02:05:46 | NULL | NULL | +| 127.0.0.2 | 2023-12-13 02:05:51 | 0.2 | 0.4 | ++-----------+---------------------+------+--------+ +``` + +The following query returns the average CPU usage in a 10-second time range and calculates it every 5 seconds: + +```sql +SELECT + ts, + host, + avg(cpu) RANGE '10s' FILL LINEAR +FROM monitor +ALIGN '5s' TO '2023-12-01T00:00:00' BY (host) ORDER BY ts ASC; +``` + +1. `avg(cpu) RANGE '10s' FILL LINEAR` is a Range expression. `RANGE '10s'` specifies that the time range of the aggregation is 10s, and `FILL LINEAR` specifies that if there is no data within a certain aggregation time, use the `LINEAR` method to fill it. +2. `ALIGN '5s'` specifies the that data statistics should be performed in steps of 5s. +3. `TO '2023-12-01T00:00:00` specifies the origin alignment time. The default value is Unix time 0. +4. `BY (host)` specifies the aggregate key. If the `BY` keyword is omitted, the primary key of the data table is used as the aggregate key by default. +5. `ORDER BY ts ASC` specifies the sorting method of the result set. If you do not specify the sorting method, the order of the results is not guaranteed. + +The Response is shown below: + +```sql ++---------------------+-----------+----------------------------------------+ +| ts | host | AVG(monitor.cpu) RANGE 10s FILL LINEAR | ++---------------------+-----------+----------------------------------------+ +| 2023-12-13 02:05:35 | 127.0.0.1 | 0.5 | +| 2023-12-13 02:05:40 | 127.0.0.1 | 0.5 | +| 2023-12-13 02:05:45 | 127.0.0.1 | 0.4 | +| 2023-12-13 02:05:50 | 127.0.0.1 | 0.4 | +| 2023-12-13 02:05:35 | 127.0.0.2 | 0.3 | +| 2023-12-13 02:05:40 | 127.0.0.2 | 0.3 | +| 2023-12-13 02:05:45 | 127.0.0.2 | 0.2 | +| 2023-12-13 02:05:50 | 127.0.0.2 | 0.2 | ++---------------------+-----------+----------------------------------------+ +``` + +### Time range window + +The origin time range window steps forward and backward in the time series to generate all time range windows. +In the example above, the origin alignment time is set to `2023-12-01T00:00:00`, which is also the end time of the origin time window. + +The `RANGE` option, along with the origin alignment time, defines the origin time range window that starts from `origin alignment timestamp` and ends at `origin alignment timestamp + range`. + +The `ALIGN` option defines the query resolution steps. +It determines the calculation steps from the origin time window to other time windows. +For example, with the origin alignment time `2023-12-01T00:00:00` and `ALIGN '5s'`, the alignment times are `2023-11-30T23:59:55`, `2023-12-01T00:00:00`, `2023-12-01T00:00:05`, `2023-12-01T00:00:10`, and so on. + +These time windows are left-closed and right-open intervals +that satisfy the condition `[alignment timestamp, alignment timestamp + range)`. + +The following images can help you understand the time range window more visually: + +When the query resolution is greater than the time range window, the metrics data will be calculated for only one time range window. + +![align > range](/align_greater_than_range.png) + +When the query resolution is less than the time range window, the metrics data will be calculated for multiple time range windows. + +![align < range](/align_less_than_range.png) + +### Align to specific timestamp + +The alignment times default based on the time zone of the current SQL client session. +You can change the origin alignment time to any timestamp you want. For example, use `NOW` to align to the current time: + +```sql +SELECT + ts, + host, + avg(cpu) RANGE '1w' +FROM monitor +ALIGN '1d' TO NOW BY (host); +``` + +Or use a `ISO 8601` timestamp to align to a specified time: + +```sql +SELECT + ts, + host, + avg(cpu) RANGE '1w' +FROM monitor +ALIGN '1d' TO '2023-12-01T00:00:00+08:00' BY (host); +``` + +### Fill null values + +The `FILL` option can be used to fill null values in the data. +In the above example, the `LINEAR` method is used to fill null values. +Other methods are also supported, such as `PREV` and a constant value `X`. +For more information, please refer to the [FILL OPTION](/reference/sql/range.md#fill-option). + +### Syntax + +Please refer to [Range Query](/reference/sql/range.md) for more information. + +## Table name constraints + +If your table name contains special characters or uppercase letters, +you must enclose the table name in backquotes. +For examples, please refer to the [Table name constraints](/user-guide/deployments-administration/manage-data/basic-table-operations.md#table-name-constraints) section in the table creation documentation. + +## HTTP API + +Use POST method to query data: + +```shell +curl -X POST \ + -H 'authorization: Basic {{authorization if exists}}' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d 'sql=select * from monitor' \ +http://localhost:4000/v1/sql?db=public +``` + +The result is shown below: + +```json +{ + "code": 0, + "output": [ + { + "records": { + "schema": { + "column_schemas": [ + { + "name": "host", + "data_type": "String" + }, + { + "name": "ts", + "data_type": "TimestampMillisecond" + }, + { + "name": "cpu", + "data_type": "Float64" + }, + { + "name": "memory", + "data_type": "Float64" + } + ] + }, + "rows": [ + ["127.0.0.1", 1667446797450, 0.1, 0.4], + ["127.0.0.1", 1667446798450, 0.5, 0.2], + ["127.0.0.2", 1667446798450, 0.2, 0.3] + ] + } + } + ], + "execution_time_ms": 0 +} +``` + +For more information about SQL HTTP request, please refer to [API document](/user-guide/protocols/http.md#post-sql-statements). diff --git a/versioned_docs/version-1.0/user-guide/query-data/view.md b/versioned_docs/version-1.0/user-guide/query-data/view.md new file mode 100644 index 0000000000..e8efaaeb2e --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/query-data/view.md @@ -0,0 +1,147 @@ +--- +keywords: [SQL views, create view, query view, update view, manage views, data security, complex queries] +description: Explanation of SQL views in GreptimeDB, including how to create, query, update, and manage views for simplifying complex queries and ensuring data security. +--- + +# View + +In SQL, a view is a virtual table based on the result set of an SQL statement. +It contains rows and columns just like a real table. +The query of a view is run every time the view is referenced in a query. + +In the following situations, you can use views: + +* Simplifying complex queries, avoiding the need to repeatedly write and send complex statements for every query. +* Granting read permissions to specific users while restricting access to certain columns and rows to ensure data security and isolation. + +A view is created with the `CREATE VIEW` statement. + +## View examples + +```sql +CREATE VIEW cpu_monitor AS + SELECT cpu, host, ts FROM monitor; +``` + +The view name is `cpu_monitor`, and the query statement after `AS` is the SQL statement to present the data. Query the view: + +```sql +SELECT * FROM cpu_monitor; +``` + +```sql ++------+-----------+---------------------+ +| cpu | host | ts | ++------+-----------+---------------------+ +| 0.5 | 127.0.0.1 | 2023-12-13 02:05:41 | +| 0.3 | 127.0.0.1 | 2023-12-13 02:05:46 | +| 0.4 | 127.0.0.1 | 2023-12-13 02:05:51 | +| 0.3 | 127.0.0.2 | 2023-12-13 02:05:41 | +| 0.2 | 127.0.0.2 | 2023-12-13 02:05:46 | +| 0.2 | 127.0.0.2 | 2023-12-13 02:05:51 | ++------+-----------+---------------------+ +``` + +Query view by `WHERE`: + +```sql +SELECT * FROM cpu_monitor WHERE host = '127.0.0.2'; +``` + +```sql ++------+-----------+---------------------+ +| cpu | host | ts | ++------+-----------+---------------------+ +| 0.3 | 127.0.0.2 | 2023-12-13 02:05:41 | +| 0.2 | 127.0.0.2 | 2023-12-13 02:05:46 | +| 0.2 | 127.0.0.2 | 2023-12-13 02:05:51 | ++------+-----------+---------------------+ +``` + +Create a view that queries data from two tables: + +```sql +CREATE VIEW app_cpu_monitor AS + SELECT cpu, latency, host, ts FROM monitor LEFT JOIN app_monitor + ON monitor.host = app_monitor.host AND monitor.ts = app_monitor.ts +``` + +Then query the view as if the data were coming from one single table: + +```sql +SELECT * FROM app_cpu_monitor WHERE host = 'host1' +``` + +## Update View + +`CREATE OR REPLACE VIEW` to update a view, if it doesn't exist, it will be created: + +```sql +CREATE OR REPLACE VIEW memory_monitor AS + SELECT memory, host, ts FROM monitor; +``` + +## Shows the view definition + +Shows the `CREATE VIEW` statement that creates the named view by `SHOW CREATE VIEW view_name`: + +```sql +SHOW CREATE VIEW cpu_monitor; +``` + +```sql ++-------------+--------------------------------------------------------------+ +| View | Create View | ++-------------+--------------------------------------------------------------+ +| cpu_monitor | CREATE VIEW cpu_monitor AS SELECT cpu, host, ts FROM monitor | ++-------------+--------------------------------------------------------------+ +``` + +## List Views + +`SHOW VIEWS` statement to find all the views: + +```sql +> SHOW VIEWS; + ++----------------+ +| Views | ++----------------+ +| cpu_monitor | +| memory_monitor | ++----------------+ +``` + +of course, just like `SHOW TABLES`, it supports `LIKE` and `WHERE`: + +```sql +> SHOW VIEWS like 'cpu%'; ++-------------+ +| Views | ++-------------+ +| cpu_monitor | ++-------------+ +1 row in set (0.02 sec) + +> SHOW VIEWS WHERE Views = 'memory_monitor'; ++----------------+ +| Views | ++----------------+ +| memory_monitor | ++----------------+ +``` + +## Drop View + +Use `DROP VIEW` statement to drop a view: + +```sql +DROP VIEW cpu_monitor; +``` + +To be quiet if it does not exist: + +```sql +DROP VIEW IF EXISTS test; +``` + diff --git a/versioned_docs/version-1.0/user-guide/timezone.md b/versioned_docs/version-1.0/user-guide/timezone.md new file mode 100644 index 0000000000..30d1b981e8 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/timezone.md @@ -0,0 +1,54 @@ +--- +keywords: [time zone management, SQL time zone, data ingestion, querying, client session, time zone configuration] +description: Guide on specifying and managing time zones in GreptimeDB client sessions, including impacts on data ingestion and querying. +--- + +# Time Zone + +You can specify the time zone in the client session to manage time data conveniently. +The specified time zone in the client session does not affect the time data stored in the GreptimeDB server, +it only applies when the client sends a request to the server. +GreptimeDB converts the time value from a string representation to a datetime according to the specified time zone during ingestion or querying, or converts it back. + +## Specify time zone in clients + +By default, all clients use [the default time zone configuration](/user-guide/deployments-administration/configuration.md#default-time-zone-configuration), which is UTC. +You can also specify a time zone in each client session, +which will override the default time zone configuration. + +### MySQL client + +- **Command Line**: For configuring the time zone via the MySQL command line client, please refer to the [time zone section](/user-guide/protocols/mysql.md#time-zone) in the MySQL protocol documentation. +- **MySQL Driver**: If you are using MySQL Driver in Java or Go, see the [time zone section](/reference/sql-tools.md#time-zone) of the SQL tools documentation. + +### PostgreSQL client + +To configure the time zone for the PostgreSQL client, please refer to the [time zone section](/user-guide/protocols/postgresql.md#time-zone) in the PostgreSQL protocol documentation. + +### HTTP API + +When using the HTTP API, you can specify the time zone through the header parameter. For more information, please refer to the [HTTP API documentation](/user-guide/protocols/http.md#time-zone). + +### Dashboard + +The dashboard will use the local timezone as the default timezone value. You can change it in the settings menu. + +### Other clients + +For other clients, you can change [the default time zone configuration](/user-guide/deployments-administration/configuration.md#default-time-zone-configuration) of GreptimeDB. + +## Impact of time zone on SQL statements + +The client's time zone setting influences both data ingestion and querying. + +### Ingest data + +The time zone set in the client impacts the data during ingestion. +For more information, please refer to the [ingest data section](/user-guide/ingest-data/for-iot/sql.md#time-zone). +Additionally, the default timestamp values in the table schema are influenced by the client's time zone in the same manner as the ingested data. + +### Query data + +The time zone setting also affects data during querying. +For detailed information, please refer to the [query data section](/user-guide/query-data/sql.md#time-zone). + diff --git a/versioned_docs/version-1.0/user-guide/traces/data-model.md b/versioned_docs/version-1.0/user-guide/traces/data-model.md new file mode 100644 index 0000000000..e60e8208c5 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/traces/data-model.md @@ -0,0 +1,198 @@ +--- +keywords: [Trace, OpenTelemetry, Jaeger] +description: Covers internals of how trace data is stored in GreptimeDB. +--- + +# Trace Data Modeling + +:::warning + +This section currently in the experimental stage and may be adjusted in future versions. + +::: + +In this section, we will cover how trace data is modeled in GreptimeDB as +tables. + +We reuse the concept of Pipeline for trace data modeling. However, note that at +the moment, only built-in pipelines are supported. + +## Data model versioning + +First, the data types and features in GreptimeDB are evolving. For +forward-compatibility, we use the pipeline name for data model +versioning. Currently we have following pipeline for trace: + +- `greptime_trace_v1` + +It is required for user to specify this on OpenTelemetry OTLP/HTTP headers via +`x-greptime-pipeline-name: greptime_trace_v1`. + +We may introduce new data model by adding new available pipeline names. And we +will keep previous pipeline supported. Note that new pipeline may not be +compatible with previous ones so you are recommended to use it in new table. + +## Data model + +The `greptime_trace_v1` data model is pretty straight-forward. + +- It maps most common data fields from [OpenTelemetry + Trace](https://opentelemetry.io/docs/concepts/signals/traces/) data model to + GreptimeDB's table columns. +- A new `duration_nano` column is generated using `end_time - start_time`. +- All attributes fields are flatten into columns using the name pattern: + `[span|resource|scope]_attributes.[attribute_key]`. If the attribute value is + a compound type like `Array` or `Kvlist`, it is serialized to json type of + GreptimeDB. +- Compound fields, `span_links` and `span_events` are stored as json type. + +The table will be automatically generated when your first data item arrived. It +also follows our schema-less principle to update the table schema automatically +for new columns, for example, the new attribute fields. + +A typical table structure generated from OpenTelemetry django instrument is like: + +``` +timestamp | 2025-05-07 10:03:29.657544 +timestamp_end | 2025-05-07 10:03:29.661714 +duration_nano | 4169970 +trace_id | fb60d19aa36fdcb7d14a71ca0b9b42ae +span_id | 49806a2671f2ddcb +span_kind | SPAN_KIND_SERVER +span_name | POST todos/ +span_status_code | STATUS_CODE_UNSET +span_status_message | +trace_state | +scope_name | opentelemetry.instrumentation.django +scope_version | 0.51b0 +service_name | myproject +span_attributes.http.request.method | POST +span_attributes.url.full | +span_attributes.server.address | django:8000 +span_attributes.network.peer.address | +span_attributes.server.port | 8000 +span_attributes.network.peer.port | +span_attributes.http.response.status_code | 201 +span_attributes.network.protocol.version | 1.1 +resource_attributes.telemetry.sdk.language | python +resource_attributes.telemetry.sdk.name | opentelemetry +resource_attributes.telemetry.sdk.version | 1.30.0 +span_events | [] +span_links | [] +parent_span_id | eccc18b6fc210f31 +span_attributes.db.system | +span_attributes.db.name | +span_attributes.db.statement | +span_attributes.url.scheme | http +span_attributes.url.path | /todos/ +span_attributes.client.address | 10.89.0.5 +span_attributes.client.port | 44302 +span_attributes.user_agent.original | python-requests/2.32.3 +span_attributes.http.route | todos/ +``` + +To check the table definition, you can use `show create table
` +statement. An output like this is expected: + +``` +Table | web_trace_demo +Create Table | CREATE TABLE IF NOT EXISTS "web_trace_demo" ( + + | "timestamp" TIMESTAMP(9) NOT NULL, + + | "timestamp_end" TIMESTAMP(9) NULL, + + | "duration_nano" BIGINT UNSIGNED NULL, + + | "trace_id" STRING NULL SKIPPING INDEX WITH(granularity = '10240', type = 'BLOOM'), + + | "span_id" STRING NULL, + + | "span_kind" STRING NULL, + + | "span_name" STRING NULL, + + | "span_status_code" STRING NULL, + + | "span_status_message" STRING NULL, + + | "trace_state" STRING NULL, + + | "scope_name" STRING NULL, + + | "scope_version" STRING NULL, + + | "service_name" STRING NULL SKIPPING INDEX WITH(granularity = '10240', type = 'BLOOM'),+ + | "span_attributes.http.request.method" STRING NULL, + + | "span_attributes.url.full" STRING NULL, + + | "span_attributes.server.address" STRING NULL, + + | "span_attributes.network.peer.address" STRING NULL, + + | "span_attributes.server.port" BIGINT NULL, + + | "span_attributes.network.peer.port" BIGINT NULL, + + | "span_attributes.http.response.status_code" BIGINT NULL, + + | "span_attributes.network.protocol.version" STRING NULL, + + | "resource_attributes.telemetry.sdk.language" STRING NULL, + + | "resource_attributes.telemetry.sdk.name" STRING NULL, + + | "resource_attributes.telemetry.sdk.version" STRING NULL, + + | "span_events" JSON NULL, + + | "span_links" JSON NULL, + + | "parent_span_id" STRING NULL, + + | "span_attributes.db.system" STRING NULL, + + | "span_attributes.db.name" STRING NULL, + + | "span_attributes.db.statement" STRING NULL, + + | "span_attributes.url.scheme" STRING NULL, + + | "span_attributes.url.path" STRING NULL, + + | "span_attributes.client.address" STRING NULL, + + | "span_attributes.client.port" BIGINT NULL, + + | "span_attributes.user_agent.original" STRING NULL, + + | "span_attributes.http.route" STRING NULL, + + | TIME INDEX ("timestamp"), + + | PRIMARY KEY ("service_name") + + | ) + + | PARTITION ON COLUMNS ("trace_id") ( + + | trace_id < '1', + + | trace_id >= 'f', + + | trace_id >= '1' AND trace_id < '2', + + | trace_id >= '2' AND trace_id < '3', + + | trace_id >= '3' AND trace_id < '4', + + | trace_id >= '4' AND trace_id < '5', + + | trace_id >= '5' AND trace_id < '6', + + | trace_id >= '6' AND trace_id < '7', + + | trace_id >= '7' AND trace_id < '8', + + | trace_id >= '8' AND trace_id < '9', + + | trace_id >= '9' AND trace_id < 'a', + + | trace_id >= 'a' AND trace_id < 'b', + + | trace_id >= 'b' AND trace_id < 'c', + + | trace_id >= 'c' AND trace_id < 'd', + + | trace_id >= 'd' AND trace_id < 'e', + + | trace_id >= 'e' AND trace_id < 'f' + + | ) + + | ENGINE=mito + + | WITH( + + | append_mode = 'true', + + | table_data_model = 'greptime_trace_v1' + + | ) +``` + +### Partition Rules + +We included default [partition +rules](/user-guide/deployments-administration/manage-data/table-sharding.md#partition) for +trace table on the `trace_id` column based on the first character of it. This is +optimised for retrieve trace spans by the trace id. + +The partition rule introduces 16 partitions for the table. It is suitable for a +3-5 datanode setup. + +To customize the partition rule, you can create a new table ahead-of-time by +copying the DDL output by `show create table` on original table, update the +`PARTITION ON` section to include your own rules. + +### Index + +We include [skipping +index](/user-guide/manage-data/data-index.md#skipping-index) on `service_name` +and `trace_id` for most typical queries. + +In real-world, you may want to speed up queries on other fields like an attribute +field. It's possible by apply additional index on these fields using [alter +table](/reference/sql/alter.md#create-an-index-for-a-column) statement. + +Unlike partition rules, index can be created on existing table and be affective +on new data. + +### Append Only + +By default, trace table created by OpenTelemetry API are in [append only +mode](/user-guide/deployments-administration/performance-tuning/design-table.md#when-to-use-append-only-tables). + +### TTL + +You can apply [TTL on trace table](/reference/sql/alter.md#alter-table-options). diff --git a/versioned_docs/version-1.0/user-guide/traces/extend-trace.md b/versioned_docs/version-1.0/user-guide/traces/extend-trace.md new file mode 100644 index 0000000000..ae8b9e7942 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/traces/extend-trace.md @@ -0,0 +1,115 @@ +--- +keywords: [Trace, OpenTelemetry, Jaeger, Grafana] +description: Introduces additional features to generate more data insights from trace data +--- + +# Extending Trace Data + +:::warning + +This section currently in the experimental stage and may be adjusted in future versions. + +::: + +You can also generate derived data from trace. In this chapter, we will show you +some examples. + +## Generate Aggregated Metrics from Trace + +The span contains `duration_nano` field for span processing time. In this +example, we will create [Flow](/user-guide/flow-computation/overview.md) task to +generate latency metrics from trace data. + +We will use OpenTelemetry Django instruments for source data. But the source +data doesn't really matter because fields used in this example are all generic +ones. + +### Create sink table + +First, we create a sink table which is a materialzed view in Flow. For latency +quantiles, we will use [uddsketch](https://arxiv.org/abs/2004.08604) for a quick +estimation of latency at given percentile. + +```sql +CREATE TABLE "django_http_request_latency" ( + "span_name" STRING NULL, + "latency_sketch" BINARY, + "time_window" TIMESTAMP time index, + PRIMARY KEY ("span_name") +); +``` + +This table contains 3 key columns: + +- `span_name`: the type or name of span +- `latency_sketch`: the uddsketch data structure +- `time_window`: indicate the time window of current record + +### Create flow + +Next we create a flow task to generate uddsketch data for every 30s time +window. The example filters spans by the scope name, which is optional depends +on your data. + +```sql +CREATE FLOW django_http_request_latency_flow +SINK TO django_http_request_latency +EXPIRE AFTER '30m' +COMMENT 'Aggregate latency using uddsketch' +AS +SELECT + span_name, + uddsketch_state(128, 0.01, "duration_nano") AS "latency_sketch", + date_bin('30 seconds'::INTERVAL, "timestamp") as "time_window", +FROM web_trace_demo +WHERE + scope_name = 'opentelemetry.instrumentation.django' +GROUP BY + span_name, + time_window; +``` + +### Query metrics + +The sink table will be filled with aggregated data as trace data ingested. We +can use following SQL to get p90 latency of the each span. + +```sql +SELECT + span_name, + time_window, + uddsketch_calc(0.90, "latency_sketch") AS p90 +FROM + django_http_request_latency +ORDER BY + time_window DESC +LIMIT 20; +``` + +The query will return results like: + +``` + span_name | time_window | p90 +---------------------+----------------------------+-------------------- + GET todos/ | 2025-05-09 02:38:00.000000 | 4034758.586053441 + POST todos/ | 2025-05-09 02:38:00.000000 | 22988738.680499777 + PUT todos// | 2025-05-09 02:38:00.000000 | 5338559.200101535 + GET todos/ | 2025-05-09 02:37:30.000000 | 4199425.807196321 + POST todos/ | 2025-05-09 02:37:30.000000 | 15104466.164886404 + PUT todos// | 2025-05-09 02:37:30.000000 | 16693072.385310777 + GET todos/ | 2025-05-09 02:37:00.000000 | 4370813.453648573 + POST todos/ | 2025-05-09 02:37:00.000000 | 30417369.407361753 + PUT todos// | 2025-05-09 02:37:00.000000 | 14512192.224492861 + GET todos/ | 2025-05-09 02:36:30.000000 | 3578495.53232116 + POST todos/ | 2025-05-09 02:36:30.000000 | 15409606.895490168 + PUT todos// | 2025-05-09 02:36:30.000000 | 15409606.895490168 + GET todos/ | 2025-05-09 02:36:00.000000 | 3507634.2346514342 + POST todos/ | 2025-05-09 02:36:00.000000 | 45377987.991290994 + PUT todos// | 2025-05-09 02:36:00.000000 | 14512192.224492861 + GET todos/ | 2025-05-09 02:35:30.000000 | 3237945.86410019 + POST todos/ | 2025-05-09 02:35:30.000000 | 15409606.895490168 + PUT todos// | 2025-05-09 02:35:30.000000 | 13131130.769316385 + GET todos/ | 2025-05-09 02:35:00.000000 | 3173828.124217018 + POST todos/ | 2025-05-09 02:35:00.000000 | 14512192.224492861 +(20 rows) +``` diff --git a/versioned_docs/version-1.0/user-guide/traces/overview.md b/versioned_docs/version-1.0/user-guide/traces/overview.md new file mode 100644 index 0000000000..34d2dc0e39 --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/traces/overview.md @@ -0,0 +1,20 @@ +--- +keywords: [trace, distributed tracing, opentelemetry, jaeger, wide events, observability] +description: Introducing GreptimeDB's built-in support for managing tracing data at scale +--- + +# Trace + +:::warning + +This section currently in the experimental stage and may be adjusted in future versions. + +::: + +Native support for Trace data is introduced since GreptimeDB v0.14. In this +section we will cover from basic ingestion and query steps, to advanced +internals of data modeling. + +- [How to ingest/query trace data](./read-write.md) +- [Trace data modeling in GreptimeDB](./data-model.md) +- [Extending trace data](./extend-trace.md) diff --git a/versioned_docs/version-1.0/user-guide/traces/read-write.md b/versioned_docs/version-1.0/user-guide/traces/read-write.md new file mode 100644 index 0000000000..06087c54bb --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/traces/read-write.md @@ -0,0 +1,184 @@ +--- +keywords: [Trace, OpenTelemetry, Jaeger, Grafana] +description: Covers basics of trace data ingestion and query in GreptimeDB. +--- + +# Ingestion and Query + +:::warning + +This section currently in the experimental stage and may be adjusted in future versions. + +::: + +In this section, we will get started with trace data in GreptimeDB from +ingestion and query. + +GreptimeDB doesn't invent new protocols for trace, it follows existing standard +and widely adopted protocols. + +## Ingestion + +GreptimeDB uses OpenTelemetry OTLP/HTTP protocol as the primary trace data +ingestion protocol. OpenTelemetry Trace is the most adopted subprotocol in +OpenTelemetry family. + +### OpenTelemetry SDK + +If OpenTelemetry SDK/API is used in your application, you can configure an +OTLP/HTTP exporter to write trace data directly to GreptimeDB. + +We covered this part in our [OpenTelemetry protocol +docs](/user-guide/ingest-data/for-observability/opentelemetry.md). You can +follow the guide for endpoint and parameters. + +### OpenTelemetry Collector + +[OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) is a +vendor-neutral service for collecting and processing OpenTelemetry data. You can +also configure it to send trace data to GreptimeDB using OTLP/HTTP. + +#### Start OpenTelemetry Collector + +You can use the following command to quickly start an OpenTelemetry Collector +instance, which will listen on ports `4317` (gRPC) and `4318` (HTTP): + +```shell +docker run --rm \ + --network host \ + -p 4317:4317 \ + -p 4318:4318 \ + -v $(pwd)/config.yaml:/etc/otelcol-contrib/config.yaml \ + otel/opentelemetry-collector-contrib:0.123.0 +``` + +The content of the `config.yaml` file is as follows: + +```yaml +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +exporters: + otlphttp: + endpoint: "http://greptimedb:4000/v1/otlp" # Replace greptimedb with your setup + headers: + x-greptime-pipeline-name: "greptime_trace_v1" + #authorization: "Basic " + tls: + insecure: true + +service: + pipelines: + traces: + receivers: [otlp] + exporters: [otlphttp] +``` + +#### Write traces data to OpenTelemetry Collector + +You can configure the corresponding exporter to write traces data to the +OpenTelemetry Collector. For example, you can use the environment variable +`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` to configure the endpoint of the exporter: + +```shell +export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="http://localhost:4318/v1/otlp/v1/traces" +``` + +For convenience, you can use the tool +[`telemetrygen`](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/cmd/telemetrygen) +to quickly generate traces data and write it to the OpenTelemetry Collector. For +more details, please refer to the [OpenTelemetry Collector official +documentation](https://opentelemetry.io/docs/collector/quick-start/). + +You can use the following command to install `telemetrygen` (please ensure you +have installed Go): + +```shell +go install github.com/open-telemetry/opentelemetry-collector-contrib/cmd/telemetrygen@latest +``` + +Then you can use the following command to generate traces data and write it to +the OpenTelemetry Collector: + +```shell +telemetrygen traces --otlp-insecure --traces 3 +``` + +The above command will generate 3 traces data and write it to the OpenTelemetry +Collector via gRPC protocol, and eventually stored into GreptimeDB. + +### Authorization + +The GreptimeDB OTEL endpoint supports Basic authentication. For details, please refer to the [authentication](/user-guide/protocols/http.md#authentication) documentation. + +### GreptimeDB Pipeline + +The HTTP header `x-greptime-pipeline-name` is required for ingesting trace +data. Here we reuse the Pipeline concept of GreptimeDB for data +transformation. However, note that we only support built-in `greptime_trace_v1` +as the pipeline for tracing. No custom pipeline is allowed for the moment. + +### Append Only + +By default, trace table created by OpenTelemetry API are in [append only +mode](/user-guide/deployments-administration/performance-tuning/design-table.md#when-to-use-append-only-tables). + +## Query + +To query the trace data, GreptimeDB has two types of API provided. The Jaeger +compatible API and GreptimeDB's original SQL based query interfaces, which is +available in HTTP, MySQL and Postgres protocols. + +### Jaeger + +We build Jaeger compatibility layer into GreptimeDB so you can reuse your Jaeger +frontend or any other integrations like Grafana's Jaeger data source. + +For detail of Jaeger's endpoint and parameters, check [our Jaeger protocol +docs](/user-guide/query-data/jaeger.md). + +### SQL + +All data in GreptimeDB is available for query using SQL, via MySQL and other +transport protocol. + +By default, trace data is written into the table called +`opentelemetry_traces`. The table name is customizable via header +`x-greptime-trace-table-name`. You can run SQL queries against the table: + +```sql +SELECT * FROM public.opentelemetry_traces \G +``` + +An example output is like + +``` +*************************** 1. row *************************** + timestamp: 2025-04-02 09:58:43.822229 + timestamp_end: 2025-04-02 09:58:43.822352 + duration_nano: 123000 + parent_span_id: NULL + trace_id: 1948380e459f4ca69bb4f4274b5db7ba + span_id: f179c8dc2171a0a0 + span_kind: SPAN_KIND_CLIENT + span_name: lets-go + span_status_code: STATUS_CODE_UNSET + span_status_message: + trace_state: + scope_name: telemetrygen + scope_version: + service_name: telemetrygen +span_attributes.net.sock.peer.addr: 1.2.3.4 + span_attributes.peer.service: telemetrygen-server + span_events: [] + span_links: [] +... +``` + +We will cover more information about the table structure in [data +model](./data-model.md) section. diff --git a/versioned_docs/version-1.0/user-guide/vectors/vector-type.md b/versioned_docs/version-1.0/user-guide/vectors/vector-type.md new file mode 100644 index 0000000000..3749bd7b0e --- /dev/null +++ b/versioned_docs/version-1.0/user-guide/vectors/vector-type.md @@ -0,0 +1,99 @@ +--- +keywords: [vector data type, AI applications, machine learning, deep learning, vector storage, vector computation, SQL vector functions] +description: Overview of vector data type in GreptimeDB, including how to define, insert, and perform calculations with vector type columns in SQL. +--- + +# Vector Data Type + +## Overview + +In the field of artificial intelligence, vectors are an important data type used to represent features or samples within a dataset. Vectors are utilized in various machine learning and deep learning algorithms, such as recommendation systems, natural language processing, and image recognition. By introducing the vector type, GreptimeDB enables more efficient support for these AI applications, offering robust vector storage and computation capabilities. + +## Basic Introduction to Vector Type + +In GreptimeDB, a vector is represented as an array of Float32 (32-bit floating-point) with a fixed dimension. When creating a vector type column, the dimension must be specified and cannot be changed afterward. + +## Defining a Vector Type Column + +In SQL, a table with a vector type column can be defined using the following syntax. Note that the dimension `` must be a positive integer that specifies the length of the vector. + +```sql +CREATE TABLE ( + ... + VECTOR() +); +``` + +For example, to define a table with a vector type column of dimension 3: + +```sql +CREATE TABLE vecs ( + ts TIMESTAMP TIME INDEX, + vec_col VECTOR(3) +); +``` + +## Inserting Vector Data + +In GreptimeDB, you can insert vector data into the database in several ways. The simplest method is to use a string format and implicitly convert it to a vector. The string needs to be enclosed in square brackets `[]`. Below is an example of using implicit conversion in SQL: + +```sql +INSERT INTO
() VALUES +('[, , ...]'), +('[, , ...]'), +... +('[, , ...]'); +``` + +For example, to insert three 3-dimensional vectors: + +```sql +INSERT INTO vecs (ts, vec_col) VALUES +('2024-11-18 00:00:01', '[1.0, 2.0, 3.0]'), +('2024-11-18 00:00:02', '[4.0, 5.0, 6.0]'), +('2024-11-18 00:00:03', '[7.0, 8.0, 9.0]'); +``` + +If you wish to have more explicit control over data conversion, you can use the `parse_vec` function to explicitly parse a string into a vector: + +```sql +INSERT INTO vecs (ts, vec_col) VALUES +('2024-11-18 00:00:01', parse_vec('[1.0, 2.0, 3.0]')), +('2024-11-18 00:00:02', parse_vec('[4.0, 5.0, 6.0]')), +('2024-11-18 00:00:03', parse_vec('[7.0, 8.0, 9.0]')); +``` + +## Vector Calculations + +GreptimeDB supports various vector functions for calculating the similarity between vectors, including `vec_l2sq_distance`, `vec_cos_distance`, and `vec_dot_product`. These functions are used in AI applications to search for the most similar content. + +To perform vector calculations, use the following SQL format: + +```sql +SELECT (, ) FROM
; +``` + +For example, to find the vector with the smallest squared Euclidean distance to a given vector `[5.0, 5.0, 5.0]` and display the distance, you can use the following query: + +```sql +SELECT vec_to_string(vec_col), vec_l2sq_distance(vec_col, '[5.0, 5.0, 5.0]') AS distance +FROM vecs +ORDER BY distance; +``` + +Upon executing this query, you will get results similar to the following: + +``` ++-----------------------------+----------+ +| vec_to_string(vecs.vec_col) | distance | ++-----------------------------+----------+ +| [4,5,6] | 2 | +| [1,2,3] | 29 | +| [7,8,9] | 29 | ++-----------------------------+----------+ +3 rows in set (0.01 sec) +``` + +Through this approach, GreptimeDB enables you to quickly identify and locate similar data vectors, thus providing robust support for AI applications. + +For more information about vector functions, please refer to the [Vector Functions Reference](/reference/sql/functions/vector.md). diff --git a/versioned_sidebars/version-0.17-sidebars.json b/versioned_sidebars/version-0.17-sidebars.json index 3f8191dad9..8bd27bf2f3 100644 --- a/versioned_sidebars/version-0.17-sidebars.json +++ b/versioned_sidebars/version-0.17-sidebars.json @@ -409,90 +409,6 @@ "tutorials/k8s-metrics-monitor" ] }, - { - "type": "category", - "label": "GreptimeCloud", - "items": [ - { - "type": "doc", - "id": "greptimecloud/overview", - "label": "Overview" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "doc", - "id": "greptimecloud/getting-started/overview", - "label": "Overview" - }, - "greptimecloud/getting-started/prometheus", - "greptimecloud/getting-started/mysql", - "greptimecloud/getting-started/influxdb", - "greptimecloud/getting-started/go", - "greptimecloud/getting-started/java", - "greptimecloud/getting-started/python", - "greptimecloud/getting-started/node", - "greptimecloud/getting-started/vector" - ] - }, - { - "type": "category", - "label": "Integrations", - "items": [ - "greptimecloud/integrations/prometheus", - "greptimecloud/integrations/grafana", - "greptimecloud/integrations/mysql", - "greptimecloud/integrations/postgresql", - "greptimecloud/integrations/influxdb", - "greptimecloud/integrations/kafka", - "greptimecloud/integrations/otlp", - "greptimecloud/integrations/vector", - "greptimecloud/integrations/alloy", - "greptimecloud/integrations/emqx", - "greptimecloud/integrations/streamlit", - "greptimecloud/integrations/superset", - "greptimecloud/integrations/metabase", - "greptimecloud/integrations/mindsdb", - "greptimecloud/integrations/dbeaver", - "greptimecloud/integrations/fluent-bit", - { - "type": "category", - "label": "SDK Libraries", - "items": [ - "greptimecloud/integrations/sdk-libraries/go", - "greptimecloud/integrations/sdk-libraries/java" - ] - } - ] - }, - { - "type": "category", - "label": "Migrate to GreptimeCloud", - "items": [ - "greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb", - "greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus" - ] - }, - { - "type": "category", - "label": "Usage & Billing", - "items": [ - { - "type": "doc", - "id": "greptimecloud/usage-&-billing/overview", - "label": "Overview" - }, - "greptimecloud/usage-&-billing/request-capacity-unit", - "greptimecloud/usage-&-billing/hobby", - "greptimecloud/usage-&-billing/serverless", - "greptimecloud/usage-&-billing/dedicated", - "greptimecloud/usage-&-billing/billing" - ] - } - ] - }, { "type": "category", "label": "GreptimeDB Enterprise", diff --git a/versioned_sidebars/version-1.0-sidebars.json b/versioned_sidebars/version-1.0-sidebars.json new file mode 100644 index 0000000000..87c560b499 --- /dev/null +++ b/versioned_sidebars/version-1.0-sidebars.json @@ -0,0 +1,861 @@ +{ + "docs": [ + { + "type": "doc", + "className": "hidden", + "id": "index" + }, + { + "type": "category", + "label": "Getting Started", + "items": [ + { + "type": "doc", + "id": "getting-started/overview", + "label": "Overview" + }, + { + "type": "category", + "label": "Installation", + "items": [ + { + "type": "doc", + "id": "getting-started/installation/overview", + "label": "Overview" + }, + "getting-started/installation/greptimedb-standalone", + "getting-started/installation/greptimedb-cluster", + "getting-started/installation/greptimedb-dashboard" + ] + }, + "getting-started/quick-start" + ] + }, + { + "type": "category", + "label": "User Guide", + "items": [ + { + "type": "doc", + "id": "user-guide/overview", + "label": "Overview" + }, + { + "type": "category", + "label": "Concepts", + "items": [ + { + "type": "doc", + "id": "user-guide/concepts/overview", + "label": "Overview" + }, + "user-guide/concepts/why-greptimedb", + "user-guide/concepts/data-model", + "user-guide/concepts/architecture", + "user-guide/concepts/storage-location", + "user-guide/concepts/key-concepts", + "user-guide/concepts/features-that-you-concern" + ] + }, + { + "type": "category", + "label": "Ingest Data", + "items": [ + { + "type": "doc", + "id": "user-guide/ingest-data/overview", + "label": "Overview" + }, + { + "type": "category", + "label": "For observability", + "items": [ + { + "type": "doc", + "id": "user-guide/ingest-data/for-observability/overview", + "label": "Overview" + }, + "user-guide/ingest-data/for-observability/prometheus", + "user-guide/ingest-data/for-observability/vector", + "user-guide/ingest-data/for-observability/opentelemetry", + "user-guide/ingest-data/for-observability/influxdb-line-protocol", + "user-guide/ingest-data/for-observability/kafka", + "user-guide/ingest-data/for-observability/loki", + "user-guide/ingest-data/for-observability/otel-collector", + "user-guide/ingest-data/for-observability/alloy", + "user-guide/ingest-data/for-observability/elasticsearch", + "user-guide/ingest-data/for-observability/fluent-bit" + ] + }, + { + "type": "category", + "label": "For IoT", + "items": [ + { + "type": "doc", + "id": "user-guide/ingest-data/for-iot/overview", + "label": "Overview" + }, + "user-guide/ingest-data/for-iot/sql", + { + "type": "category", + "label": "gRPC SDKs", + "items": [ + { + "type": "doc", + "id": "user-guide/ingest-data/for-iot/grpc-sdks/overview", + "label": "Overview" + }, + "user-guide/ingest-data/for-iot/grpc-sdks/go", + "user-guide/ingest-data/for-iot/grpc-sdks/java" + ] + }, + "user-guide/ingest-data/for-iot/influxdb-line-protocol", + "user-guide/ingest-data/for-iot/kafka", + "user-guide/ingest-data/for-iot/emqx", + "user-guide/ingest-data/for-iot/opentsdb" + ] + } + ] + }, + { + "type": "category", + "label": "Query Data", + "items": [ + { + "type": "doc", + "id": "user-guide/query-data/overview", + "label": "Overview" + }, + "user-guide/query-data/sql", + "user-guide/query-data/promql", + "user-guide/query-data/view", + "user-guide/query-data/cte", + "user-guide/query-data/query-external-data", + "user-guide/query-data/log-query", + "user-guide/query-data/jaeger" + ] + }, + { + "type": "category", + "label": "Manage Data", + "items": [ + { + "type": "doc", + "id": "user-guide/manage-data/overview", + "label": "Overview" + }, + "user-guide/manage-data/data-index" + ] + }, + { + "type": "category", + "label": "Integrations", + "items": [ + { + "type": "doc", + "id": "user-guide/integrations/overview", + "label": "Overview" + }, + "user-guide/integrations/prometheus", + "user-guide/integrations/vector", + "user-guide/integrations/kafka", + "user-guide/integrations/telegraf", + "user-guide/integrations/grafana", + "user-guide/integrations/superset", + "user-guide/integrations/metabase", + "user-guide/integrations/emqx", + "user-guide/integrations/dbeaver", + "user-guide/integrations/alloy", + "user-guide/integrations/streamlit", + "user-guide/integrations/mindsdb", + "user-guide/integrations/fluent-bit", + "user-guide/integrations/coroot", + "user-guide/integrations/mcp" + ] + }, + { + "type": "category", + "label": "Protocols", + "items": [ + { + "type": "doc", + "id": "user-guide/protocols/overview", + "label": "Overview" + }, + "user-guide/protocols/influxdb-line-protocol", + "user-guide/protocols/opentelemetry", + "user-guide/protocols/mysql", + "user-guide/protocols/postgresql", + "user-guide/protocols/http", + "user-guide/protocols/grpc", + "user-guide/protocols/opentsdb", + "user-guide/protocols/loki", + "user-guide/protocols/elasticsearch" + ] + }, + "user-guide/timezone", + { + "type": "category", + "label": "Migrate to GreptimeDB", + "items": [ + { + "type": "doc", + "id": "user-guide/migrate-to-greptimedb/overview", + "label": "Overview" + }, + "user-guide/migrate-to-greptimedb/migrate-from-influxdb", + "user-guide/migrate-to-greptimedb/migrate-from-clickhouse", + "user-guide/migrate-to-greptimedb/migrate-from-mysql", + "user-guide/migrate-to-greptimedb/migrate-from-postgresql", + "user-guide/migrate-to-greptimedb/migrate-from-prometheus" + ] + }, + { + "type": "category", + "label": "Flow Computation", + "items": [ + { + "type": "doc", + "id": "user-guide/flow-computation/overview", + "label": "Overview" + }, + "user-guide/flow-computation/continuous-aggregation", + "user-guide/flow-computation/manage-flow", + "user-guide/flow-computation/expressions" + ] + }, + { + "type": "category", + "label": "Logs", + "items": [ + { + "type": "doc", + "id": "user-guide/logs/overview", + "label": "Overview" + }, + "user-guide/logs/quick-start", + "user-guide/logs/use-custom-pipelines", + "user-guide/logs/fulltext-search", + "user-guide/logs/manage-pipelines" + ] + }, + { + "type": "category", + "label": "Traces", + "items": [ + { + "type": "doc", + "id": "user-guide/traces/overview", + "label": "Overview" + }, + "user-guide/traces/read-write", + "user-guide/traces/data-model", + "user-guide/traces/extend-trace" + ] + }, + { + "type": "category", + "label": "Vector Storage", + "items": [ + "user-guide/vectors/vector-type" + ] + }, + { + "type": "category", + "label": "Deployments & Administration", + "items": [ + { + "type": "doc", + "id": "user-guide/deployments-administration/overview", + "label": "Overview" + }, + { + "type": "category", + "label": "Kubernetes", + "items": [ + { + "type": "doc", + "id": "user-guide/deployments-administration/deploy-on-kubernetes/overview", + "label": "Overview" + }, + "user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-standalone", + "user-guide/deployments-administration/deploy-on-kubernetes/deploy-greptimedb-cluster", + "user-guide/deployments-administration/deploy-on-kubernetes/greptimedb-operator-management", + "user-guide/deployments-administration/deploy-on-kubernetes/common-helm-chart-configurations", + "user-guide/deployments-administration/deploy-on-kubernetes/configure-frontend-groups", + "user-guide/deployments-administration/deploy-on-kubernetes/configure-remote-wal" + ] + }, + { + "type": "category", + "label": "Manage Metadata", + "items": [ + "user-guide/deployments-administration/manage-metadata/overview", + "user-guide/deployments-administration/manage-metadata/configuration", + "user-guide/deployments-administration/manage-metadata/restore-backup", + "user-guide/deployments-administration/manage-metadata/manage-etcd" + ] + }, + { + "type": "category", + "label": "Write-Ahead Logging (WAL)", + "items": [ + "user-guide/deployments-administration/wal/overview", + "user-guide/deployments-administration/wal/local-wal", + { + "type": "category", + "label": "Remote WAL", + "items": [ + "user-guide/deployments-administration/wal/remote-wal/configuration", + "user-guide/deployments-administration/wal/remote-wal/manage-kafka" + ] + }, + "user-guide/deployments-administration/wal/noop-wal" + ] + }, + "user-guide/deployments-administration/configuration", + { + "type": "category", + "label": "Authentication", + "items": [ + { + "type": "doc", + "id": "user-guide/deployments-administration/authentication/overview", + "label": "Overview" + }, + "user-guide/deployments-administration/authentication/static" + ] + }, + { + "type": "category", + "label": "Monitoring", + "items": [ + { + "type": "doc", + "id": "user-guide/deployments-administration/monitoring/overview", + "label": "Overview" + }, + "user-guide/deployments-administration/monitoring/check-db-status", + "user-guide/deployments-administration/monitoring/standalone-monitoring", + "user-guide/deployments-administration/monitoring/cluster-monitoring-deployment", + "user-guide/deployments-administration/monitoring/monitor-cluster-with-prometheus", + "user-guide/deployments-administration/monitoring/key-logs", + "user-guide/deployments-administration/monitoring/tracing", + "user-guide/deployments-administration/monitoring/slow-query", + "user-guide/deployments-administration/monitoring/runtime-info" + ] + }, + "user-guide/deployments-administration/capacity-plan", + { + "type": "category", + "label": "Manage Data", + "items": [ + { + "type": "doc", + "id": "user-guide/deployments-administration/manage-data/overview", + "label": "Overview" + }, + "user-guide/deployments-administration/manage-data/basic-table-operations", + "user-guide/deployments-administration/manage-data/table-sharding", + "user-guide/deployments-administration/manage-data/region-migration", + "user-guide/deployments-administration/manage-data/region-failover", + "user-guide/deployments-administration/manage-data/compaction" + ] + }, + { + "type": "category", + "label": "Performance Tuning", + "items": [ + "user-guide/deployments-administration/performance-tuning/performance-tuning-tips", + "user-guide/deployments-administration/performance-tuning/design-table" + ] + }, + { + "type": "category", + "label": "Disaster Recovery", + "items": [ + { + "type": "doc", + "id": "user-guide/deployments-administration/disaster-recovery/overview", + "label": "Overview" + }, + "user-guide/deployments-administration/disaster-recovery/back-up-&-restore-data", + "user-guide/deployments-administration/disaster-recovery/back-up-&-restore-meta-data", + "user-guide/deployments-administration/disaster-recovery/dr-solution-based-on-cross-region-deployment-in-single-cluster" + ] + }, + { + "type": "category", + "label": "Maintenance", + "items": [ + "user-guide/deployments-administration/maintenance/maintenance-mode", + "user-guide/deployments-administration/maintenance/recovery-mode", + "user-guide/deployments-administration/maintenance/prevent-metadata-changes", + "user-guide/deployments-administration/maintenance/sequence-management", + "user-guide/deployments-administration/maintenance/table-reconciliation" + ] + }, + "user-guide/deployments-administration/troubleshooting", + "user-guide/deployments-administration/run-on-android", + "user-guide/deployments-administration/upgrade" + ] + } + ] + }, + { + "type": "category", + "label": "Tutorials", + "items": [ + "tutorials/k8s-metrics-monitor" + ] + }, + { + "type": "category", + "label": "GreptimeCloud", + "items": [ + { + "type": "doc", + "id": "greptimecloud/overview", + "label": "Overview" + }, + { + "type": "category", + "label": "Getting Started", + "items": [ + { + "type": "doc", + "id": "greptimecloud/getting-started/overview", + "label": "Overview" + }, + "greptimecloud/getting-started/prometheus", + "greptimecloud/getting-started/mysql", + "greptimecloud/getting-started/influxdb", + "greptimecloud/getting-started/go", + "greptimecloud/getting-started/java", + "greptimecloud/getting-started/python", + "greptimecloud/getting-started/node", + "greptimecloud/getting-started/vector" + ] + }, + { + "type": "category", + "label": "Integrations", + "items": [ + "greptimecloud/integrations/prometheus", + "greptimecloud/integrations/grafana", + "greptimecloud/integrations/mysql", + "greptimecloud/integrations/postgresql", + "greptimecloud/integrations/influxdb", + "greptimecloud/integrations/kafka", + "greptimecloud/integrations/otlp", + "greptimecloud/integrations/vector", + "greptimecloud/integrations/alloy", + "greptimecloud/integrations/emqx", + "greptimecloud/integrations/streamlit", + "greptimecloud/integrations/superset", + "greptimecloud/integrations/metabase", + "greptimecloud/integrations/mindsdb", + "greptimecloud/integrations/dbeaver", + "greptimecloud/integrations/fluent-bit", + { + "type": "category", + "label": "SDK Libraries", + "items": [ + "greptimecloud/integrations/sdk-libraries/go", + "greptimecloud/integrations/sdk-libraries/java" + ] + } + ] + }, + { + "type": "category", + "label": "Migrate to GreptimeCloud", + "items": [ + "greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb", + "greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus" + ] + }, + { + "type": "category", + "label": "Usage & Billing", + "items": [ + { + "type": "doc", + "id": "greptimecloud/usage-&-billing/overview", + "label": "Overview" + }, + "greptimecloud/usage-&-billing/request-capacity-unit", + "greptimecloud/usage-&-billing/hobby", + "greptimecloud/usage-&-billing/serverless", + "greptimecloud/usage-&-billing/dedicated", + "greptimecloud/usage-&-billing/billing" + ] + } + ] + }, + { + "type": "category", + "label": "GreptimeDB Enterprise", + "items": [ + { + "type": "doc", + "id": "enterprise/overview", + "label": "Overview" + }, + { + "type": "category", + "label": "Deployments & Administration", + "items": [ + { + "type": "doc", + "id": "enterprise/deployments-administration/overview", + "label": "Overview" + }, + { + "type": "category", + "label": "Kubernetes", + "items": [ + { + "type": "doc", + "id": "enterprise/deployments-administration/deploy-on-kubernetes/overview", + "label": "Overview" + }, + "enterprise/deployments-administration/deploy-on-kubernetes/installation", + "enterprise/deployments-administration/deploy-on-kubernetes/upgrade", + "enterprise/deployments-administration/deploy-on-kubernetes/configure-datanode-groups" + ] + }, + "enterprise/deployments-administration/authentication", + { + "type": "category", + "label": "Monitoring", + "items": [ + { + "type": "doc", + "id": "enterprise/deployments-administration/monitoring/overview", + "label": "Overview" + }, + "enterprise/deployments-administration/monitoring/self-monitor-cluster", + "enterprise/deployments-administration/monitoring/check-db-status", + "enterprise/deployments-administration/monitoring/key-metrics", + "enterprise/deployments-administration/monitoring/key-logs", + "enterprise/deployments-administration/monitoring/audit-logging" + ] + }, + { + "type": "category", + "label": "Disaster Recovery", + "items": [ + { + "type": "doc", + "id": "enterprise/deployments-administration/disaster-recovery/overview", + "label": "Overview" + }, + "enterprise/deployments-administration/disaster-recovery/dr-solution-based-on-active-active-failover" + ] + }, + "enterprise/deployments-administration/backup" + ] + }, + { + "type": "category", + "label": "Autopilot", + "items": [ + "enterprise/autopilot/region-balancer" + ] + }, + { + "type": "category", + "label": "Elasticsearch Compatibility", + "items": [ + "enterprise/elasticsearch-compatible/overview", + "enterprise/elasticsearch-compatible/query", + "enterprise/elasticsearch-compatible/aggregate" + ] + }, + "enterprise/console-ui", + { + "type": "category", + "label": "Read Replicas", + "items": [ + "enterprise/read-replicas/overview", + "enterprise/read-replicas/manage-read-replicas", + "enterprise/read-replicas/query-read-replicas" + ] + }, + "enterprise/trigger", + { + "type": "category", + "label": "Releases", + "items": [ + "enterprise/release-notes/release-25_05", + "enterprise/release-notes/release-24_11" + ] + } + ] + }, + { + "type": "category", + "label": "Reference", + "items": [ + "reference/glossary", + { + "type": "category", + "label": "GreptimeDB Command Line Interface", + "items": [ + "reference/command-lines/overview", + "reference/command-lines/metasrv", + "reference/command-lines/datanode", + "reference/command-lines/flownode", + "reference/command-lines/frontend", + "reference/command-lines/standalone", + { + "type": "category", + "label": "Utilities", + "items": [ + "reference/command-lines/utilities/data", + "reference/command-lines/utilities/metadata", + "reference/command-lines/utilities/metadata-interaction", + "reference/command-lines/utilities/repair-logical-tables" + ] + } + ] + }, + "reference/sql-tools", + "reference/time-durations", + "reference/about-greptimedb-engines", + { + "type": "category", + "label": "SQL", + "items": [ + { + "type": "doc", + "id": "reference/sql/overview", + "label": "Overview" + }, + "reference/sql/data-types", + "reference/sql/alter", + "reference/sql/case", + "reference/sql/cast", + "reference/sql/copy", + "reference/sql/create", + "reference/sql/delete", + "reference/sql/describe_table", + "reference/sql/distinct", + "reference/sql/drop", + "reference/sql/explain", + "reference/sql/group_by", + "reference/sql/having", + "reference/sql/insert", + "reference/sql/join", + "reference/sql/limit", + "reference/sql/offset", + "reference/sql/order_by", + "reference/sql/range", + "reference/sql/replace", + "reference/sql/select", + "reference/sql/show", + "reference/sql/tql", + "reference/sql/truncate", + "reference/sql/where", + "reference/sql/with", + "reference/sql/trigger-syntax", + { + "type": "category", + "label": "Functions", + "items": [ + { + "type": "doc", + "id": "reference/sql/functions/overview", + "label": "Overview" + }, + "reference/sql/functions/df-functions", + "reference/sql/functions/geo", + "reference/sql/functions/ip", + "reference/sql/functions/json", + "reference/sql/functions/vector", + "reference/sql/functions/approximate" + ] + }, + "reference/sql/admin", + "reference/sql/compatibility", + { + "type": "category", + "label": "Greptime Private", + "items": [ + { + "type": "doc", + "id": "reference/sql/greptime-private/overview", + "label": "Overview" + }, + "reference/sql/greptime-private/slow_queries", + "reference/sql/greptime-private/pipelines" + ] + }, + { + "type": "category", + "label": "Information Schema", + "items": [ + { + "type": "doc", + "id": "reference/sql/information-schema/overview", + "label": "Overview" + }, + "reference/sql/information-schema/build-info", + "reference/sql/information-schema/character-sets", + "reference/sql/information-schema/collations", + "reference/sql/information-schema/collation-character-set-applicability", + "reference/sql/information-schema/columns", + "reference/sql/information-schema/engines", + "reference/sql/information-schema/key-column-usage", + "reference/sql/information-schema/partitions", + "reference/sql/information-schema/procedure-info", + "reference/sql/information-schema/schemata", + "reference/sql/information-schema/tables", + "reference/sql/information-schema/table-constraints", + "reference/sql/information-schema/views", + "reference/sql/information-schema/flows", + "reference/sql/information-schema/region-peers", + "reference/sql/information-schema/region-statistics", + "reference/sql/information-schema/runtime-metrics", + "reference/sql/information-schema/cluster-info", + "reference/sql/information-schema/process-list", + "reference/sql/information-schema/ssts-index-meta", + "reference/sql/information-schema/ssts-manifest", + "reference/sql/information-schema/ssts-storage" + ] + } + ] + }, + { + "type": "category", + "label": "Pipeline", + "items": [ + "reference/pipeline/built-in-pipelines", + "reference/pipeline/write-log-api", + "reference/pipeline/pipeline-config" + ] + }, + "reference/http-endpoints", + "reference/telemetry", + "reference/gtctl" + ] + }, + { + "type": "category", + "label": "Contributor Guide", + "items": [ + { + "type": "doc", + "id": "contributor-guide/overview", + "label": "Overview" + }, + "contributor-guide/getting-started", + { + "type": "category", + "label": "Frontend", + "items": [ + { + "type": "doc", + "id": "contributor-guide/frontend/overview", + "label": "Overview" + }, + "contributor-guide/frontend/table-sharding", + "contributor-guide/frontend/distributed-querying" + ] + }, + { + "type": "category", + "label": "Datanode", + "items": [ + { + "type": "doc", + "id": "contributor-guide/datanode/overview", + "label": "Overview" + }, + "contributor-guide/datanode/storage-engine", + "contributor-guide/datanode/query-engine", + "contributor-guide/datanode/data-persistence-indexing", + "contributor-guide/datanode/wal", + "contributor-guide/datanode/metric-engine" + ] + }, + { + "type": "category", + "label": "Metasrv", + "items": [ + { + "type": "doc", + "id": "contributor-guide/metasrv/overview", + "label": "Overview" + }, + "contributor-guide/metasrv/admin-api", + "contributor-guide/metasrv/selector" + ] + }, + { + "type": "category", + "label": "Flownode", + "items": [ + { + "type": "doc", + "id": "contributor-guide/flownode/overview", + "label": "Overview" + }, + "contributor-guide/flownode/batching_mode", + "contributor-guide/flownode/dataflow", + "contributor-guide/flownode/arrangement" + ] + }, + { + "type": "category", + "label": "Tests", + "items": [ + { + "type": "doc", + "id": "contributor-guide/tests/overview", + "label": "Overview" + }, + "contributor-guide/tests/unit-test", + "contributor-guide/tests/integration-test", + "contributor-guide/tests/sqlness-test" + ] + }, + { + "type": "category", + "label": "How To", + "items": [ + "contributor-guide/how-to/how-to-write-sdk", + "contributor-guide/how-to/how-to-use-tokio-console", + "contributor-guide/how-to/how-to-trace-greptimedb" + ] + } + ] + }, + { + "type": "category", + "label": "Release Notes", + "items": [ + "reference/about-greptimedb-version", + { + "type": "link", + "label": "Releases", + "href": "/release-notes" + } + ] + }, + { + "type": "category", + "label": "FAQ and Others", + "items": [ + { + "type": "doc", + "id": "faq-and-others/overview", + "label": "Overview" + }, + "faq-and-others/faq" + ] + } + ] +} diff --git a/versions.json b/versions.json index 7af34c6b94..9d9ef45a48 100644 --- a/versions.json +++ b/versions.json @@ -1,4 +1,5 @@ [ + "1.0", "0.17", "0.16", "0.15",