Performance improvements on finding a random post for API and bot '/start' command
Some checks failed
release / Build and push Docker image (push) Has been cancelled

This commit is contained in:
2025-02-26 13:41:43 +03:30
parent 39fa7a8219
commit b343438f9e
2 changed files with 21 additions and 10 deletions

View File

@@ -24,15 +24,19 @@ public class HandleStartMessage
// .Where(post => post.MediaAttachments.Any(media => media.Approved))
// .ToListAsync();
var filter = Builders<Post>.Filter.ElemMatch(post => post.MediaAttachments, Builders<MediaAttachment>.Filter.Eq(media => media.Approved, true));
var mediaAttachmentsToSelect = await _db.Find(filter).ToListAsync();
var filter = Builders<Post>.Filter.ElemMatch(post => post.MediaAttachments,
Builders<MediaAttachment>.Filter.Eq(media => media.Approved, true));
var projection = Builders<Post>.Projection
.Include(p => p.Url)
.Include(p => p.Account.DisplayName)
.Include(p => p.MediaAttachments);
var selectedPost = await _db.Aggregate().Match(filter).Project<Post>(projection).Sample(1).FirstOrDefaultAsync();
// select random approved media attachment
var selectedMediaAttachment = mediaAttachmentsToSelect[new Random().Next(mediaAttachmentsToSelect.Count)];
// send media attachment
await _bot.SendPhoto(message.Chat.Id,
selectedMediaAttachment.MediaAttachments.FirstOrDefault(m => m.Approved == true).Url,
$"Here is your cat!🐈\n" + "<a href=\"" + selectedMediaAttachment.Url + "\">" +
selectedPost.MediaAttachments.FirstOrDefault(m => m.Approved).RemoteUrl,
$"Here is your cat!🐈\n" + "<a href=\"" + selectedPost.Url + "\">" +
$"View on Mastodon " + " </a>", ParseMode.Html
, replyMarkup: new InlineKeyboardMarkup()
.AddButton(InlineKeyboardButton.WithUrl("Join channel 😺", "https://t.me/catsofmastodon"))

View File

@@ -51,16 +51,23 @@ public class ServerStartup
var stopwatch = Stopwatch.StartNew();
// Choose all posts media attachments that are approved
var filter = Builders<Post>.Filter.ElemMatch(post => post.MediaAttachments, Builders<MediaAttachment>.Filter.Eq(media => media.Approved, true));
var mediaAttachmentsToSelect = await _db.Find(filter).ToListAsync();
var filter = Builders<Post>.Filter.ElemMatch(post => post.MediaAttachments,
Builders<MediaAttachment>.Filter.Eq(media => media.Approved, true));
var projection = Builders<Post>.Projection
.Include(p => p.Url)
.Include(p => p.Account.DisplayName)
.Include(p => p.MediaAttachments);
var selectedPost = await _db.Aggregate().Match(filter).Project<Post>(projection).Sample(1).FirstOrDefaultAsync();
// Stop and print execution time
stopwatch.Stop();
Console.WriteLine($"Query executed in: {stopwatch.ElapsedMilliseconds} ms");
// Select random approved media attachment
var selectedPost = mediaAttachmentsToSelect[new Random().Next(mediaAttachmentsToSelect.Count)];
// Send as JSON
selectedPost.MediaAttachments = selectedPost.MediaAttachments
.Where(media => media.Approved)
.ToList();
await context.Response.WriteAsJsonAsync(selectedPost);
});
});