Precalculate index stats

This commit is contained in:
Pijus Kamandulis
2025-06-23 17:52:20 +03:00
parent d801debaf6
commit be637f4540
13 changed files with 243 additions and 81 deletions

View File

@@ -17,6 +17,8 @@ const (
TopSharesCollectionName = "TopShares"
TopSharesAmount = 20
TimeWindowHighShareCollectionName = "TimeWindowHighShareStat"
)
func InitDatabase(path string) (*clover.DB, error) {
@@ -65,6 +67,21 @@ func InitDatabase(path string) (*clover.DB, error) {
}
}
// Init TimeWindowHighShareStat collection
hasTimeWindowCollection, err := db.HasCollection(TimeWindowHighShareCollectionName)
if err != nil {
return nil, fmt.Errorf("failed to check TimeWindowHighShare collection: %v", err)
}
if !hasTimeWindowCollection {
if err := db.CreateCollection(TimeWindowHighShareCollectionName); err != nil {
return nil, fmt.Errorf("failed to create TimeWindowHighShare collection: %v", err)
}
if err := db.CreateIndex(TimeWindowHighShareCollectionName, "TimeWindowID"); err != nil {
return nil, fmt.Errorf("failed to create index for TimeWindowHighShare: %v", err)
}
}
return db, nil
}
@@ -165,3 +182,37 @@ func ReplaceTopShares(db *clover.DB, shares []models.ShareLog) {
log.Printf("Replaced TopShares with %d shares", len(shares))
}
func GetTimeWindowHighShares(db *clover.DB) []models.TimeWindowHighShare {
results, err := db.FindAll(
c.NewQuery(TimeWindowHighShareCollectionName).
Sort(c.SortOption{Field: "TimeWindowID", Direction: 1}),
)
if err != nil {
log.Printf("failed to list time window high shares: %v", err)
return nil
}
timeWindowHighShares := make([]models.TimeWindowHighShare, len(results))
for idx, doc := range results {
var timeWindowHighShare models.TimeWindowHighShare
doc.Unmarshal(&timeWindowHighShare)
timeWindowHighShares[idx] = timeWindowHighShare
}
return timeWindowHighShares
}
func SetTimeWindowHighShare(db *clover.DB, share models.TimeWindowHighShare) error {
doc := document.NewDocumentOf(&share)
existingDoc, _ := db.FindFirst(c.NewQuery(TimeWindowHighShareCollectionName).
Where(c.Field("TimeWindowID").Eq(share.TimeWindowID)))
if existingDoc != nil {
db.ReplaceById(TimeWindowHighShareCollectionName, existingDoc.ObjectId(), doc)
} else {
db.InsertOne(TimeWindowHighShareCollectionName, doc)
}
return nil
}