Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis - Python example of xadd and xread

Could you give a very simple example of using Redis' xread and xadd in Python ( that displays the type and format of return values form xread and input of xadd)? I've already read many documentation but none of them are in Python.

The Redis doc gives an example:

> XADD mystream * sensor-id 1234 temperature 19.8
1518951480106-0

but If I try in python:

sample = {b"hello":b"12"}
id = r.xadd("mystream", sample)

I get this error:

redis.exceptions.ResponseError: WRONGTYPE Operation against a key holding the wrong kind of value
like image 977
AgnosticCucumber Avatar asked Mar 06 '19 09:03

AgnosticCucumber


People also ask

Which command do you use to add a value to Redis stream named Mystream?

XADD is the only Redis command that can add data to a stream, but there are other commands, such as XDEL and XTRIM , that are able to remove data from a stream.

Which of these Redis data structures can be used to create consumer groups?

XGROUP is used in order to create, destroy and manage consumer groups. XREADGROUP is used to read from a stream via a consumer group. XACK is the command that allows a consumer to mark a pending message as correctly processed.

What is stream in Redis?

Conceptually, a Stream in Redis is a list where you can append entries. Each entry has a unique ID and a value. The ID is auto-generated by default, and it includes a timestamp. The value is a hash. You can query ranges or use blocking commands to read entries as they come.


1 Answers

make sure to flush before running just to make sure that there doesn't exist a list / stream with the same name. :

redis-cli flushall
if __name__ == '__main__':
    r = redis.Redis(host='localhost', port=6379, db=0)
    encoder = JSONEncoder()
    sample = {"hello": encoder.encode([1234,125, 1235, 1235])} # converts list to string
    stream_name = 'mystream'

    for i in range(10):
        r.xadd(stream_name, sample)

    # "$" doesn't seem to work in python
    read_samples = r.xread({stream_name:b"0-0"})

like image 154
AgnosticCucumber Avatar answered Sep 20 '22 22:09

AgnosticCucumber