Asked Dec 4th, 2024 10:17 a.m. 166 0 2
  • 166 0 2
0

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

Share
  • 166 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 ANSWERS


Answered Dec 5th, 2024 2:29 a.m.
Accepted
0

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

Share
Answered Dec 5th, 2024 1:13 a.m.
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

Share
Avatar Hùng Trần @hungtvk12
Dec 7th, 2024 11:00 a.m.

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

0
| Reply
Share
Viblo
Let's register a Viblo Account to get more interesting posts.