client

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2024 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package client (v2) is the current official Go client for InfluxDB.

Index

Examples

Constants

View Source
const (
	//MyDB = "NOAA_water_database"
	MyDB = "test"
)

数据库名称

View Source
const STRINGBYTELENGTH = 24

结果转换成字节数组时string类型占用字节数

View Source
const TimeSize = "8m"

fatcache 设置存入的时间间隔 "1.5h" "15m"

View Source
const (
	// UDPPayloadSize is a reasonable default payload size for UDP packets that
	// could be travelling over the internet.
	UDPPayloadSize = 512
)

Variables

View Source
var Fields = GetFieldKeys(c, MyDB)
View Source
var QueryTemplates = make(map[string]string) // 存放查询模版及其语义段;查询模板只替换了时间范围,语义段没变
View Source
var TagKV = GetTagKV(c, MyDB)

数据库中所有表的tag和field

Functions

func BoolToByteArray

func BoolToByteArray(b bool) ([]byte, error)

所有转换都是 小端序

func ByteArrayToBool

func ByteArrayToBool(byteArray []byte) (bool, error)

func ByteArrayToFloat64

func ByteArrayToFloat64(byteArray []byte) (float64, error)

func ByteArrayToInt64

func ByteArrayToInt64(byteArray []byte) (int64, error)

func ByteArrayToString

func ByteArrayToString(byteArray []byte) string

func BytesPerLine

func BytesPerLine(datatypes []string) int

BytesPerLine 根据一行中所有列的数据类型计算转换成字节数组后一行的总字节数

func FieldsAndAggregation

func FieldsAndAggregation(queryString string, measurementName string) (string, string)

FieldsAndAggregation 列名 和 聚合函数名称

func Float64ToByteArray

func Float64ToByteArray(number float64) ([]byte, error)

func GetAggregation

func GetAggregation(queryString string) string

GetAggregation 从查询语句中获取聚合函数

func GetDataTypeArrayFromResponse

func GetDataTypeArrayFromResponse(resp *Response) []string

GetDataTypeArrayFromResponse 从查寻结果中获取每一列的数据类型

func GetDataTypeArrayFromSF

func GetDataTypeArrayFromSF(sfString string) []string

GetDataTypeArrayFromSF 从列名和数据类型组成的字符串中提取出每一列的数据类型 time[int64],index[int64],location[string],randtag[string] 列名和数据类型都存放在数组中,顺序是固定的,不用手动排序,直接取出来就行

func GetFieldKeys

func GetFieldKeys(c Client, database string) map[string]map[string]string

GetFieldKeys 获取一个数据库中所有表的field name及其数据类型

func GetFromFatcache

func GetFromFatcache(queryString string, timeSize string) [][]byte

按时间尺度分块,向 Fatcache 查询,返回结果的原始字节流

func GetInterval

func GetInterval(query string) string

GetInterval 获取 GROUP BY interval

func GetNumOfTable

func GetNumOfTable(resp *Response) int64

GetNumOfTable 获取查询结果中表的数量

func GetQueryTemplate

func GetQueryTemplate(queryString string) string

GetQueryTemplate 用 "?" 替换查询语句的时间范围,重新排列符号,重构为查询模版

func GetQueryTimeRange

func GetQueryTimeRange(queryString string) (int64, int64)

GetQueryTimeRange 获取一条查询语句的时间范围 单位为秒 "s"

func GetResponseTimeRange

func GetResponseTimeRange(resp *Response) (int64, int64)

GetResponseTimeRange 获取查询结果的时间范围 从 response 中取数据,可以确保起止时间都有,只需要进行类型转换

func GetSFSG

func GetSFSG(query string) (string, string)

func GetSFSGWithDataType

func GetSFSGWithDataType(queryString string, resp *Response) (string, string)

GetSFSGWithDataType 重写,包含数据类型和列名

func GetSM

func GetSM(resp *Response, tagPredicates []string) string

GetSM get measurement's name and tags func GetSM(queryString string, resp *Response) string {

func GetSP

func GetSP(query string, resp *Response, tagMap MeasurementTagMap) (string, []string)

只获取谓词,不要时间范围

func GetSPST

func GetSPST(query string) string

SP 和 ST 都可以在这个函数中取到 条件判断谓词和查询时间范围

func GetSemanticSegment

func GetSemanticSegment(queryString string) string

GetSemanticSegment 重构根据查询语句生成语义段的功能

func GetSeperateSM

func GetSeperateSM(resp *Response, tagPredicates []string) []string

分别返回每张表的tag

func GetSeperateSemanticSegment

func GetSeperateSemanticSegment(queryString string) []string

GetSeperateSemanticSegment 获取每张子表的 SM

func GetSeriesTagsMap

func GetSeriesTagsMap(resp *Response) map[int]map[string]string

GetSeriesTagsMap (表按字典序排列)获取一个结果(Response)中的所有表(Series)的所有tag( map[string]string )

func GetTagNameArr

func GetTagNameArr(resp *Response) []string

GetTagNameArr 判断结果是否为空,并从结果中取出tags数组,用于规范tag map的输出顺序

func GroupByTags

func GroupByTags(queryString string, measurementName string) []string

GroupByTags GROUP BY 后面的 tags 的所有值

func Int64ToByteArray

func Int64ToByteArray(number int64) ([]byte, error)

func IntegratedClient

func IntegratedClient(queryString string)
 STsCache

	1. 客户端接收查询语句
	2. 客户端向 cache 系统查询,得到部分结果
	3. 生成这条查询语句的模版,把时间范围用占位符替换
	4. 得到要向数据库查询的时间范围,带入模版,向数据库查询剩余数据
	5. 客户端把剩余数据存入 cache

func IntegratedSM

func IntegratedSM(measurementName string, tagConds []string, tags []string) string

IntegratedSM 重构的构造 SM 字段的方法

func InterfaceToByteArray

func InterfaceToByteArray(index int, datatype string, value interface{}) []byte

InterfaceToByteArray 把查询结果的 interface{} 类型转换为 []byte

index: 数据所在列的序号,第一列的时间戳如果是字符串要先转换成 int64
datatype: 所在列的数据类型,决定转换的方法
value: 待转换的数据

func MeasurementName

func MeasurementName(queryString string) string

MeasurementName 度量名称

func PredicatesAndTagConditions

func PredicatesAndTagConditions(query string, measurement string, tagMap MeasurementTagMap) (string, []string)

PredicatesAndTagConditions 条件谓词,区分出 field 的谓词和 tag 的谓词

func ResponseIsEmpty

func ResponseIsEmpty(resp *Response) bool

ResponseIsEmpty 判断结果是否为空

func ResponseToByteArray

func ResponseToByteArray(resp *Response, queryString string) []byte

ResponseToByteArray 把数据库的查询结果转换为字节流

func SemanticSegment

func SemanticSegment(queryString string, response *Response) string

SemanticSegment 根据查询语句和数据库返回数据组成字段,用作存入cache的key

func SeperateSM

func SeperateSM(integratedSM string) []string

func SeperateSemanticSegment

func SeperateSemanticSegment(queryString string, response *Response) []string

SeperateSemanticSegment 每个子表的语义段

func SeriesToRow

func SeriesToRow(ser Series) models.Row

SeriesToRow 转换成可以替换到结果中的结构体

func SetToFatache

func SetToFatache(queryString string, timeSize string)

按时间尺度分块,存入 cache

func SplitResponseValuesByTime

func SplitResponseValuesByTime(queryString string, resp *Response, timeSize string) ([][][][]interface{}, []int64, []int64)
Fatcache

根据时间尺度分割查询结果 返回分块后的数据,以及每块对应的查询语句时间字符串

func StringToByteArray

func StringToByteArray(str string) []byte

func TSCacheParameter

func TSCacheParameter(resp *Response) ([][]string, [][]int64, [][][]byte)

获取把查询结果转换成字节流所需的数据,包括 列名、每列数据的总长度、每列的具体数据

func TSCacheValueToByte

func TSCacheValueToByte(resp *Response) []byte
用于 TSCache, 按列存储的形式

把查询结果转换成字节流

func TagsMapToString

func TagsMapToString(tagsMap map[string]string) string

TagsMapToString 按字典序把一张表中的所有tags组合成字符串

func TimeInt64ToString

func TimeInt64ToString(number int64) string

int64 时间戳转换为 RFC3339 格式字符串 "2019-08-18T00:00:00Z"

func TimeStringToInt64

func TimeStringToInt64(timestamp string) int64

RFC3339 字符串转换为 int64 时间戳

Types

type BatchPoints

type BatchPoints interface {
	// AddPoint adds the given point to the Batch of points.
	AddPoint(p *Point)
	// AddPoints adds the given points to the Batch of points.
	AddPoints(ps []*Point)
	// Points lists the points in the Batch.
	Points() []*Point

	// Precision returns the currently set precision of this Batch.
	Precision() string
	// SetPrecision sets the precision of this batch.
	SetPrecision(s string) error

	// Database returns the currently set database of this Batch.
	Database() string
	// SetDatabase sets the database of this Batch.
	SetDatabase(s string)

	// WriteConsistency returns the currently set write consistency of this Batch.
	WriteConsistency() string
	// SetWriteConsistency sets the write consistency of this Batch.
	SetWriteConsistency(s string)

	// RetentionPolicy returns the currently set retention policy of this Batch.
	RetentionPolicy() string
	// SetRetentionPolicy sets the retention policy of this Batch.
	SetRetentionPolicy(s string)
}

BatchPoints is an interface into a batched grouping of points to write into InfluxDB together. BatchPoints is NOT thread-safe, you must create a separate batch for each goroutine.

Example

Create a batch and add a point

// Create a new point batch
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
	Database:  "BumbleBeeTuna",
	Precision: "s",
})

// Create a point and add to batch
tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
	"idle":   10.1,
	"system": 53.3,
	"user":   46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
if err != nil {
	fmt.Println("Error: ", err.Error())
}
bp.AddPoint(pt)
Output:

Example (Setters)

Using the BatchPoints setter functions

// Create a new point batch
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{})
bp.SetDatabase("BumbleBeeTuna")
bp.SetPrecision("ms")

// Create a point and add to batch
tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
	"idle":   10.1,
	"system": 53.3,
	"user":   46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
if err != nil {
	fmt.Println("Error: ", err.Error())
}
bp.AddPoint(pt)
Output:

func NewBatchPoints

func NewBatchPoints(conf BatchPointsConfig) (BatchPoints, error)

NewBatchPoints returns a BatchPoints interface based on the given config.

type BatchPointsConfig

type BatchPointsConfig struct {
	// Precision is the write precision of the points, defaults to "ns".
	Precision string

	// Database is the database to write points to.
	Database string

	// RetentionPolicy is the retention policy of the points.
	RetentionPolicy string

	// Write consistency is the number of servers required to confirm write.
	WriteConsistency string
}

BatchPointsConfig is the config data needed to create an instance of the BatchPoints struct.

type BooleanValue

type BooleanValue bool

BooleanValue is a boolean literal.

func (BooleanValue) MarshalJSON

func (v BooleanValue) MarshalJSON() ([]byte, error)

type ChunkedResponse

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

ChunkedResponse represents a response from the server that uses chunking to stream the output.

func NewChunkedResponse

func NewChunkedResponse(r io.Reader) *ChunkedResponse

NewChunkedResponse reads a stream and produces responses from the stream.

func (*ChunkedResponse) Close

func (r *ChunkedResponse) Close() error

Close closes the response.

func (*ChunkedResponse) NextResponse

func (r *ChunkedResponse) NextResponse() (*Response, error)

NextResponse reads the next line of the stream and returns a response.

type Client

type Client interface {
	// Ping checks that status of cluster, and will always return 0 time and no
	// error for UDP clients.
	Ping(timeout time.Duration) (time.Duration, string, error)

	// Write takes a BatchPoints object and writes all Points to InfluxDB.
	Write(bp BatchPoints) error

	// Query makes an InfluxDB Query on the database. This will fail if using
	// the UDP client.
	Query(q Query) (*Response, error)

	// QueryAsChunk makes an InfluxDB Query on the database. This will fail if using
	// the UDP client.
	QueryAsChunk(q Query) (*ChunkedResponse, error)

	// Close releases any resources a Client may be using.
	Close() error
}

Client is a client interface for writing & querying the database.

Example

Create a new client

// NOTE: this assumes you've setup a user and have setup shell env variables,
// namely INFLUX_USER/INFLUX_PWD. If not just omit Username/Password below.
_, err := client.NewHTTPClient(client.HTTPConfig{
	Addr:     "http://localhost:8086",
	Username: os.Getenv("INFLUX_USER"),
	Password: os.Getenv("INFLUX_PWD"),
})
if err != nil {
	fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
Output:

Example (CreateDatabase)

Create a Database with a query

// Make client
c, err := client.NewHTTPClient(client.HTTPConfig{
	Addr: "http://localhost:8086",
})
if err != nil {
	fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
defer c.Close()

q := client.NewQuery("CREATE DATABASE telegraf", "", "")
if response, err := c.Query(q); err == nil && response.Error() == nil {
	fmt.Println(response.Results)
}
Output:

Example (Query)

Make a Query

// Make client
c, err := client.NewHTTPClient(client.HTTPConfig{
	Addr: "http://localhost:8086",
})
if err != nil {
	fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
defer c.Close()

q := client.NewQuery("SELECT count(value) FROM shapes", "square_holes", "ns")
if response, err := c.Query(q); err == nil && response.Error() == nil {
	fmt.Println(response.Results)
}
Output:

Example (QueryWithParams)
// Make client
c, err := client.NewHTTPClient(client.HTTPConfig{
	Addr: "http://localhost:8086",
})
if err != nil {
	fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
defer c.Close()

q := client.NewQueryWithParameters("SELECT $fn($value) FROM $m", "square_holes", "ns", client.Params{
	"fn":    client.Identifier("count"),
	"value": client.Identifier("value"),
	"m":     client.Identifier("shapes"),
})
if response, err := c.Query(q); err == nil && response.Error() == nil {
	fmt.Println(response.Results)
}
Output:

Example (UDP)

Write a point using the UDP client

// Make client
config := client.UDPConfig{Addr: "localhost:8089"}
c, err := client.NewUDPClient(config)
if err != nil {
	fmt.Println("Error: ", err.Error())
}
defer c.Close()

// Create a new point batch
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
	Precision: "s",
})

// Create a point and add to batch
tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
	"idle":   10.1,
	"system": 53.3,
	"user":   46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
if err != nil {
	fmt.Println("Error: ", err.Error())
}
bp.AddPoint(pt)

// Write the batch
c.Write(bp)
Output:

Example (Write)

Write a point using the HTTP client

// Make client
c, err := client.NewHTTPClient(client.HTTPConfig{
	Addr: "http://localhost:8086",
})
if err != nil {
	fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
defer c.Close()

// Create a new point batch
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
	Database:  "BumbleBeeTuna",
	Precision: "s",
})

// Create a point and add to batch
tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
	"idle":   10.1,
	"system": 53.3,
	"user":   46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
if err != nil {
	fmt.Println("Error: ", err.Error())
}
bp.AddPoint(pt)

// Write the batch
c.Write(bp)
Output:

Example (Write1000)

Write 1000 points

sampleSize := 1000

// Make client
c, err := client.NewHTTPClient(client.HTTPConfig{
	Addr: "http://localhost:8086",
})
if err != nil {
	fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
defer c.Close()

rand.Seed(42)

bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
	Database:  "systemstats",
	Precision: "us",
})

for i := 0; i < sampleSize; i++ {
	regions := []string{"us-west1", "us-west2", "us-west3", "us-east1"}
	tags := map[string]string{
		"cpu":    "cpu-total",
		"host":   fmt.Sprintf("host%d", rand.Intn(1000)),
		"region": regions[rand.Intn(len(regions))],
	}

	idle := rand.Float64() * 100.0
	fields := map[string]interface{}{
		"idle": idle,
		"busy": 100.0 - idle,
	}

	pt, err := client.NewPoint(
		"cpu_usage",
		tags,
		fields,
		time.Now(),
	)
	if err != nil {
		println("Error:", err.Error())
		continue
	}
	bp.AddPoint(pt)
}

err = c.Write(bp)
if err != nil {
	fmt.Println("Error: ", err.Error())
}
Output:

func NewHTTPClient

func NewHTTPClient(conf HTTPConfig) (Client, error)

NewHTTPClient returns a new Client from the provided config. Client is safe for concurrent use by multiple goroutines.

func NewUDPClient

func NewUDPClient(conf UDPConfig) (Client, error)

NewUDPClient returns a client interface for writing to an InfluxDB UDP service from the given config.

type ContentEncoding

type ContentEncoding string
const (
	DefaultEncoding ContentEncoding = ""
	GzipEncoding    ContentEncoding = "gzip"
)

type DurationValue

type DurationValue time.Duration

DurationValue is a duration literal.

func (DurationValue) MarshalJSON

func (v DurationValue) MarshalJSON() ([]byte, error)

type HTTPConfig

type HTTPConfig struct {
	// Addr should be of the form "http://host:port"
	// or "http://[ipv6-host%zone]:port".
	Addr string

	// Username is the influxdb username, optional.
	Username string

	// Password is the influxdb password, optional.
	Password string

	// UserAgent is the http User Agent, defaults to "InfluxDBClient".
	UserAgent string

	// Timeout for influxdb writes, defaults to no timeout.
	Timeout time.Duration

	// InsecureSkipVerify gets passed to the http client, if true, it will
	// skip https certificate verification. Defaults to false.
	InsecureSkipVerify bool

	// TLSConfig allows the user to set their own TLS config for the HTTP
	// Client. If set, this option overrides InsecureSkipVerify.
	TLSConfig *tls.Config

	// Proxy configures the Proxy function on the HTTP client.
	Proxy func(req *http.Request) (*url.URL, error)

	// WriteEncoding specifies the encoding of write request
	WriteEncoding ContentEncoding
}

HTTPConfig is the config data needed to create an HTTP Client.

type Identifier

type Identifier string

Identifier is an identifier value.

func (Identifier) MarshalJSON

func (v Identifier) MarshalJSON() ([]byte, error)

type IntegerValue

type IntegerValue int64

IntegerValue is an integer literal.

func (IntegerValue) MarshalJSON

func (v IntegerValue) MarshalJSON() ([]byte, error)

type MeasurementTagMap

type MeasurementTagMap struct {
	Measurement map[string][]TagKeyMap
}

func GetTagKV

func GetTagKV(c Client, database string) MeasurementTagMap

GetTagKV 获取所有表的tag的key和value

type Message

type Message struct {
	Level string
	Text  string
}

Message represents a user message.

type NumberValue

type NumberValue float64

NumberValue is a number literal.

func (NumberValue) MarshalJSON

func (v NumberValue) MarshalJSON() ([]byte, error)

type Params

type Params map[string]interface{}

Params is a type alias to the query parameters.

type Point

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

Point represents a single data point.

Example

Create a new point with a timestamp

tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
	"idle":   10.1,
	"system": 53.3,
	"user":   46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
if err == nil {
	fmt.Println("We created a point: ", pt.String())
}
Output:

Example (WithoutTime)

Create a new point without a timestamp

tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
	"idle":   10.1,
	"system": 53.3,
	"user":   46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields)
if err == nil {
	fmt.Println("We created a point w/o time: ", pt.String())
}
Output:

func NewPoint

func NewPoint(
	name string,
	tags map[string]string,
	fields map[string]interface{},
	t ...time.Time,
) (*Point, error)

NewPoint returns a point with the given timestamp. If a timestamp is not given, then data is sent to the database without a timestamp, in which case the server will assign local time upon reception. NOTE: it is recommended to send data with a timestamp.

func NewPointFrom

func NewPointFrom(pt models.Point) *Point

NewPointFrom returns a point from the provided models.Point.

func (*Point) Fields

func (p *Point) Fields() (map[string]interface{}, error)

Fields returns the fields for the point.

func (*Point) Name

func (p *Point) Name() string

Name returns the measurement name of the point.

func (*Point) PrecisionString

func (p *Point) PrecisionString(precision string) string

PrecisionString returns a line-protocol string of the Point, with the timestamp formatted for the given precision.

func (*Point) String

func (p *Point) String() string

String returns a line-protocol string of the Point.

func (*Point) Tags

func (p *Point) Tags() map[string]string

Tags returns the tags associated with the point.

func (*Point) Time

func (p *Point) Time() time.Time

Time return the timestamp for the point.

func (*Point) UnixNano

func (p *Point) UnixNano() int64

UnixNano returns timestamp of the point in nanoseconds since Unix epoch.

type Query

type Query struct {
	Command         string
	Database        string
	RetentionPolicy string
	Precision       string
	Chunked         bool // chunked是数据存储和查询的方式,用于大量数据的读写操作,把数据划分成较小的块存储,而不是单条记录	,块内数据点数量固定
	ChunkSize       int
	Parameters      map[string]interface{}
}

Query defines a query to send to the server.

func NewQuery

func NewQuery(command, database, precision string) Query

NewQuery returns a query object. The database and precision arguments can be empty strings if they are not needed for the query.

func NewQueryWithParameters

func NewQueryWithParameters(command, database, precision string, parameters map[string]interface{}) Query

NewQueryWithParameters returns a query object. The database and precision arguments can be empty strings if they are not needed for the query. parameters is a map of the parameter names used in the command to their values.

func NewQueryWithRP

func NewQueryWithRP(command, database, retentionPolicy, precision string) Query

NewQueryWithRP returns a query object. The database, retention policy, and precision arguments can be empty strings if they are not needed for the query. Setting the retention policy only works on InfluxDB versions 1.6 or greater.

type RegexValue

type RegexValue string

RegexValue is a regexp literal.

func (RegexValue) MarshalJSON

func (v RegexValue) MarshalJSON() ([]byte, error)

type RespWithTimeRange

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

RespWithTimeRange 用于对结果排序的结构体

func SortResponseWithTimeRange

func SortResponseWithTimeRange(rwtr []RespWithTimeRange) []RespWithTimeRange

SortResponseWithTimeRange 用起止时间为一组查询结果排序 冒泡排序

type Response

type Response struct {
	Results []Result
	Err     string `json:"error,omitempty"`
}

Response represents a list of statement results.

func ByteArrayToResponse

func ByteArrayToResponse(byteArray []byte) *Response
todo	由字节数组转换成结果类型时,在查询语句的谓词中出现的tag不应该被添加到结果类型的 Tags 中,Tags中只有 GROUP BY tag:如何区分 谓词的tag 和 GROUP BY tag
* 在生成语义段的过程中,关于tag的谓词会被添加到SM中,而不是留在SP;(用作为全局变量的TagKV(当前数据库的所有tag及其值)判断谓词是否是tag)
* GROUP BY tag 会和 tag 谓词一起出现在SM中
* 如何区分两种tag:当前条件下没办法,但是可以通过调整查询语句避免这一问题:把出现在 WHRER 中的 tag 也写进 GROUP BY,让转换前后的结果中都存在多余的谓词 tag

字节数组转换成结果类型

func Merge

func Merge(precision string, resps ...*Response) []*Response

Merge Lists: todo 是否需要查询语句和结果的映射(?), 需要的话合并之后怎么映射(?) done 传入的表是乱序的,需要 排序 或 两次遍历,让表按升序正确合并 done 按照升序,合并碎片化的查询结果,如 [1,25] , [27,50] 合并, 设置一个合理的时间误差,在误差内的表可以合并 ( 1ms ? ) done 传入参数是查询结果的表 (?) ,数量任意(?)或者是表的数组; 返回值是表的数组(?); done 合并过程:需要比较每张表的起止时间,按照时间升序(越往下时间越大(越新)),如果两张表的起止时间在误差范围内,则合并;(不考虑时间范围重合的情况) done 按照 GROUP BY tag value 区分同一个查询的不同的表,合并时两个查询的表分别合并;多 tag 如何处理(?) done 表合并:能否直接从 Response 结构中合并(?) done 查询结果中的表按照tag值划分,不同表的起止时间可能不同(?) done 把两个查询结果的所有表合并,是否可以只比较第一张表的起止时间,如果这两张表可以合并,就认为两个查询的所有表都可以合并 (?)

func MergeResultTable

func MergeResultTable(resp1, resp2 *Response) *Response

MergeResultTable 2 合并到 1 后面,返回 1

func SortResponses

func SortResponses(resps []*Response) []*Response

SortResponses 传入一组查询结果,构造成用于排序的结构体,对不为空的结果按时间升序进行排序,返回结果数组

func TSCacheByteToValue

func TSCacheByteToValue(byteArray []byte) *Response
TSCache

把字节流转换成查询结果

func (*Response) Error

func (r *Response) Error() error

Error returns the first error from any statement. It returns nil if no errors occurred on any statements.

func (*Response) ToString

func (resp *Response) ToString() string

type Result

type Result struct {
	StatementId int `json:"statement_id"`
	Series      []models.Row
	Messages    []*Message
	Err         string `json:"error,omitempty"`
}

Result represents a resultset returned from a single statement.

type Series

type Series struct {
	Name    string            // measurement name
	Tags    map[string]string // GROUP BY tags
	Columns []string          // column name
	Values  [][]interface{}   // specific query results
	Partial bool              // useless (false)
}

Series 用于合并结果时暂时存储合并好的数据,合并完成后替换到结果中

func MergeSeries

func MergeSeries(resp1, resp2 *Response) []Series

MergeSeries 多表合并的关键部分,合并两个结果中的所有表的结构 有些表可能是某个结果独有的

type StringValue

type StringValue string

StringValue is a string literal.

func (StringValue) MarshalJSON

func (v StringValue) MarshalJSON() ([]byte, error)

type TagKeyMap

type TagKeyMap struct {
	Tag map[string]TagValues
}

type TagValues

type TagValues struct {
	Values []string
}

type TimeValue

type TimeValue time.Time

TimeValue is a time literal.

func (TimeValue) MarshalJSON

func (v TimeValue) MarshalJSON() ([]byte, error)

type UDPConfig

type UDPConfig struct {
	// Addr should be of the form "host:port"
	// or "[ipv6-host%zone]:port".
	Addr string

	// PayloadSize is the maximum size of a UDP client message, optional
	// Tune this based on your network. Defaults to UDPPayloadSize.
	PayloadSize int
}

UDPConfig is the config data needed to create a UDP Client.

Jump to

Keyboard shortcuts

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