add limit param to query and rangeQuery

Signed-off-by: Vandit Singh <vanditsinghkv@gmail.com>
This commit is contained in:
Vandit Singh 2024-12-09 02:21:30 +05:30
parent fec7ca052a
commit d02c40c79e

View file

@ -435,6 +435,10 @@ func (api *API) options(*http.Request) apiFuncResult {
}
func (api *API) query(r *http.Request) (result apiFuncResult) {
limit, err := parseLimitParam(r.FormValue("limit"))
if err != nil {
return invalidParamError(err, "limit")
}
ts, err := parseTimeParam(r, "time", api.now())
if err != nil {
return invalidParamError(err, "time")
@ -476,6 +480,9 @@ func (api *API) query(r *http.Request) (result apiFuncResult) {
return apiFuncResult{nil, returnAPIError(res.Err), res.Warnings, qry.Close}
}
if limit > 0 {
res = truncateResults(res, limit)
}
// Optional stats field in response if parameter "stats" is not empty.
sr := api.statsRenderer
if sr == nil {
@ -523,6 +530,10 @@ func extractQueryOpts(r *http.Request) (promql.QueryOpts, error) {
}
func (api *API) queryRange(r *http.Request) (result apiFuncResult) {
limit, err := parseLimitParam(r.FormValue("limit"))
if err != nil {
return invalidParamError(err, "limit")
}
start, err := parseTime(r.FormValue("start"))
if err != nil {
return invalidParamError(err, "start")
@ -587,6 +598,10 @@ func (api *API) queryRange(r *http.Request) (result apiFuncResult) {
return apiFuncResult{nil, returnAPIError(res.Err), res.Warnings, qry.Close}
}
if limit > 0 {
res = truncateResults(res, limit)
}
// Optional stats field in response if parameter "stats" is not empty.
sr := api.statsRenderer
if sr == nil {
@ -2099,3 +2114,22 @@ func toHintLimit(limit int) int {
}
return limit
}
func truncateResults(result *promql.Result, limit int) *promql.Result {
switch v := result.Value.(type) {
case promql.Matrix:
if len(v) > limit {
result.Value = v[:limit]
}
case promql.Vector:
if len(v) > limit {
result.Value = v[:limit]
}
default:
// No truncation for other types (Scalars or Strings)
return result
}
// Return the modified result
return result
}