2017-04-06 93 views
0

我在influx中存儲了一些數據,並且令人困惑的是涌入量比Mysql緩慢4-5倍。我嘗試通過在mysql中插入10000行然後在influxdb中進行測試。 和統計信息如下。爲什麼涌入性能很慢

Mysql 

real: 6m 39sec 
user: 2.956sec 
sys: 0.504sec 

Influxdb 

real: 6m 17.193sec 
user: 11.860sec 
sys: 0.328sec 

我的influx代碼如下,我用相同的模式存儲在mysql中。

#!/usr/bin/env python 
# coding: utf-8 
import time 
import csv 
import sys 
import datetime 
import calendar 
import pytz 
from influxdb import client as influxdb 
from datetime import datetime 

host = 'localhost' 
port = 8086 
user = "admin" 
password = "admin" 
db_name = "testdatabase" 
db = influxdb.InfluxDBClient(database=db_name) 


def read_data(): 
    with open(file) as f: 
     reader = f.readlines()[4:] 
     for line in reader: 
      yield (line.strip().split(',')) 


fmt = '%Y-%m-%d %H:%M:%S' 
file = '/home/rob/mycsvfile.csv' 

csvToInflux = read_data() 
body = [] 
for metric in csvToInflux: 
    timestamp = datetime.strptime(metric[0][1: len(metric[0]) - 1], fmt) 

    new_value = float(metric[1]) 
    body.append({ 
     'measurement': 'mytable1', 
     'time': timestamp, 
     'fields': { 
      'col1': metric[1], 
      'col2': metric[2], 
      'col3': metric[3], 
      'col4': metric[4], 
      'col5': metric[5], 
      'col6': metric[6], 
      'col7': metric[7], 
      'col8': metric[8], 
      'col9': metric[9] 
     } 
     }) 
    db.write_points(body) 

有人可以給我一個想法,我該如何改進它。我認爲這可能是由於緩存。緩存選項在Influx db中默認是關閉的?有人可以指導我進行批量處理。我試圖查看過去和谷歌,但無法解決我的問題。我是新手涌入db。我試圖讓它更快。 感謝您的任何幫助或提示。

回答

1

一個一個地插入influxdb是慢的,你應該分批做。例如,10000線(一一)一個CSV嘗試:

with open('/tmp/blah.csv') as f: 
    lines = f.readlines() 

import influxdb 

inf = influxdb.InfluxDBClient('localhost', 8086, 'root', 'root', 'example1') 

for line in lines: 
    parts = line.split(',') 
    json_body = [{ 
     'measurement': 'one_by_one', 
     'time': parts[0], 
     'fields':{ 
      'my_value': int(parts[1].strip()) 
     } 
    }] 
    inf.write_points(json_body) 

這給我的

└─ $ ▶ time python influx_one.py 

real 1m43.655s 
user 0m19.547s 
sys  0m3.266s 

結果並做了小改動,插入CSV的所有行一氣呵成:

json_body = [] 
for line in lines: 
    parts = line.split(',') 
    json_body.append({ 
     'measurement': 'one_batch', 
     'time': parts[0], 
     'fields':{ 
      'my_value': int(parts[1].strip()) 
     } 
    }) 

inf.write_points(json_body) 

結果是非常非常好:

└─ $ ▶ time python influx_good.py 

real 0m2.693s 
user 0m1.797s 
sys  0m0.734s 
+0

非常感謝您的幫助。我會嘗試它,並會回來更新。 – rob

+0

你可以相應地編輯我的代碼嗎?因爲我試圖通過使用json_body和append來使用你的最後一個例子中的批處理想法,但它不適用於我。非常感謝 – rob

+0

我現在無法編輯它(我用手機),但爲什麼它不適合你?你有錯誤還是仍然很慢? @rob – Pigueiras