Skip to content

Commit 8f56b52

Browse files
authored
Adding complex chaining example using pipelines with builder pattern (#3774)
1 parent b102c3b commit 8f56b52

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

docs/examples/pipeline_examples.ipynb

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,67 @@
156156
"pipe.set(\"a\", \"a value\").set(\"b\", \"b value\").get(\"a\").execute()"
157157
]
158158
},
159+
{
160+
"cell_type": "markdown",
161+
"metadata": {},
162+
"source": [
163+
"Here's a slightly more advanced example for chaining complex operations using the builder pattern."
164+
]
165+
},
166+
{
167+
"cell_type": "code",
168+
"execution_count": null,
169+
"metadata": {},
170+
"outputs": [],
171+
"source": [
172+
"from dataclasses import dataclass\n",
173+
"from typing import Optional\n",
174+
"\n",
175+
"@dataclass\n",
176+
"class User:\n",
177+
" email: str\n",
178+
" username: Optional[str] = None\n",
179+
"\n",
180+
"@dataclass\n",
181+
"class Post:\n",
182+
" title: str\n",
183+
" body: str\n",
184+
" author: Optional[str] = None\n",
185+
"\n",
186+
"class RedisRepository:\n",
187+
" def __init__(self):\n",
188+
" self.pipeline = r.pipeline()\n",
189+
"\n",
190+
" def add_user(self, user: User):\n",
191+
" if not user.username:\n",
192+
" user.username = user.email.split(\"@\")[0]\n",
193+
" self.pipeline.hset(f\"user:{user.username}\", mapping={\"username\": user.username, \"email\": user.email})\n",
194+
" return self\n",
195+
" \n",
196+
" def add_post(self, post: Post):\n",
197+
" self.pipeline.hset(f\"post:#{post.title}#\", mapping={\"title\": post.title, \"body\": post.body, \"author\": post.author})\n",
198+
" if post.author:\n",
199+
" self.pipeline.sadd(f\"user:{post.author}:posts\", f\"post:#{post.title}#\")\n",
200+
" return self\n",
201+
"\n",
202+
" def add_follow(self, follower: str, following: str):\n",
203+
" self.pipeline.sadd(f\"user:{follower}:following\", following)\n",
204+
" self.pipeline.sadd(f\"user:{following}:followers\", follower)\n",
205+
" return self\n",
206+
"\n",
207+
" def execute(self):\n",
208+
" return self.pipeline.execute()\n",
209+
"\n",
210+
"pipe = RedisRepository()\n",
211+
"results = (pipe\n",
212+
" .add_user(User(email=\"[email protected]\"))\n",
213+
" .add_user(User(email=\"[email protected]\"))\n",
214+
" .add_follow(\"alice\", \"bob\")\n",
215+
" .add_post(Post(title=\"Hello World\", body=\"I'm using Redis!\", author=\"alice\"))\n",
216+
" .execute()\n",
217+
")"
218+
]
219+
},
159220
{
160221
"cell_type": "markdown",
161222
"metadata": {},

0 commit comments

Comments
 (0)