直入主题。
opentsdb可以直接用get方式插入和查询
用python去实现opentsdb的数据插入和查询也是通过request的get方法来实现的。
插入单条数据:
curl -i -X POST -d '{"metric":"sig", "timestamp":1573216835, "value":18, "tags": {"host":"web01"}}' http://localhost:4242/api/put?details
插入多行数据,来自网络上的代码:
import requests
data1 = {
"metric": "sig",
"timestamp": '1573216837',
"value": '21',
"tags": {
"host": "web01",
"dc": "lga"
}
}
data2 = {
"metric": "sig",
"timestamp": '1573216838',
"value": '22',
"tags": {
"host": "web01",
"dc": "lga"
}
}
data3 = {
"metric": "sig",
"timestamp": '1573216839',
"value": '23',
"tags": {
"host": "web01",
"dc": "lga"
}
}
data3 = {
"metric": "sys.nice",
"timestamp": '1573216840',
"value": '24',
"tags": {
"host": "web01",
"dc": "lga"
}
}
list1 = [data1, data2, data3, data4]
def send_json(json):
result = requests.post("http://localhost:4242/api/put?details", json=json)
return result.text
def main():
print send_json(list1)
if __name__ == "__main__":
main()
循环插入数据:
import time
import math
import requests
def get_value(num):
return math.sin(num)+1
def send_json(json, s):
result = s.post("http://localhost:4242/api/put?details", json=json)
return result.text
def main():
s = requests.Session()
a = int(time.time()) - 100
ls = []
tsuids = 000001000002000001
for i in range(1, 100):
json = {
"metric": "sys.batch.sig",
"timestamp": a,
"tsuids": tsuids,
"value": get_value(i),
"tags": {
"host": "web01",
"dc": "lga"
}
}
i += 0.01
a += 1
tsuids += 1
ls.append(json)
if len(ls) == 50:
send_json(ls, s)
ls = []
send_json(ls, s)
ls = []
if __name__ == "__main__":
start = time.time()
main()
print time.time()-start
查询数据:
# -*- coding: utf-8 -*-
import requests
def data_get(query):
result = requests.get("http://localhost:4242/api/query?" + query)
jsonresponse = result.json()[0]['dps']
return jsonresponse
if __name__ == "__main__":
print data_get('start=1573216835&m=sum:sig')
curl命令通过/api/query/last接口查询
curl http://localhost:4242/api/query/last?tsuids=000001000002000001&backScan=24&resolve=true