Debian Codegraph @

influxdb/_dataframe_client.py

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