본문 바로가기
Tech Stack/Database ( TSDB, NOSQL, SQL )

InfluxDB nodeJS 라이브러리

by jaeaemin 2022. 11. 15.

 

현재 모니터링 시스템을 구축하기 위해서 사용하는 라이브러리는 아래와 같다.

 

https://github.com/node-influx/node-influx

 

GitHub - node-influx/node-influx: 📈 The InfluxDB Client for Node.js and Browsers

📈 The InfluxDB Client for Node.js and Browsers. Contribute to node-influx/node-influx development by creating an account on GitHub.

github.com

 

 

 

 

간단한 사용 방법을 포스팅한다 ! 

 

 

[1] Influx 연결 

   
   InfluxService.client = new Influx.InfluxDB({
      database: database,
      host: process.env.HOST,
      port: port,
      protocol: 'https'
      schema: [{
        measurement: 'response_times',
     	fields: {
           path: Influx.FieldType.STRING,
           duration: Influx.FieldType.INTEGER
     	},
     	tags: [ 'host' ]
      }]
});
    
const client = InfluxService.client;

 

InfluxDB는 데이터베이스의 쿼리를 실행가능하도록 하는 공용 인터페이스로, ORM의 레벨 하위의 드라이버 수준의 모듈로, 이 클래스에서 메서드를 호출해서 직접 쿼리하는 것이 가능하다. 

 

인터페이스를 통해 호출  가능한 메서드들은 아래와 같다. 주로 CQ, RP, Series, Shard 등에 접근하여 작업이 가능하다.

Public Methods
public
addSchema(schema: ISchemaOptions)
Adds specified schema for better fields coercing.
public
alterRetentionPolicy(name: *, options: *): *
Alters an existing retention policy on a database.
public
createContinuousQuery(name: *, query: *, database: *, resample: *): *
Creates a continuous query in a database
public
createDatabase(databaseName: *): *
Creates a new database with the provided name.
public
createRetentionPolicy(name: *, options: *): *
Creates a new retention policy on a database.
public
createUser(username: *, password: *, admin: *): *
Creates a new InfluxDB user.
public
dropContinuousQuery(name: *, database: *): *
Creates a continuous query in a database
public
dropDatabase(databaseName: *): *
Deletes a database with the provided name.
public
dropMeasurement(measurement: *, database: *): *
Removes a measurement from the database.
public
dropRetentionPolicy(name: *, database: *): *
Deletes a retention policy and associated data.
public
dropSeries(options: *): *
Removes a one or more series from InfluxDB.
public
dropShard(shard_id: *): *
Drops a shard with the provided number.
public
dropUser(username: *): *
Removes a user from the database.
public
Returns array of database names.
public
getMeasurements(database: *): *
Returns array of measurements.
public
getSeries(options: *): *
Returns a list of all series within the target measurement, or from the entire database if a measurement isn't provided.
public
getUsers(): *
Returns a list of users on the Influx database.
public
grantAdminPrivilege(username: *): *
Grants admin privileges to a specified user.
public
grantPrivilege(username: *, privilege: *, database: *): *
Grants a privilege to a specified user.
public
parsePoint(point: *, options: *): {"fields": *, "tags": *, "measurement": *, "timestamp": *, "fieldsPairs": *, "tagsNames": *, "castedTimestamp": *}
ParsePoint will perform the coercions/schema checks and return the data required for writing a point.
public
ping(timeout: *): *
Pings all available hosts, collecting online status and version info.
public
query(query: *, options: *): *
.query() runs a query (or list of queries), and returns the results in a friendly format, IResults.
public
queryRaw(query: *, options: *): *
QueryRaw functions similarly to .query() but it does no fancy transformations on the returned data; it calls JSON.parse and returns those results verbatim.
public
revokeAdminPrivilege(username: *): *
Removes a admin privilege from a specified user.
public
revokePrivilege(username: *, privilege: *, database: *): *
Removes a privilege from a specified user.
public
setPassword(username: *, password: *): *
Sets a password for an Influx user.
public
showContinousQueries(database: *): *
Returns a list of continous queries in the database.
public
showRetentionPolicies(database: *): *
Shows retention policies on the database
public
showShards(database: *): *
Shows shards on the database
public
writeMeasurement(measurement: *, points: *, options: *): *
WriteMeasurement functions similarly to InfluxDB#writePoints, but it automatically fills in the measurement value for all points for you.
public
writePoints(points: *, options: *): *
WritePoints sends a list of points together in a batch to InfluxDB.
Private Methods
private
_createSchema(schema: ISchemaOptions)
Creates specified measurement schema
 
private
Returns the default database that queries operates on.
 
private
_getQueryOpts(params: *, method: string): {"method": *, "path": string, "query": *}
Creates options to be passed into the pool to query databases.

 

 

 

[2] Influx - 라이브러리를 통한 데이터 post 예시 

  async writeUtilityHit(features): Promise<any> {
    const client = InfluxService.client;
    const data = [];
    features.forEach(function (features) {
      var utc_time = new Date(features.acquiredAt)
      var microSecond: string = features.acquiredAt.slice(20)
      console.log(features.acquiredAt)
      console.log(Influx.toNanoDate(Math.floor(utc_time.getTime() / 1000) + microSecond + '000'))
      data.push({
        measurement: 'utility_hit2', //app 변수로 변경 가능
        tags: {
          point_id: features.pointId,
          feature_type_id: features.featureTypeId,
        },
        timestamp: Influx.toNanoDate(Math.floor(utc_time.getTime() / 1000) + microSecond + '000'),
        fields: {
          value: features.value,
          real_time: features.acquiredAt,
        },
      });
    });
    client.writePoints(data).then();
  }
 
반응형

'Tech Stack > Database ( TSDB, NOSQL, SQL )' 카테고리의 다른 글

Kapacitor  (0) 2022.08.25
InfluxDB CQ ( continuous query )  (0) 2022.08.12
Telegraf  (0) 2022.07.15
InfluxDB  (1) 2022.06.27
Redis Command  (0) 2022.04.04