Yêu cầu thg 12 4, 2024 10:17 SA 179 0 2
  • 179 0 2
0

Aggregation trên Spring boot cực kỳ chậm

Chia sẻ
  • 179 0 2

Chào mọi người, em có đoạn Aggregation trong spring boot như sau:

        @Aggregation(pipeline = {
                        "{ $match: { 'createdAt': { $gte: ?0, $lt: ?1 } } }",
                        "{ $lookup: { from: 'UserAccount', localField: 'email', foreignField: 'email', as: 'account' } }",
                        "{ $lookup: { from: 'Province', localField: 'account.locationId', foreignField: 'locationId', as: 'location' } }",
                        "{ $group: { _id: { description: { $arrayElemAt: ['$location.description', 0] } }, number: { $sum: 1 } } }",
                        "{ $project: { province: '$_id.description', number: 1, _id: 0 } }",
                        "{ $sort: { number: -1 } }"
        })

Khi gọi API thì mất khoảng 40s mặc dù chỉ trả về 30 phần tử, nhưng khi gọi aggregate trong Studio 3T thì lại chưa đến 1s:

db.getCollection("SessionMesh").aggregate([

   {
     $lookup: {
       from: "UserAccount",
       localField: "email",
       foreignField: "email",
       as: "account"
     }
   },
   {
     $lookup: {
       from: "Province",
       localField: "account.locationId",
       foreignField: "locationId",
       as: "location"
     }
   },
   {
     $group: {
       _id: { description: { $arrayElemAt: ["$location.description", 0] } }, count: { $sum: 1 } 
     }
   },
   {
     $project: {
       province: '$_id.description', count: 1, _id: 0
     }
   },
   {
       $sort: {
           count: -1
       }
   }
])

Cho em hỏi tại sao lại có sự khác biệt lớn đến như vậy và cách khắc phục như thế nào ạ. Em xin cảm ơn.

2 CÂU TRẢ LỜI


Đã trả lời thg 12 5, 2024 2:29 SA
Đã được chấp nhận
0

Sau khi đánh 2 cái index thì em đã khắc phục đc r ạ 😂

Chia sẻ
Đã trả lời thg 12 5, 2024 1:13 SA
0

Trong spring boot người ta rất ích ai dùng kiểu này , bạn có thể viết Native query

Chia sẻ
Avatar Hùng Trần @hungtvk12
thg 12 7, 2024 11:00 SA

vẫn dùng ngon bạn ơi, cơ bản là do cách bạn kia xử lý thôi