influxdb

package
v0.0.0-...-256bcdb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2024 License: BSD-3-Clause Imports: 24 Imported by: 0

README

Influxdb v1.x 客户端

  • 本包内部不处理db、rp、measurement、tag key、field key特殊命名问题,由调用方保证符合influxdb规范,建议参考下面的命名规范
  • 对于tag value、field value中特殊字符,基于经验做了一定的转义处理,详见 EscapeXXX 系列函数,如果使用 RawQuery|RawWrite 则需自行处理转义逻辑

db、rp、measurement、tag key、field key命名规范

  • 大小写敏感:统一使用小写字母
  • 字符限制:
    • 以字母开头,可包含字母、数字、下划线、连接符
    • 避免使用其他特殊字符
    • 避免使用保留字
  • 长度限制:没有严格的长度限制,但建议保持名称简短且具描述性
  • 保持一致性:在整个数据库中保持一致的命名约定,便于管理和查询

tag value、field value格式

  • 由于行协议和influxQL语法差异,在读写数据时对值格式的要求不同,所以读写时转义逻辑也不同
  • 写入数据:
    • tag value不能用双引号包裹,field value如果是字符值必须用双引号包裹,所以转义逻辑应该区分对待
  • 查询数据:
    • tag value和field value都是以单引号包裹,time字段和数值型field value除外
  • tag字段通常用于索引和过滤,因此它们的值应该具有较低的基数(即重复率高),基数太大的话会导致内存占用过高
  • field字段用于存储实际的测量值,具有较高的基数

数据类型

常见问题

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EscapeCondValue

func EscapeCondValue(s string, isFieldVal ...bool) string

EscapeCondValue 查询数据时,需要将条件值中部分字符进行转义

 由于tag和field写入时转义稍有差别,所以查询条件也需要区分,通常都是用tag字段作为条件,如果是field字段,需要额外指定 isFieldVal=true
	https://docs.influxdata.com/influxdb/v1/query_language/data_exploration/#string-literals

func EscapeFieldValue

func EscapeFieldValue(s string) string

EscapeFieldValue 写入数据时,需要将field值中不合规的字符进行转义

func EscapeTagTailBackslash

func EscapeTagTailBackslash(s string) string

EscapeTagTailBackslash 写入数据时,标签字段尾部的反斜杠会对后面的空格进行转义,导致行协议无法正确解析,所以需要额外处理,查询时也需要对齐

func EscapeTagValue

func EscapeTagValue(s string) string

EscapeTagValue 写入数据时,需要将tag字段值中不合规的字符进行转义

行协议:https://docs.influxdata.com/influxdb/v1/write_protocols/line_protocol_reference

func FormatMeasurement

func FormatMeasurement(s string) string

FormatMeasurement 统一measurement命名规范,避免特殊字符

func Quote

func Quote(s string) string

Quote 给字符串加上双引号

func QuoteIfNeed

func QuoteIfNeed(s string) string

QuoteIfNeed 如有必要,给字段的Key加上双引号,否则返回原字符串

https://docs.influxdata.com/influxdb/v1/query_language/explore-data/#quoting

func SingleQuote

func SingleQuote(s string) string

SingleQuote 给查询条件值加上单引号

https://docs.influxdata.com/influxdb/v1/troubleshooting/frequently-asked-questions/#when-should-i-single-quote-and-when-should-i-double-quote-in-queries

func UnescapeQueryResultValue

func UnescapeQueryResultValue(s string) string

UnescapeQueryResultValue 还原查询结果中tag、field值的转义

写入时(RawWrite除外)tag、field值转义时都移除了前后空格,唯一特殊情况是以反斜杠结尾的tag字段,特殊追加了一个空格,所以查询结果中需要去掉,以保持一致

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(addr string, opts ...Option) *Client

func (*Client) AlterRetentionPolicy

func (this *Client) AlterRetentionPolicy(db string, rp *RetentionPolicy) error

func (*Client) Close

func (this *Client) Close()

Close 关闭客户端,释放资源

!!!务必在程序退出时调用,否则可能会导致数据丢失!!!

func (*Client) CreateDatabase

func (this *Client) CreateDatabase(db string) (bool, error)

func (*Client) CreateRetentionPolicy

func (this *Client) CreateRetentionPolicy(db string, rp *RetentionPolicy) (bool, error)

func (*Client) DropDatabase

func (this *Client) DropDatabase(db string) error

func (*Client) DropMeasurement

func (this *Client) DropMeasurement(db, measurement string) error

func (*Client) DropRetentionPolicy

func (this *Client) DropRetentionPolicy(db, rp string) error

func (*Client) Flush

func (this *Client) Flush()

Flush 强制刷新写入,立即将所有缓存的数据写入InfluxDB,一般无需手动调用

func (*Client) NewQuery

func (this *Client) NewQuery() *Query

func (*Client) Printf

func (this *Client) Printf(format string, args ...interface{})

Printf ants.Logger实现

func (*Client) RawQuery

func (this *Client) RawQuery(db, sql string) ([]*Series, error)

RawQuery 执行查询语句

func (*Client) RawWrite

func (this *Client) RawWrite(db, rp string, lines []string) error

RawWrite 执行写入操作

  • db: 数据库名,必须指定
  • rp: 保留策略名,为空时使用默认
  • lines: 符合influxdb行协议的数据,需自行处理转义

func (*Client) ShowDatabases

func (this *Client) ShowDatabases() ([]string, error)

func (*Client) ShowFieldKeys

func (this *Client) ShowFieldKeys(db, measurement string) ([]string, error)

func (*Client) ShowMeasurements

func (this *Client) ShowMeasurements(db string) ([]string, error)

func (*Client) ShowRetentionPolicies

func (this *Client) ShowRetentionPolicies(db string) ([]*RetentionPolicy, error)

func (*Client) ShowSeries

func (this *Client) ShowSeries(db, measurement string) ([]string, error)

func (*Client) ShowTagKeys

func (this *Client) ShowTagKeys(db, measurement string) ([]string, error)

func (*Client) Write

func (this *Client) Write(db, rp string, points []*Point, immediate bool) error

Write 写入数据

  • db: 数据库名,必须指定
  • rp: 保留策略名,为空时使用默认
  • points: 数据点
  • immediate: 是否立即写入

type ICond

type ICond interface {
	IsValid() bool
	And(...ICond) ICond
	Or(...ICond) ICond
	String() string
}

func And

func And(arr ...ICond) ICond

func Between

func Between(col string, less, more interface{}) ICond

Between 左右均为闭区间

func BetweenOpen

func BetweenOpen(col string, less, more interface{}) ICond

func BetweenOpenL

func BetweenOpenL(col string, less, more interface{}) ICond

func BetweenOpenR

func BetweenOpenR(col string, less, more interface{}) ICond

func Expr

func Expr(col, opr string, val interface{}) ICond

Expr 表达式

  • col: 字段名,支持tag字段(包含time)
  • opr: 操作符,支持 =, !=, >, <, >=, <=, <>, =~, !~
  • val: 字段值,支持数值、字符串

func In

func In(col string, values ...interface{}) ICond

func Match

func Match(col, pattern string) ICond

Match 模糊匹配

https://docs.influxdata.com/influxdb/v1/query_language/explore-data/#regular-expressions
!!! 注意:正则表达式匹配性能较差,尽量避免使用 !!!

func NewCond

func NewCond() ICond

func NotIn

func NotIn(col string, values ...interface{}) ICond

func NotMatch

func NotMatch(col, pattern string) ICond

NotMatch 不匹配

!!! 注意:正则表达式匹配性能较差,尽量避免使用 !!!

func Or

func Or(arr ...ICond) ICond

Or 或条件

!!!注意时间字段不能使用 OR 连接,否则会返回空结果!!!
https://docs.influxdata.com/influxdb/v1/troubleshooting/frequently-asked-questions/#why-is-my-query-with-a-where-or-time-clause-returning-empty-results

func RawExpr

func RawExpr(expr string) ICond

RawExpr 表达式

type Option

type Option func(*Client)

func WithAuth

func WithAuth(username, password string) Option

func WithFlushInterval

func WithFlushInterval(interval time.Duration) Option

WithFlushInterval 设置异步写入数据的时间间隔

func WithFlushSize

func WithFlushSize(size int) Option

WithFlushSize 设置异步写入数据的行数上限, 最大不超过 bucketSize

func WithGroupSize

func WithGroupSize(size int) Option

WithGroupSize 设置每组桶的数量,默认16

func WithLogger

func WithLogger(logger logs.Logger) Option

func WithLoggerLevel

func WithLoggerLevel(level int) Option

func WithQueryEpoch

func WithQueryEpoch(epoch string) Option

WithQueryEpoch 设置查询返回的时间格式, 默认s, 可选值:ns, u, ms, s, m, h

influxdb默认返回的时间是RFC3339格式,如果需要返回时间戳,需要通过epoch参数指定

func WithWritePoolSize

func WithWritePoolSize(n int) Option

WithWritePoolSize 设置最大写入并发

func WithWritePrecision

func WithWritePrecision(precision string) Option

WithWritePrecision 设置写入数据的时间精度, 默认s, 可选值:ns, u, ms, s, m, h

func WithWriteSortTagKey

func WithWriteSortTagKey(sort bool) Option

type Point

type Point struct {
	Measurement string                 // 表名,必须指定
	Tags        map[string]interface{} // tag字段
	Fields      map[string]interface{} // field字段
	Time        int64                  // 时间戳,不传时数据库会自动写入当前时间
}

Point 数据点

注意:写入精度默认为秒,可以通过 WithWritePrecision 设置

func (*Point) ToLineData

func (p *Point) ToLineData(sortTagKey bool) string

ToLineData 转换为行协议数据

行协议:<measurement>[,<tag_key>=<tag_value>[,<tag_key>=<tag_value>]] <field_key>=<field_value>[,<field_key>=<field_value>] [<timestamp>]

type Query

type Query struct {
	// contains filtered or unexported fields
}

func (*Query) Asc

func (this *Query) Asc(field string) *Query

func (*Query) Desc

func (this *Query) Desc(field string) *Query

func (*Query) Do

func (this *Query) Do() ([]*Series, error)

func (*Query) From

func (this *Query) From(db, rp string, measurements ...string) *Query

From 设置查询的来源

  • db: 数据库名,必须指定
  • rp: 保留策略名,为空时使用默认
  • measurements: 表名,必须指定,可以多个

func (*Query) GroupBy

func (this *Query) GroupBy(groupBy string) *Query

GroupBy 设置分组字段

注意:内部会自动添加`GROUP BY`前缀,外部需要处理字段双引号

func (*Query) Limit

func (this *Query) Limit(limit int) *Query

func (*Query) OrderBy

func (this *Query) OrderBy(orderBy string) *Query

OrderBy 设置排序字段

注意:内部会自动添加`ORDER BY`前缀,外部需要处理字段双引号

func (*Query) Select

func (this *Query) Select(fields ...string) *Query

func (*Query) String

func (this *Query) String() string

func (*Query) TimeZone

func (this *Query) TimeZone(tz string) *Query

func (*Query) Where

func (this *Query) Where(cond ICond) *Query

type RetentionPolicy

type RetentionPolicy struct {
	Name               string `json:"name"`
	Duration           string `json:"duration"`           // "8760h0m0s"
	ShardGroupDuration string `json:"shardGroupDuration"` // "168h0m0s"
	Replication        int    `json:"replication"`        // 副本数量
	Default            bool   `json:"default"`            // 是否默认策略
}

type Series

type Series struct {
	Name    string            `json:"name,omitempty"` // 表名,多表查询时有用
	Tags    map[string]string `json:"tags,omitempty"`
	Columns []string          `json:"columns"`
	Values  [][]interface{}   `json:"values"`
}

func (*Series) ToStringObjectMap

func (this *Series) ToStringObjectMap() []mapUtil.StringObjectMap

ToStringObjectMap converts the Series to a slice of mapUtil.StringObjectMap.

[
	{column1: value1, column2: value2, ...}, // row 1
	{column1: value1, column2: value2, ...}, // row 2
	...
]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL