Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

chore: support non-dsl search in dashboards v2 list apis (#12051)

Naman Verma707f01bd9c8e
diff --git a/pkg/modules/dashboard/impldashboard/listfilter.go b/pkg/modules/dashboard/impldashboard/listfilter.go
index baa1c3ad00..dd87ce4a0e 100644
--- a/pkg/modules/dashboard/impldashboard/listfilter.go
+++ b/pkg/modules/dashboard/impldashboard/listfilter.go
@@ -20,21 +20,21 @@ func (c Compiled) IsEmpty() bool {
// Compile always returns a non-nil *Compiled. An empty query (or one that
// produces no SQL) yields a Compiled with an empty SQL — callers gate on
// SQL != "" rather than a nil check.
+//
+// A `key OP value` term compiles to a DSL predicate; a bare word is a
+// case-insensitive substring search over the dashboard name, description, and tag
+// keys/values. They compose through AND/OR/NOT, so `prod payment` matches both
+// words (implicit AND) and `prod OR name = 'x'` mixes free text with a filter. A
+// quoted token matches literally, e.g. `"prod payment"`.
func Compile(query string, formatter sqlstore.SQLFormatter) (*Compiled, error) {
- if len(query) == 0 {
+ if len(strings.TrimSpace(query)) == 0 {
return &Compiled{}, nil
}
- queryVisitor := newVisitor(formatter)
- sql, args, syntaxErrs := queryVisitor.compile(query)
-
- if len(syntaxErrs) > 0 {
- return nil, errors.NewInvalidInputf(dashboardtypes.ErrCodeDashboardListFilterInvalid,
- "invalid filter query: %s", strings.Join(syntaxErrs, "; "))
- }
- if len(queryVisitor.errors) > 0 {
+ sql, args, errs := newVisitor(formatter).compile(query)
+ if len(errs) > 0 {
return nil, errors.NewInvalidInputf(dashboardtypes.ErrCodeDashboardListFilterInvalid,
- "invalid filter query: %s", strings.Join(queryVisitor.errors, "; "))
+ "invalid filter query: %s", strings.Join(errs, "; "))
}
return &Compiled{
diff --git a/pkg/modules/dashboard/impldashboard/listfilter_test.go b/pkg/modules/dashboard/impldashboard/listfilter_test.go
index 277767919c..075fdf3171 100644
--- a/pkg/modules/dashboard/impldashboard/listfilter_test.go
+++ b/pkg/modules/dashboard/impldashboard/listfilter_test.go
@@ -460,6 +460,83 @@ func TestCompile_ComplexExamples(t *testing.T) {
})
}
+func TestCompile_FreeText(t *testing.T) {
+ // freeTextSQL is the predicate every free-text query compiles to; only the
+ // bound pattern differs.
+ freeTextSQL := `
+ (
+ lower(COALESCE(json_extract("dashboard"."data", '$.spec.display.name'), '')) LIKE LOWER(?) ESCAPE '\'
+ OR lower(COALESCE(json_extract("dashboard"."data", '$.spec.display.description'), '')) LIKE LOWER(?) ESCAPE '\'
+ OR EXISTS (
+ SELECT 1 FROM tag_relation tr
+ JOIN tag t ON t.id = tr.tag_id
+ WHERE tr.kind = ? AND tr.resource_id = dashboard.id
+ AND (lower(COALESCE(t.key, '')) LIKE LOWER(?) ESCAPE '\' OR lower(COALESCE(t.value, '')) LIKE LOWER(?) ESCAPE '\')
+ ))`
+ freeTextArgs := func(pattern string) []any {
+ return []any{pattern, pattern, kindArg, pattern, pattern}
+ }
+
+ runCompileCases(t, []compileCase{
+ {
+ subtestName: "single bare word",
+ dslQueryToCompile: `payment`,
+ expectedSQL: freeTextSQL,
+ expectedArgs: freeTextArgs("%payment%"),
+ },
+ {
+ // consecutive words are implicit-AND per the grammar, so each is its
+ // own term; `"prod payment"` (below) is the way to match the phrase
+ subtestName: "words are separate terms AND'd together",
+ dslQueryToCompile: `prod payment`,
+ expectedSQL: "(" + freeTextSQL + " AND " + freeTextSQL + ")",
+ expectedArgs: append(freeTextArgs("%prod%"), freeTextArgs("%payment%")...),
+ },
+ {
+ subtestName: "a quoted token matches the whole phrase",
+ dslQueryToCompile: `"prod payment"`,
+ expectedSQL: freeTextSQL,
+ expectedArgs: freeTextArgs("%prod payment%"),
+ },
+ {
+ subtestName: "quoting is the escape hatch for a DSL-like literal",
+ dslQueryToCompile: `"team = prod"`,
+ expectedSQL: freeTextSQL,
+ expectedArgs: freeTextArgs("%team = prod%"),
+ },
+ {
+ subtestName: "LIKE wildcards in the term are escaped to match literally",
+ dslQueryToCompile: `"50%"`,
+ expectedSQL: freeTextSQL,
+ expectedArgs: freeTextArgs(`%50\%%`),
+ },
+ {
+ subtestName: "surrounding whitespace is trimmed",
+ dslQueryToCompile: ` payment `,
+ expectedSQL: freeTextSQL,
+ expectedArgs: freeTextArgs("%payment%"),
+ },
+ {
+ subtestName: "free-text term composes with a comparison via AND",
+ dslQueryToCompile: `prod AND name CONTAINS 'signoz'`,
+ expectedSQL: "(" + freeTextSQL + ` AND json_extract("dashboard"."data", '$.spec.display.name') LIKE ? ESCAPE '\')`,
+ expectedArgs: append(freeTextArgs("%prod%"), "%signoz%"),
+ },
+ {
+ subtestName: "free-text words compose with a comparison via OR",
+ dslQueryToCompile: `prod payment OR name = 'x'`,
+ expectedSQL: "((" + freeTextSQL + " AND " + freeTextSQL + `) OR json_extract("dashboard"."data", '$.spec.display.name') = ?)`,
+ expectedArgs: append(append(freeTextArgs("%prod%"), freeTextArgs("%payment%")...), "x"),
+ },
+ {
+ subtestName: "NOT negates a free-text term",
+ dslQueryToCompile: `NOT payment`,
+ expectedSQL: "NOT (" + freeTextSQL + ")",
+ expectedArgs: freeTextArgs("%payment%"),
+ },
+ })
+}
+
func TestCompile_Rejections(t *testing.T) {
runCompileCases(t, []compileCase{
{
diff --git a/pkg/modules/dashboard/impldashboard/listfilter_visitor.go b/pkg/modules/dashboard/impldashboard/listfilter_visitor.go
index 0340d563f1..0113739497 100644
--- a/pkg/modules/dashboard/impldashboard/listfilter_visitor.go
+++ b/pkg/modules/dashboard/impldashboard/listfilter_visitor.go
@@ -32,13 +32,19 @@ func newVisitor(formatter sqlstore.SQLFormatter) *visitor {
}
}
-// compile turns the parse tree into `?`-placeholder WHERE SQL + arguments for bun.
+// compile builds `?`-placeholder WHERE SQL + args for bun. Each term is either a
+// `key OP value` comparison or a bare token that becomes a free-text search; the
+// two compose through the boolean grammar (AND/OR/NOT). Malformed input is
+// returned as errors.
func (v *visitor) compile(query string) (string, []any, []string) {
tree, _, collector := filterquery.Parse(query)
if len(collector.Errors) > 0 {
return "", nil, collector.Errors
}
condition, _ := v.visit(tree).(string)
+ if len(v.errors) > 0 {
+ return "", nil, v.errors
+ }
if condition == "" {
return "", nil, nil
}
@@ -119,10 +125,10 @@ func (v *visitor) VisitPrimary(ctx *grammar.PrimaryContext) any {
if ctx.Comparison() != nil {
return v.visit(ctx.Comparison())
}
- // Bare keys, values, full text, and function calls are not part of the
- // dashboard list DSL.
- v.addError("unsupported expression %q — every term must be of the form `key OP value`", ctx.GetText())
- return ""
+ // A lone key/value/full-text token is a free-text term, composed with any
+ // comparisons through the boolean grammar. A quoted token matches its contents
+ // literally — the escape hatch for a phrase or a term that looks like DSL.
+ return v.buildFreeTextTerm(trimQuotes(ctx.GetText()))
}
// VisitComparison dispatches a single `key OP value` term. A key that matches
@@ -401,6 +407,50 @@ func buildSubqueryForTagKeyAndValue(subqueryBuilder *sqlbuilder.SelectBuilder, t
return buildSubqueryForTagKey(subqueryBuilder, tagKey).Where(valuePredicate)
}
+// ─── free-text search ────────────────────────────────────────────────────────
+
+// buildFreeTextTerm matches value as a case-insensitive substring of the
+// dashboard name, description, or any tag key/value.
+func (v *visitor) buildFreeTextTerm(value string) string {
+ nameColumn := string(v.formatter.JSONExtractString("dashboard.data", "$.spec.display.name"))
+ descriptionColumn := string(v.formatter.JSONExtractString("dashboard.data", "$.spec.display.description"))
+ namePredicate := v.buildFreeTextContains(v.selectBuilder, nameColumn, value)
+ descriptionPredicate := v.buildFreeTextContains(v.selectBuilder, descriptionColumn, value)
+
+ subqueryBuilder := sqlbuilder.NewSelectBuilder()
+ keyPredicate := v.buildFreeTextContains(subqueryBuilder, "t.key", value)
+ valuePredicate := v.buildFreeTextContains(subqueryBuilder, "t.value", value)
+ buildSubqueryForFreeTextTag(subqueryBuilder, keyPredicate, valuePredicate)
+ tagPredicate := v.selectBuilder.Exists(subqueryBuilder)
+
+ return v.selectBuilder.Or(namePredicate, descriptionPredicate, tagPredicate)
+}
+
+// buildFreeTextContains emits a case-insensitive contains as
+// LOWER(COALESCE(col, '')) LIKE LOWER(?), identical on SQLite and Postgres.
+// COALESCE keeps a NULL column (an absent description) false rather than NULL —
+// otherwise `NOT (…)` goes NULL and drops every description-less dashboard. The
+// value's % and _ are escaped, and ESCAPE pins backslash as the escape char.
+func (v *visitor) buildFreeTextContains(builder *sqlbuilder.SelectBuilder, columnExpression, value string) string {
+ lowerColumn := string(v.formatter.LowerExpression("COALESCE(" + columnExpression + ", '')"))
+ pattern := "%" + v.formatter.EscapeLikePattern(value) + "%"
+ return fmt.Sprintf("%s LIKE LOWER(%s) ESCAPE '\\'", lowerColumn, builder.Var(pattern))
+}
+
+func buildSubqueryForFreeTextTag(subqueryBuilder *sqlbuilder.SelectBuilder, keyPredicate, valuePredicate string) *sqlbuilder.SelectBuilder {
+ const dashboardTagKind = `"dashboard"`
+
+ return subqueryBuilder.
+ Select("1").
+ From("tag_relation tr").
+ Join("tag t", "t.id = tr.tag_id").
+ Where(
+ subqueryBuilder.Equal("tr.kind", dashboardTagKind),
+ "tr.resource_id = dashboard.id",
+ subqueryBuilder.Or(keyPredicate, valuePredicate),
+ )
+}
+
// ─── value extraction helpers ───────────────────────────────────────────────
func (v *visitor) addError(format string, arguments ...any) {
diff --git a/tests/integration/tests/dashboard/03_v2_dashboard.py b/tests/integration/tests/dashboard/03_v2_dashboard.py
index 2e3200f4c3..4a515a64b7 100644
--- a/tests/integration/tests/dashboard/03_v2_dashboard.py
+++ b/tests/integration/tests/dashboard/03_v2_dashboard.py
@@ -723,7 +723,74 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta
assert response.status_code == HTTPStatus.OK, response.text
assert {d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]} == expected, query
- # ── stage 5: name sort honours order ─────────────────────────────────────
+ # ── stage 5: free-text search (bare-word terms) ──────────────────────────
+ # A bare word is a case-insensitive substring search over the name and every
+ # tag key/value. Consecutive words are separate terms AND'd together (implicit
+ # AND); a quoted token matches the whole phrase; and a term composes with
+ # comparisons via AND/OR.
+ free_text_cases = [
+ # name substring, matched case-insensitively
+ ("overview", {"Alpha Overview", "Beta Overview", "Zeta Overview"}),
+ # matches a name substring on some rows and a tag value on the same rows
+ ("storage", {"Gamma Storage", "Delta Storage"}),
+ # tag value only (no name contains "pulse")
+ ("pulse", {"Alpha Overview", "Beta Overview", "Zeta Overview"}),
+ # tag value only
+ ("critical", {"Delta Storage", "Epsilon Metrics"}),
+ # tag key only
+ ("tier", {"Delta Storage", "Epsilon Metrics"}),
+ # tag key present on every dashboard
+ (
+ "env",
+ {
+ "Alpha Overview",
+ "Beta Overview",
+ "Gamma Storage",
+ "Delta Storage",
+ "Epsilon Metrics",
+ "Zeta Overview",
+ },
+ ),
+ # two words AND'd: only Delta matches both "delta" and "storage"
+ ("delta storage", {"Delta Storage"}),
+ # two words AND'd with no dashboard matching both
+ ("overview storage", set()),
+ # a quoted token matches the whole phrase
+ ('"Alpha Overview"', {"Alpha Overview"}),
+ # a free-text term AND'd with a comparison (the reviewer's case)
+ ("pulse AND env = 'prod'", {"Alpha Overview"}),
+ # a free-text term OR'd with a comparison
+ (
+ "storage OR env = 'staging'",
+ {"Gamma Storage", "Delta Storage", "Epsilon Metrics", "Zeta Overview"},
+ ),
+ # no match anywhere
+ ("nonexistent", set()),
+ # NOT over a term nothing matches returns everything — including these
+ # description-less dashboards, which a negated search must not exclude.
+ (
+ "NOT payment",
+ {
+ "Alpha Overview",
+ "Beta Overview",
+ "Gamma Storage",
+ "Delta Storage",
+ "Epsilon Metrics",
+ "Zeta Overview",
+ },
+ ),
+ ]
+ for query, expected in free_text_cases:
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),
+ params={"query": query, "limit": 200},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ assert {d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]} == expected, query
+
+ # ── stage 6: name sort honours order ─────────────────────────────────────
response = requests.get(
signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),
params={"sort": "name", "order": "asc", "limit": 200},
@@ -753,7 +820,7 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta
"Alpha Overview",
]
- # ── stage 6: pinning floats a dashboard to the top of any ordering ───────
+ # ── stage 7: pinning floats a dashboard to the top of any ordering ───────
assert (
requests.put(
signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{ids['lc-gamma']}/pins"),
@@ -791,7 +858,7 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta
]
assert all("pinned" not in d for d in response.json()["data"]["dashboards"])
- # ── stage 7: unpinning restores the natural ordering ─────────────────────
+ # ── stage 8: unpinning restores the natural ordering ─────────────────────
assert (
requests.delete(
signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{ids['lc-gamma']}/pins"),
@@ -815,7 +882,7 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta
"Zeta Overview",
]
- # ── stage 8: update mutates the spec but keeps the immutable name ────────
+ # ── stage 9: update mutates the spec but keeps the immutable name ────────
update_body = {
"schemaVersion": "v6",
"name": "lc-alpha",
@@ -840,7 +907,18 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta
)
assert response.json()["data"]["spec"]["display"]["description"] == "now with a description"
- # ── stage 9: a locked dashboard rejects updates until unlocked ───────────
+ # free-text search also matches the description (only Alpha has one now);
+ # quoted so the phrase matches as one substring rather than per-word
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),
+ params={"query": '"now with a description"', "limit": 200},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ assert {d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]} == {"Alpha Overview"}
+
+ # ── stage 10: a locked dashboard rejects updates until unlocked ──────────
assert (
requests.put(
signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-beta']}/lock"),
@@ -880,7 +958,7 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta
== HTTPStatus.OK
)
- # ── stage 10: delete removes the dashboard from get and list ─────────────
+ # ── stage 11: delete removes the dashboard from get and list ─────────────
assert (
requests.delete(
signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-gamma']}"),
@@ -912,7 +990,7 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta
"Zeta Overview",
}
- # ── stage 11: clone suffixes the display name and mints a new, retrievable one ─
+ # ── stage 12: clone suffixes the display name and mints a new, retrievable one ─
response = requests.post(
signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-alpha']}/clone"),
headers={"Authorization": f"Bearer {token}"},