Skip to content

Commit

Permalink
update pages
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelCurrin authored Aug 8, 2024
1 parent d25586d commit 4d0e8e2
Show file tree
Hide file tree
Showing 5 changed files with 110 additions and 13 deletions.
3 changes: 0 additions & 3 deletions cheatsheets/nosql/redis/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@ A in-memory data structure store, known for high performance as a database, cach
[Redis]: {% link cheatsheets/python/libraries/database/redis/index.md %}





## Keyspace notifications

Get notified when data enters or leaves Redis. Also timeout and time-based notifications.
Expand Down
43 changes: 39 additions & 4 deletions cheatsheets/nosql/redis/redis-cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ Start with:
$ redis-cli
```


## Overview of common commands


| Type | Get Commands | Create/Update Commands | Delete Commands |
|------|--------------|------------------------|-----------------|
| String | `GET`, `MGET` | `SET`, `INCR`, `DECR`, `INCRBY`, `DECRBY`, `APPEND` | - |
| List | `LRANGE`, `LINDEX` | `LPUSH`, `RPUSH`, `LREM` | `LPOP`, `RPOP` |
| Set | `SMEMBERS`, `SISMEMBER` | `SADD`, `SUNION`, `SINTER` | `SREM`, `SDIFF` |
| Sorted Set | `ZRANGE`, `ZREVRANGE`, `ZRANGEBYSCORE`, `ZCARD` | `ZADD` | `ZREM`, `ZREMRANGEBYSCORE` |
| Hash | `HGET`, `HMGET`, `HGETALL`, `HKEYS`, `HVALS` | `HSET`, `HINCRBY` | `HDEL` |
| Pub/Sub | `SUBSCRIBE`, `PSUBSCRIBE` | `PUBLISH` | `UNSUBSCRIBE`, `PUNSUBSCRIBE` |



## String operations

```console
Expand Down Expand Up @@ -241,18 +256,38 @@ Update a member by incrementing their value:

## Pub/sub feature

Follows the fire and forget principle. Data sent to the bus is sent to all consumers. If not consumed by workers, the data are lost.
The publish/subscribe feature.

Works for realtime data transport and is lightweight and easy to use. But data is not persisted. It follows the fire and forget principle. Data sent to the bus is sent to all consumers. If not consumed by workers, the data are lost.

Works for realtime data transport and is lightweight and easy to use. But data is not persisted.
### Publish

```console
> PUBLISH channel message
```
PUBLISH channel message

### Subscribe

```console
> SUBSCRIBE channel [channel ...]
```

Pattern subscribe:

```console
> PSUBSCRIBE pattern [pattern ...]
```
SUBSCRIBE channel [channel ...]

e.g. Here the client will subscribe to all channels that start with "news.". If another client publishes a message to the channel "news.politics" or "news.sports"

```console
> PSUBSCRIBE news.*
```

See also `UNSUBSCRIBE` and `PUNSUBSCRIBE`.



## Streams

An append-only data type (not a feature). They **persist** data unless you remove a record. Modelled after log files. You can add complex data as key-value pairs.
Expand Down
21 changes: 19 additions & 2 deletions cheatsheets/python/libraries/database/redis/data-types/hashes.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,28 @@ print(exists) # True
## Create/update

```python
# Set hash fields
r.hset('user:1000', mapping={'name': 'John Doe', 'email': 'john@example.com', 'age': '30'})
# Set a field.
r.hset('user:1000', 'visits', '10')

# Set a field only if it doesn't exist
r.hsetnx('user:1000', 'visits', '10')

# Set multiple fields as a dict.
mapping = {'name': 'John Doe', 'email': 'john@example.com', 'age': '30'}
r.hset('user:1000', mapping=mapping)

# Set multiple fields as list.
items = [
['name', 'John Doe'],
['email', 'john@example.com'],
['age', '30']
]
r.hset('user:1000', items=items)

# Mixed is also possible.
r.hset('user:1000', 'name', 'John Doe', mapping={'email': 'john@example.com', 'age': '30'})
r.hgetall('user:1000')
# => {b'name': b'John Doe', b'email': b'john@example.com', b'age': b'30'}
```

```python
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ print(length) # 4
```python
# Get range of items (0-based indexing)
items = r.lrange('fruits', 0, -1)
print(items) # [b'date', b'apple', b'banana', b'cherry']
# [b'date', b'apple', b'banana', b'cherry']
# OR
items = [item.decode() for item in items]
# ['apple', 'banana', 'cherry']
```

## Create/update
Expand Down
51 changes: 48 additions & 3 deletions cheatsheets/python/libraries/database/redis/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Using Redis through a Python application means seamless access to rich data stru
## Related

- [Redis][] cheatsheet in the NoSQL section, including installing and running Redis.
- [Python Redis](https://realpython.com/python-redis/) guide on the RealPython website.

[Redis]: {% link cheatsheets/nosql/redis/index.md %}

Expand All @@ -24,7 +25,7 @@ Using Redis through a Python application means seamless access to rich data stru
- Use Redis as a cache backend or session store in Django to streamline data access and improve app load times.
- For async web frameworks like FastAPI or Tornado, use Redis for tasks like backgorund job processing and message queing for responsive apps that can handle concurent requests gracefully.

## Install Python Redis Client
## Install the Python Redis client

```sh
$ pip install redis
Expand Down Expand Up @@ -55,7 +56,6 @@ r.set('mykey', 'Hello, Redis!')
```python
# Get a key.
value = r.get('mykey')
print(value)
# b'Hello, Redis!'
```

Expand All @@ -74,8 +74,53 @@ exists = r.exists('mykey')
r.setex('mykey', 10, 'This will expire in 10 seconds')
```

## Batching with the pipeline method

## Common use cases
How you can insert a list of 3 items (dictionaries) with random IDs into a Redis database using a batch request in Python. Using `r.pipeline()`, we can queue multiple commands and execute them as a batch, which is more efficient than executing them individually.

```python
with r.pipeline() as pipe:
pipe.set('key1', 'value1')
pipe.rpush('list1', 'item1', 'item2')
pipe.sadd('set1', 'member1', 'member2')

pipe.execute()
```

A more realistic example. When you run this code, it will insert the 3 items into Redis with random IDs and print the inserted items with their respective IDs.

```python
import redis
import uuid

r = redis.Redis(host='localhost', port=6379, db=0)

items = [
{'name': 'Item 1', 'price': 10.99, 'category': 'Electronics'},
{'name': 'Item 2', 'price': 5.75, 'category': 'Books'},
{'name': 'Item 3', 'price': 22.50, 'category': 'Clothing'}
]

# Use a pipeline to execute a batch of commands
pipe = r.pipeline()

# Insert each item with a random ID
for item in items:
item_id = str(uuid.uuid4())
pipe.hmset(f'item:{item_id}', item)

# Execute the batch of commands
pipe.execute()

# Print the inserted items
for item in items:
item_id = str(uuid.uuid4())
inserted_item = r.hgetall(f'item:{item_id}')
print(f'Item ID: {item_id}, Item: {inserted_item}')
```


## Code for common use cases

### Queue

Expand Down

0 comments on commit 4d0e8e2

Please sign in to comment.