Skip to content

Commit

Permalink
fix(db): slow newest/oldest milestone query (#1071)
Browse files Browse the repository at this point in the history
* fix(db): slow newest/oldest milestone query

* rename
  • Loading branch information
grtlr committed Jan 27, 2023
1 parent 3568cfe commit 5e3b9f9
Showing 1 changed file with 18 additions and 21 deletions.
39 changes: 18 additions & 21 deletions src/db/collections/milestone.rs
Expand Up @@ -247,34 +247,31 @@ impl MilestoneCollection {
.await
}

/// Find the newest milestone.
pub async fn get_newest_milestone(&self) -> Result<Option<MilestoneIndexTimestamp>, Error> {
self.find_one(
doc! {},
FindOneOptions::builder()
.sort(doc! { "at.milestone_index": BY_NEWEST })
.projection(doc! {
async fn get_first_milestone_sorted(&self, order: i32) -> Result<Option<MilestoneIndexTimestamp>, Error> {
self.aggregate(
[
doc! { "$sort": doc! { "at.milestone_index": order } },
doc! { "$limit": 1 },
doc! { "$project": doc! {
"milestone_index": "$at.milestone_index",
"milestone_timestamp": "$at.milestone_timestamp",
})
.build(),
"milestone_timestamp": "$at.milestone_timestamp"
} },
],
None,
)
.await?
.try_next()
.await
}

/// Find the newest milestone.
pub async fn get_newest_milestone(&self) -> Result<Option<MilestoneIndexTimestamp>, Error> {
self.get_first_milestone_sorted(BY_NEWEST).await
}

/// Find the oldest milestone.
pub async fn get_oldest_milestone(&self) -> Result<Option<MilestoneIndexTimestamp>, Error> {
self.find_one(
doc! {},
FindOneOptions::builder()
.sort(doc! { "at.milestone_index": BY_OLDEST })
.projection(doc! {
"milestone_index": "$at.milestone_index",
"milestone_timestamp": "$at.milestone_timestamp",
})
.build(),
)
.await
self.get_first_milestone_sorted(BY_OLDEST).await
}

/// Gets the current ledger index.
Expand Down

0 comments on commit 5e3b9f9

Please sign in to comment.