Skip to content

Commit 2849531

Browse files
committed
refactor: use limit() instead of tail() for fetching smart attributes (upstream PR AnalogJ#829)
2 parents d134ad7 + eb6f3e4 commit 2849531

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

webapp/backend/pkg/database/scrutiny_repository_device_smart_attributes.go

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,12 +149,17 @@ func (sr *scrutinyRepository) aggregateSmartAttributesQuery(wwn string, duration
149149

150150
if len(nestedDurationKeys) == 1 {
151151
//there's only one bucket being queried, no need to union, just aggregate the dataset and return
152-
partialQueryStr = append(partialQueryStr, []string{
153-
sr.generateSmartAttributesSubquery(wwn, nestedDurationKeys[0], selectEntries, selectEntriesOffset, attributes),
152+
subqueryParts := []string{
153+
sr.generateSmartAttributesSubquery(wwn, nestedDurationKeys[0], 0, 0, attributes),
154154
fmt.Sprintf(`%sData`, nestedDurationKeys[0]),
155155
`|> sort(columns: ["_time"], desc: true)`,
156-
`|> yield()`,
157-
}...)
156+
}
157+
if selectEntries > 0 {
158+
// Use limit() instead of tail() after desc sort to get the newest entries
159+
subqueryParts = append(subqueryParts, fmt.Sprintf(`|> limit(n: %d, offset: %d)`, selectEntries, selectEntriesOffset))
160+
}
161+
subqueryParts = append(subqueryParts, `|> yield()`)
162+
partialQueryStr = append(partialQueryStr, subqueryParts...)
158163
return strings.Join(partialQueryStr, "\n")
159164
}
160165

@@ -177,7 +182,9 @@ func (sr *scrutinyRepository) aggregateSmartAttributesQuery(wwn string, duration
177182
`|> sort(columns: ["_time"], desc: true)`,
178183
}...)
179184
if selectEntries > 0 {
180-
partialQueryStr = append(partialQueryStr, fmt.Sprintf(`|> tail(n: %d, offset: %d)`, selectEntries, selectEntriesOffset))
185+
// Use limit() instead of tail() after desc sort to get the newest entries
186+
// tail() would get the oldest entries from the end, but we want the newest from the beginning
187+
partialQueryStr = append(partialQueryStr, fmt.Sprintf(`|> limit(n: %d, offset: %d)`, selectEntries, selectEntriesOffset))
181188
}
182189
partialQueryStr = append(partialQueryStr, `|> yield(name: "last")`)
183190

@@ -196,7 +203,7 @@ func (sr *scrutinyRepository) generateSmartAttributesSubquery(wwn string, durati
196203
}
197204

198205
partialQueryStr = append(partialQueryStr, `|> aggregateWindow(every: 1d, fn: last, createEmpty: false)`)
199-
206+
200207
if selectEntries > 0 {
201208
partialQueryStr = append(partialQueryStr, fmt.Sprintf(`|> tail(n: %d, offset: %d)`, selectEntries, selectEntriesOffset))
202209
}

0 commit comments

Comments
 (0)