Brainstorm's snippets (1/226)

  Using Redis as a Time Series Database

Code

#!/usr/bin/env python3
import time
import redis

redis_url = 'redis://localhost:6379/0'


#https://www.infoq.com/articles/redis-time-series
def record_event_with_pipeline(connection, id, event):
    event['id'] = id
    event_key = 'event:{id}'.format(id=id)
    pipe = connection.pipeline(True)
    pipe.hmset(event_key, event)
    pipe.zadd('events', **{id: event['timestamp']})
    pipe.execute()


def record_event(connection, id, event):
    """
    Example:
        "HMSET" "event:1" "timestamp" "1533445741.871906" "temperature" "100" "pressure" "200" "id" "1"
        "ZADD" "events" "1533446149.594696" "1"
    """
    event['id'] = id
    event_key = 'event:{id}'.format(id=id)
    connection.hmset(event_key, event)
    connection.zadd('events', **{id: event['timestamp']})


def main():
    redis_connection = redis.Redis.from_url(redis_url)

    for i in range(1, 11):
        id = 'n_{id}'.format(id=i)
        record_event_with_pipeline(redis_connection, id, {
            'timestamp': time.time(),
            'temperature': 100 + i,
            'pressure': 200 + i
        })

    #record_event_with_pipeline(redis_connection, 'n_1', {'timestamp': time.time(), 'temperature': 100, 'pressure': 200})

    # Now yout can do:
    #
    # > HGET event:n_1 timestamp
    # "1533445741.871906"
    # > HGET event:n_1 id
    # "n_1"
    # > HGET event:n_1 temperature
    # "100"
    # > HGET event:n_1 pressure
    # "200"
    #
    # > ZSCORE 'events' n_1
    # "1533446149.594696"
    # > ZRANGE events 0 -1
    #  1) "n_1"
    #  2) "n_2"
    #  3) "n_3"
    #  4) "n_4"
    #  5) "n_5"
    #  6) "n_6"
    #  7) "n_7"
    #  8) "n_8"
    #  9) "n_9"
    # 10) "n_10"

if __name__ == "__main__":
    main()