I'm using Redis OM for Python and my models look like below:
from typing import List
from pydantic import BaseModel
from redis_om import EmbeddedJsonModel, Field, JsonModel, Migrator
class FeedItem(EmbeddedJsonModel):
id: str = Field(index=True)
s_score: str = Field()
i_score: str = Field()
factors: List[str]
class Feed(JsonModel):
user_id: str = Field(index=True, primary_key=True)
feed_items: List[FeedItem] = Field(default=[])
which will then result in a data structure like this:
{
"user_id": "john_001",
"feed_items": [
{
"pk": "01GS2N47G8WK2831GNHMGRVDJT",
"id": "63e8c53825e41aca93229eac",
"s_score": "0.5082375478927202",
"i_score": "0.04626620037029417",
"factors": ["2nd"],
},
{
"pk": "01GS2N557FTV0SCK5TP2KENVAF",
"id": "63e8c5d31e033af45abfb64d",
"s_score": "0.7",
"i_score": "0.37718576424604",
"factors": ["2nd", "computer", "laptop"],
},
{
"pk": "01GS2N63S6VM1HZ6RJVH6M1XQJ",
"id": "63e8c743414c482153e332e6",
"s_score": "0.5082375478927202",
"i_score": "0.24141123225673727",
"factors": ["2nd", "thumbdrive", "portables"],
},
],
}
This is going to be a feed of a user and if he has viewed the first item (with "pk": "01GS2N47G8WK2831GNHMGRVDJT"
), we will need to delete this item from his feed.
Currently, what I am having to do is to find the key with "user_id": "john_001"
, retrieve the feed_items
to a Python list and remove the item with that pk
, then reassign the feed_items
and save the item. It's as the following:
feed = Feed.find(Feed.user_id = "john_001").first()
feed_items = feed.feed_items
new_feed_items = [i in feed_items if i["pk"] != "01GS2N47G8WK2831GNHMGRVDJT"]
feed.feed_items = new_feed_items
feed.save()
Is there any better way to do this? Because right now the process is taking quite long to complete (we have dozens of thousands of users' feed and there are several deletion processes like this every seconds.