_dataframe_client.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. # -*- coding: utf-8 -*-
  2. """DataFrame client for InfluxDB."""
  3. from __future__ import absolute_import
  4. from __future__ import division
  5. from __future__ import print_function
  6. from __future__ import unicode_literals
  7. import math
  8. from collections import defaultdict
  9. import pandas as pd
  10. import numpy as np
  11. from .client import InfluxDBClient
  12. from .line_protocol import _escape_tag
  13. def _pandas_time_unit(time_precision):
  14. unit = time_precision
  15. if time_precision == 'm':
  16. unit = 'ms'
  17. elif time_precision == 'u':
  18. unit = 'us'
  19. elif time_precision == 'n':
  20. unit = 'ns'
  21. assert unit in ('s', 'ms', 'us', 'ns')
  22. return unit
  23. def _escape_pandas_series(s):
  24. return s.apply(lambda v: _escape_tag(v))
  25. class DataFrameClient(InfluxDBClient):
  26. """DataFrameClient instantiates InfluxDBClient to connect to the backend.
  27. The ``DataFrameClient`` object holds information necessary to connect
  28. to InfluxDB. Requests can be made to InfluxDB directly through the client.
  29. The client reads and writes from pandas DataFrames.
  30. """
  31. EPOCH = pd.Timestamp('1970-01-01 00:00:00.000+00:00')
  32. def write_points(self,
  33. dataframe,
  34. measurement,
  35. tags=None,
  36. tag_columns=None,
  37. field_columns=None,
  38. time_precision=None,
  39. database=None,
  40. retention_policy=None,
  41. batch_size=None,
  42. protocol='line',
  43. numeric_precision=None):
  44. """Write to multiple time series names.
  45. :param dataframe: data points in a DataFrame
  46. :param measurement: name of measurement
  47. :param tags: dictionary of tags, with string key-values
  48. :param time_precision: [Optional, default None] Either 's', 'ms', 'u'
  49. or 'n'.
  50. :param batch_size: [Optional] Value to write the points in batches
  51. instead of all at one time. Useful for when doing data dumps from
  52. one database to another or when doing a massive write operation
  53. :type batch_size: int
  54. :param protocol: Protocol for writing data. Either 'line' or 'json'.
  55. :param numeric_precision: Precision for floating point values.
  56. Either None, 'full' or some int, where int is the desired decimal
  57. precision. 'full' preserves full precision for int and float
  58. datatypes. Defaults to None, which preserves 14-15 significant
  59. figures for float and all significant figures for int datatypes.
  60. """
  61. if tag_columns is None:
  62. tag_columns = []
  63. if field_columns is None:
  64. field_columns = []
  65. if batch_size:
  66. number_batches = int(math.ceil(len(dataframe) / float(batch_size)))
  67. for batch in range(number_batches):
  68. start_index = batch * batch_size
  69. end_index = (batch + 1) * batch_size
  70. if protocol == 'line':
  71. points = self._convert_dataframe_to_lines(
  72. dataframe.iloc[start_index:end_index].copy(),
  73. measurement=measurement,
  74. global_tags=tags,
  75. time_precision=time_precision,
  76. tag_columns=tag_columns,
  77. field_columns=field_columns,
  78. numeric_precision=numeric_precision)
  79. else:
  80. points = self._convert_dataframe_to_json(
  81. dataframe.iloc[start_index:end_index].copy(),
  82. measurement=measurement,
  83. tags=tags,
  84. time_precision=time_precision,
  85. tag_columns=tag_columns,
  86. field_columns=field_columns)
  87. super(DataFrameClient, self).write_points(
  88. points,
  89. time_precision,
  90. database,
  91. retention_policy,
  92. protocol=protocol)
  93. return True
  94. if protocol == 'line':
  95. points = self._convert_dataframe_to_lines(
  96. dataframe,
  97. measurement=measurement,
  98. global_tags=tags,
  99. tag_columns=tag_columns,
  100. field_columns=field_columns,
  101. time_precision=time_precision,
  102. numeric_precision=numeric_precision)
  103. else:
  104. points = self._convert_dataframe_to_json(
  105. dataframe,
  106. measurement=measurement,
  107. tags=tags,
  108. time_precision=time_precision,
  109. tag_columns=tag_columns,
  110. field_columns=field_columns)
  111. super(DataFrameClient, self).write_points(
  112. points,
  113. time_precision,
  114. database,
  115. retention_policy,
  116. protocol=protocol)
  117. return True
  118. def query(self,
  119. query,
  120. params=None,
  121. bind_params=None,
  122. epoch=None,
  123. expected_response_code=200,
  124. database=None,
  125. raise_errors=True,
  126. chunked=False,
  127. chunk_size=0,
  128. method="GET",
  129. dropna=True):
  130. """
  131. Query data into a DataFrame.
  132. .. danger::
  133. In order to avoid injection vulnerabilities (similar to `SQL
  134. injection <https://www.owasp.org/index.php/SQL_Injection>`_
  135. vulnerabilities), do not directly include untrusted data into the
  136. ``query`` parameter, use ``bind_params`` instead.
  137. :param query: the actual query string
  138. :param params: additional parameters for the request, defaults to {}
  139. :param bind_params: bind parameters for the query:
  140. any variable in the query written as ``'$var_name'`` will be
  141. replaced with ``bind_params['var_name']``. Only works in the
  142. ``WHERE`` clause and takes precedence over ``params['params']``
  143. :param epoch: response timestamps to be in epoch format either 'h',
  144. 'm', 's', 'ms', 'u', or 'ns',defaults to `None` which is
  145. RFC3339 UTC format with nanosecond precision
  146. :param expected_response_code: the expected status code of response,
  147. defaults to 200
  148. :param database: database to query, defaults to None
  149. :param raise_errors: Whether or not to raise exceptions when InfluxDB
  150. returns errors, defaults to True
  151. :param chunked: Enable to use chunked responses from InfluxDB.
  152. With ``chunked`` enabled, one ResultSet is returned per chunk
  153. containing all results within that chunk
  154. :param chunk_size: Size of each chunk to tell InfluxDB to use.
  155. :param dropna: drop columns where all values are missing
  156. :returns: the queried data
  157. :rtype: :class:`~.ResultSet`
  158. """
  159. query_args = dict(params=params,
  160. bind_params=bind_params,
  161. epoch=epoch,
  162. expected_response_code=expected_response_code,
  163. raise_errors=raise_errors,
  164. chunked=chunked,
  165. database=database,
  166. method=method,
  167. chunk_size=chunk_size)
  168. results = super(DataFrameClient, self).query(query, **query_args)
  169. if query.strip().upper().startswith("SELECT"):
  170. if len(results) > 0:
  171. return self._to_dataframe(results, dropna)
  172. else:
  173. return {}
  174. else:
  175. return results
  176. def _to_dataframe(self, rs, dropna=True):
  177. result = defaultdict(list)
  178. if isinstance(rs, list):
  179. return map(self._to_dataframe, rs,
  180. [dropna for _ in range(len(rs))])
  181. for key, data in rs.items():
  182. name, tags = key
  183. if tags is None:
  184. key = name
  185. else:
  186. key = (name, tuple(sorted(tags.items())))
  187. df = pd.DataFrame(data)
  188. df.time = pd.to_datetime(df.time)
  189. df.set_index('time', inplace=True)
  190. if df.index.tzinfo is None:
  191. df.index = df.index.tz_localize('UTC')
  192. df.index.name = None
  193. result[key].append(df)
  194. for key, data in result.items():
  195. df = pd.concat(data).sort_index()
  196. if dropna:
  197. df.dropna(how='all', axis=1, inplace=True)
  198. result[key] = df
  199. return result
  200. @staticmethod
  201. def _convert_dataframe_to_json(dataframe,
  202. measurement,
  203. tags=None,
  204. tag_columns=None,
  205. field_columns=None,
  206. time_precision=None):
  207. if not isinstance(dataframe, pd.DataFrame):
  208. raise TypeError('Must be DataFrame, but type was: {0}.'
  209. .format(type(dataframe)))
  210. if not (isinstance(dataframe.index, pd.PeriodIndex) or
  211. isinstance(dataframe.index, pd.DatetimeIndex)):
  212. raise TypeError('Must be DataFrame with DatetimeIndex or '
  213. 'PeriodIndex.')
  214. # Make sure tags and tag columns are correctly typed
  215. tag_columns = tag_columns if tag_columns is not None else []
  216. field_columns = field_columns if field_columns is not None else []
  217. tags = tags if tags is not None else {}
  218. # Assume field columns are all columns not included in tag columns
  219. if not field_columns:
  220. field_columns = list(
  221. set(dataframe.columns).difference(set(tag_columns)))
  222. if not isinstance(dataframe.index, pd.DatetimeIndex):
  223. dataframe.index = pd.to_datetime(dataframe.index)
  224. if dataframe.index.tzinfo is None:
  225. dataframe.index = dataframe.index.tz_localize('UTC')
  226. # Convert column to strings
  227. dataframe.columns = dataframe.columns.astype('str')
  228. # Convert dtype for json serialization
  229. dataframe = dataframe.astype('object')
  230. precision_factor = {
  231. "n": 1,
  232. "u": 1e3,
  233. "ms": 1e6,
  234. "s": 1e9,
  235. "m": 1e9 * 60,
  236. "h": 1e9 * 3600,
  237. }.get(time_precision, 1)
  238. if not tag_columns:
  239. points = [
  240. {'measurement': measurement,
  241. 'fields':
  242. rec.replace([np.inf, -np.inf], np.nan).dropna().to_dict(),
  243. 'time': np.int64(ts.value / precision_factor)}
  244. for ts, (_, rec) in zip(
  245. dataframe.index,
  246. dataframe[field_columns].iterrows()
  247. )
  248. ]
  249. return points
  250. points = [
  251. {'measurement': measurement,
  252. 'tags': dict(list(tag.items()) + list(tags.items())),
  253. 'fields':
  254. rec.replace([np.inf, -np.inf], np.nan).dropna().to_dict(),
  255. 'time': np.int64(ts.value / precision_factor)}
  256. for ts, tag, (_, rec) in zip(
  257. dataframe.index,
  258. dataframe[tag_columns].to_dict('record'),
  259. dataframe[field_columns].iterrows()
  260. )
  261. ]
  262. return points
  263. def _convert_dataframe_to_lines(self,
  264. dataframe,
  265. measurement,
  266. field_columns=None,
  267. tag_columns=None,
  268. global_tags=None,
  269. time_precision=None,
  270. numeric_precision=None):
  271. dataframe = dataframe.dropna(how='all').copy()
  272. if len(dataframe) == 0:
  273. return []
  274. if not isinstance(dataframe, pd.DataFrame):
  275. raise TypeError('Must be DataFrame, but type was: {0}.'
  276. .format(type(dataframe)))
  277. if not (isinstance(dataframe.index, pd.PeriodIndex) or
  278. isinstance(dataframe.index, pd.DatetimeIndex)):
  279. raise TypeError('Must be DataFrame with DatetimeIndex or '
  280. 'PeriodIndex.')
  281. dataframe = dataframe.rename(
  282. columns={item: _escape_tag(item) for item in dataframe.columns})
  283. # Create a Series of columns for easier indexing
  284. column_series = pd.Series(dataframe.columns)
  285. if field_columns is None:
  286. field_columns = []
  287. if tag_columns is None:
  288. tag_columns = []
  289. if global_tags is None:
  290. global_tags = {}
  291. # Make sure field_columns and tag_columns are lists
  292. field_columns = list(field_columns) if list(field_columns) else []
  293. tag_columns = list(tag_columns) if list(tag_columns) else []
  294. # If field columns but no tag columns, assume rest of columns are tags
  295. if field_columns and (not tag_columns):
  296. tag_columns = list(column_series[~column_series.isin(
  297. field_columns)])
  298. # If no field columns, assume non-tag columns are fields
  299. if not field_columns:
  300. field_columns = list(column_series[~column_series.isin(
  301. tag_columns)])
  302. precision_factor = {
  303. "n": 1,
  304. "u": 1e3,
  305. "ms": 1e6,
  306. "s": 1e9,
  307. "m": 1e9 * 60,
  308. "h": 1e9 * 3600,
  309. }.get(time_precision, 1)
  310. # Make array of timestamp ints
  311. if isinstance(dataframe.index, pd.PeriodIndex):
  312. time = ((dataframe.index.to_timestamp().values.astype(np.int64) /
  313. precision_factor).astype(np.int64).astype(str))
  314. else:
  315. time = ((pd.to_datetime(dataframe.index).values.astype(np.int64) /
  316. precision_factor).astype(np.int64).astype(str))
  317. # If tag columns exist, make an array of formatted tag keys and values
  318. if tag_columns:
  319. # Make global_tags as tag_columns
  320. if global_tags:
  321. for tag in global_tags:
  322. dataframe[tag] = global_tags[tag]
  323. tag_columns.append(tag)
  324. tag_df = dataframe[tag_columns]
  325. tag_df = tag_df.fillna('') # replace NA with empty string
  326. tag_df = tag_df.sort_index(axis=1)
  327. tag_df = self._stringify_dataframe(
  328. tag_df, numeric_precision, datatype='tag')
  329. # join prepended tags, leaving None values out
  330. tags = tag_df.apply(
  331. lambda s: [',' + s.name + '=' + v if v else '' for v in s])
  332. tags = tags.sum(axis=1)
  333. del tag_df
  334. elif global_tags:
  335. tag_string = ''.join(
  336. [",{}={}".format(k, _escape_tag(v))
  337. if v not in [None, ''] else ""
  338. for k, v in sorted(global_tags.items())]
  339. )
  340. tags = pd.Series(tag_string, index=dataframe.index)
  341. else:
  342. tags = ''
  343. # Make an array of formatted field keys and values
  344. field_df = dataframe[field_columns].replace([np.inf, -np.inf], np.nan)
  345. nans = pd.isnull(field_df)
  346. field_df = self._stringify_dataframe(field_df,
  347. numeric_precision,
  348. datatype='field')
  349. field_df = (field_df.columns.values + '=').tolist() + field_df
  350. field_df[field_df.columns[1:]] = ',' + field_df[field_df.columns[1:]]
  351. field_df[nans] = ''
  352. fields = field_df.sum(axis=1).map(lambda x: x.lstrip(','))
  353. del field_df
  354. # Generate line protocol string
  355. measurement = _escape_tag(measurement)
  356. points = (measurement + tags + ' ' + fields + ' ' + time).tolist()
  357. return points
  358. @staticmethod
  359. def _stringify_dataframe(dframe, numeric_precision, datatype='field'):
  360. # Prevent modification of input dataframe
  361. dframe = dframe.copy()
  362. # Find int and string columns for field-type data
  363. int_columns = dframe.select_dtypes(include=['integer']).columns
  364. string_columns = dframe.select_dtypes(include=['object']).columns
  365. # Convert dframe to string
  366. if numeric_precision is None:
  367. # If no precision specified, convert directly to string (fast)
  368. dframe = dframe.astype(str)
  369. elif numeric_precision == 'full':
  370. # If full precision, use repr to get full float precision
  371. float_columns = (dframe.select_dtypes(
  372. include=['floating']).columns)
  373. nonfloat_columns = dframe.columns[~dframe.columns.isin(
  374. float_columns)]
  375. dframe[float_columns] = dframe[float_columns].applymap(repr)
  376. dframe[nonfloat_columns] = (dframe[nonfloat_columns].astype(str))
  377. elif isinstance(numeric_precision, int):
  378. # If precision is specified, round to appropriate precision
  379. float_columns = (dframe.select_dtypes(
  380. include=['floating']).columns)
  381. nonfloat_columns = dframe.columns[~dframe.columns.isin(
  382. float_columns)]
  383. dframe[float_columns] = (dframe[float_columns].round(
  384. numeric_precision))
  385. # If desired precision is > 10 decimal places, need to use repr
  386. if numeric_precision > 10:
  387. dframe[float_columns] = (dframe[float_columns].applymap(repr))
  388. dframe[nonfloat_columns] = (dframe[nonfloat_columns]
  389. .astype(str))
  390. else:
  391. dframe = dframe.astype(str)
  392. else:
  393. raise ValueError('Invalid numeric precision.')
  394. if datatype == 'field':
  395. # If dealing with fields, format ints and strings correctly
  396. dframe[int_columns] += 'i'
  397. dframe[string_columns] = '"' + dframe[string_columns] + '"'
  398. elif datatype == 'tag':
  399. dframe = dframe.apply(_escape_pandas_series)
  400. dframe.columns = dframe.columns.astype(str)
  401. return dframe
  402. def _datetime_to_epoch(self, datetime, time_precision='s'):
  403. seconds = (datetime - self.EPOCH).total_seconds()
  404. if time_precision == 'h':
  405. return seconds / 3600
  406. elif time_precision == 'm':
  407. return seconds / 60
  408. elif time_precision == 's':
  409. return seconds
  410. elif time_precision == 'ms':
  411. return seconds * 1e3
  412. elif time_precision == 'u':
  413. return seconds * 1e6
  414. elif time_precision == 'n':
  415. return seconds * 1e9