grafana+elasticsearch API 使用
grafana取Prometheus的数据的时候,使用接口 grafana接口 ,后面加上Prometheus的接口路径
/api/datasources/proxy/1/api/v1/query_range
1是DataSourceID,有可能不为1
Prometheus官网 API:https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries
def _query_range_data(expr, endsec, interval=3600, step=60): url = grafana_url + '/api/datasources/proxy/1/api/v1/query_range' try: params = { 'query': expr, 'start': endsec - interval, 'end': endsec, 'step': step } result = json.loads(requests.get(url, params=params).content.decode('utf8', 'ignore')) except Exception as e: result = {} return result
取elasticsearch的数据的时候,使用接口 grafana接口 ,后面加上elasticsearch的接口路径
/api/datasources/proxy/1/_msearch?max_concurrent_shard_requests=5
1是DataSourceID,有可能不为1
elasticsearch官网 API:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html
def _es_api(): '''IM单聊数据''' grafana_url = 'http://xxx.xxx.xxx.xxx:3000' #grafana 地址 search_params = {"search_type":"query_then_fetch","ignore_unavailable":True,"index":"sfim_stat*"} lte = int(round(time.time() * 1000)) gte = lte - 3600000 # 取一小时数据 schat_200 = 'sid:"7" && cid:"1" && retcode:"200"' schat_not_200 = 'sid:"7" && cid:"1" && -retcode:"200"' single_chat_200 = {"size":0,"query":{"bool":{"filter":[{"range":{"@timestamp":{"gte":gte,"lte":lte,"format":"epoch_millis"}}},{"query_string":{"analyze_wildcard":True,"query":schat_200}}]}},"aggs":{"2":{"date_histogram":{"interval":"1m","field":"@timestamp","min_doc_count":0,"extended_bounds":{"min":gte,"max":lte},"format":"epoch_millis"},"aggs":{}}}} single_chat_not_200 = {"size":0,"query":{"bool":{"filter":[{"range":{"@timestamp":{"gte":gte,"lte":lte,"format":"epoch_millis"}}},{"query_string":{"analyze_wildcard":True,"query":schat_not_200}}]}},"aggs":{"2":{"date_histogram":{"interval":"1m","field":"@timestamp","min_doc_count":0,"extended_bounds":{"min":gte,"max":lte},"format":"epoch_millis"},"aggs":{}}}} data = '\n'.join([json.dumps(search_params),json.dumps(single_chat_200),json.dumps(search_params),json.dumps(single_chat_not_200)]) data = data + '\n' url = grafana_url + '/api/datasources/proxy/1/_msearch?max_concurrent_shard_requests=5' headers = { 'Authorization' :'Bearer eyJrIjoiQzloeWloNDRma3VINUpiR3hEdUdWWTQ5d1VqVWtpejUiLCJuIjoiZmV0Y2hfbW9uaXRvcl9kYXRhIiwiaWQiOjF9', 'content-type':'application/json', } result = requests.post(url=url, data=data,headers=headers).content.decode('utf8', 'ignore') return result