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.

fix: fetch only required log fields (#8299)

Nityananda Gohain50a5b88708ed
diff --git a/pkg/query-service/app/clickhouseReader/reader.go b/pkg/query-service/app/clickhouseReader/reader.go
index 268950132e..f9b4ed908b 100644
--- a/pkg/query-service/app/clickhouseReader/reader.go
+++ b/pkg/query-service/app/clickhouseReader/reader.go
@@ -38,7 +38,6 @@ import (
"go.uber.org/zap"
queryprogress "github.com/SigNoz/signoz/pkg/query-service/app/clickhouseReader/query_progress"
- "github.com/SigNoz/signoz/pkg/query-service/app/logs"
"github.com/SigNoz/signoz/pkg/query-service/app/resource"
"github.com/SigNoz/signoz/pkg/query-service/app/services"
"github.com/SigNoz/signoz/pkg/query-service/app/traces/smart"
@@ -2501,27 +2500,43 @@ func (r *ClickHouseReader) GetTagsInfoInLastHeartBeatInterval(ctx context.Contex
return &tagsInfo, nil
}
-// remove this after sometime
-func removeUnderscoreDuplicateFields(fields []model.Field) []model.Field {
- lookup := map[string]model.Field{}
- for _, v := range fields {
- lookup[v.Name+v.DataType] = v
+func (r *ClickHouseReader) GetLogFields(ctx context.Context) (*model.GetFieldsResponse, *model.ApiError) {
+ // response will contain top level fields from the otel log model
+ response := model.GetFieldsResponse{
+ Selected: constants.StaticSelectedLogFields,
+ Interesting: []model.Field{},
}
- for k := range lookup {
- if strings.Contains(k, ".") {
- delete(lookup, strings.ReplaceAll(k, ".", "_"))
- }
+ // get attribute keys
+ attributes := []model.Field{}
+ query := fmt.Sprintf("SELECT DISTINCT name, datatype from %s.%s group by name, datatype", r.logsDB, r.logsAttributeKeys)
+ err := r.db.Select(ctx, &attributes, query)
+ if err != nil {
+ return nil, &model.ApiError{Err: err, Typ: model.ErrorInternal}
}
- updatedFields := []model.Field{}
- for _, v := range lookup {
- updatedFields = append(updatedFields, v)
+ // get resource keys
+ resources := []model.Field{}
+ query = fmt.Sprintf("SELECT DISTINCT name, datatype from %s.%s group by name, datatype", r.logsDB, r.logsResourceKeys)
+ err = r.db.Select(ctx, &resources, query)
+ if err != nil {
+ return nil, &model.ApiError{Err: err, Typ: model.ErrorInternal}
}
- return updatedFields
+
+ statements := []model.ShowCreateTableStatement{}
+ query = fmt.Sprintf("SHOW CREATE TABLE %s.%s", r.logsDB, r.logsLocalTableName)
+ err = r.db.Select(ctx, &statements, query)
+ if err != nil {
+ return nil, &model.ApiError{Err: err, Typ: model.ErrorInternal}
+ }
+
+ r.extractSelectedAndInterestingFields(statements[0].Statement, constants.Attributes, &attributes, &response)
+ r.extractSelectedAndInterestingFields(statements[0].Statement, constants.Resources, &resources, &response)
+
+ return &response, nil
}
-func (r *ClickHouseReader) GetLogFields(ctx context.Context) (*model.GetFieldsResponse, *model.ApiError) {
+func (r *ClickHouseReader) GetLogFieldsFromNames(ctx context.Context, fieldNames []string) (*model.GetFieldsResponse, *model.ApiError) {
// response will contain top level fields from the otel log model
response := model.GetFieldsResponse{
Selected: constants.StaticSelectedLogFields,
@@ -2530,7 +2545,7 @@ func (r *ClickHouseReader) GetLogFields(ctx context.Context) (*model.GetFieldsRe
// get attribute keys
attributes := []model.Field{}
- query := fmt.Sprintf("SELECT DISTINCT name, datatype from %s.%s group by name, datatype", r.logsDB, r.logsAttributeKeys)
+ query := fmt.Sprintf("SELECT DISTINCT name, datatype from %s.%s where name in ('%s') group by name, datatype", r.logsDB, r.logsAttributeKeys, strings.Join(fieldNames, "','"))
err := r.db.Select(ctx, &attributes, query)
if err != nil {
return nil, &model.ApiError{Err: err, Typ: model.ErrorInternal}
@@ -2538,16 +2553,12 @@ func (r *ClickHouseReader) GetLogFields(ctx context.Context) (*model.GetFieldsRe
// get resource keys
resources := []model.Field{}
- query = fmt.Sprintf("SELECT DISTINCT name, datatype from %s.%s group by name, datatype", r.logsDB, r.logsResourceKeys)
+ query = fmt.Sprintf("SELECT DISTINCT name, datatype from %s.%s where name in ('%s') group by name, datatype", r.logsDB, r.logsResourceKeys, strings.Join(fieldNames, "','"))
err = r.db.Select(ctx, &resources, query)
if err != nil {
return nil, &model.ApiError{Err: err, Typ: model.ErrorInternal}
}
- //remove this code after sometime
- attributes = removeUnderscoreDuplicateFields(attributes)
- resources = removeUnderscoreDuplicateFields(resources)
-
statements := []model.ShowCreateTableStatement{}
query = fmt.Sprintf("SHOW CREATE TABLE %s.%s", r.logsDB, r.logsLocalTableName)
err = r.db.Select(ctx, &statements, query)
@@ -2787,219 +2798,6 @@ func (r *ClickHouseReader) UpdateTraceField(ctx context.Context, field *model.Up
return nil
}
-
-func (r *ClickHouseReader) GetLogs(ctx context.Context, params *model.LogsFilterParams) (*[]model.SignozLog, *model.ApiError) {
- response := []model.SignozLog{}
- fields, apiErr := r.GetLogFields(ctx)
- if apiErr != nil {
- return nil, apiErr
- }
-
- isPaginatePrev := logs.CheckIfPrevousPaginateAndModifyOrder(params)
- filterSql, lenFilters, err := logs.GenerateSQLWhere(fields, params)
- if err != nil {
- return nil, &model.ApiError{Err: err, Typ: model.ErrorBadData}
- }
-
- data := map[string]interface{}{
- "lenFilters": lenFilters,
- }
- if lenFilters != 0 {
- claims, errv2 := authtypes.ClaimsFromContext(ctx)
- if errv2 == nil {
- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_LOGS_FILTERS, data, claims.Email, true, false)
- }
- }
-
- query := fmt.Sprintf("%s from %s.%s", constants.LogsSQLSelect, r.logsDB, r.logsTable)
-
- if filterSql != "" {
- query = fmt.Sprintf("%s where %s", query, filterSql)
- }
-
- query = fmt.Sprintf("%s order by %s %s limit %d", query, params.OrderBy, params.Order, params.Limit)
- err = r.db.Select(ctx, &response, query)
- if err != nil {
- return nil, &model.ApiError{Err: err, Typ: model.ErrorInternal}
- }
- if isPaginatePrev {
- // rever the results from db
- for i, j := 0, len(response)-1; i < j; i, j = i+1, j-1 {
- response[i], response[j] = response[j], response[i]
- }
- }
- return &response, nil
-}
-
-func (r *ClickHouseReader) TailLogs(ctx context.Context, client *model.LogsTailClient) {
-
- fields, apiErr := r.GetLogFields(ctx)
- if apiErr != nil {
- client.Error <- apiErr.Err
- return
- }
-
- filterSql, lenFilters, err := logs.GenerateSQLWhere(fields, &model.LogsFilterParams{
- Query: client.Filter.Query,
- })
-
- data := map[string]interface{}{
- "lenFilters": lenFilters,
- }
- if lenFilters != 0 {
- claims, errv2 := authtypes.ClaimsFromContext(ctx)
- if errv2 == nil {
- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_LOGS_FILTERS, data, claims.Email, true, false)
- }
- }
-
- if err != nil {
- client.Error <- err
- return
- }
-
- query := fmt.Sprintf("%s from %s.%s", constants.LogsSQLSelect, r.logsDB, r.logsTable)
-
- tsStart := uint64(time.Now().UnixNano())
- if client.Filter.TimestampStart != 0 {
- tsStart = client.Filter.TimestampStart
- }
-
- var idStart string
- if client.Filter.IdGt != "" {
- idStart = client.Filter.IdGt
- }
-
- ticker := time.NewTicker(time.Duration(r.liveTailRefreshSeconds) * time.Second)
- defer ticker.Stop()
- for {
- select {
- case <-ctx.Done():
- done := true
- client.Done <- &done
- zap.L().Debug("closing go routine : " + client.Name)
- return
- case <-ticker.C:
- // get the new 100 logs as anything more older won't make sense
- tmpQuery := fmt.Sprintf("%s where timestamp >='%d'", query, tsStart)
- if filterSql != "" {
- tmpQuery = fmt.Sprintf("%s and %s", tmpQuery, filterSql)
- }
- if idStart != "" {
- tmpQuery = fmt.Sprintf("%s and id > '%s'", tmpQuery, idStart)
- }
- tmpQuery = fmt.Sprintf("%s order by timestamp desc, id desc limit 100", tmpQuery)
- response := []model.SignozLog{}
- err := r.db.Select(ctx, &response, tmpQuery)
- if err != nil {
- zap.L().Error("Error while getting logs", zap.Error(err))
- client.Error <- err
- return
- }
- for i := len(response) - 1; i >= 0; i-- {
- select {
- case <-ctx.Done():
- done := true
- client.Done <- &done
- zap.L().Debug("closing go routine while sending logs : " + client.Name)
- return
- default:
- client.Logs <- &response[i]
- if i == 0 {
- tsStart = response[i].Timestamp
- idStart = response[i].ID
- }
- }
- }
- }
- }
-}
-
-func (r *ClickHouseReader) AggregateLogs(ctx context.Context, params *model.LogsAggregateParams) (*model.GetLogsAggregatesResponse, *model.ApiError) {
- logAggregatesDBResponseItems := []model.LogsAggregatesDBResponseItem{}
-
- function := "toFloat64(count()) as value"
- if params.Function != "" {
- function = fmt.Sprintf("toFloat64(%s) as value", params.Function)
- }
-
- fields, apiErr := r.GetLogFields(ctx)
- if apiErr != nil {
- return nil, apiErr
- }
-
- filterSql, lenFilters, err := logs.GenerateSQLWhere(fields, &model.LogsFilterParams{
- Query: params.Query,
- })
- if err != nil {
- return nil, &model.ApiError{Err: err, Typ: model.ErrorBadData}
- }
-
- data := map[string]interface{}{
- "lenFilters": lenFilters,
- }
- if lenFilters != 0 {
- claims, errv2 := authtypes.ClaimsFromContext(ctx)
- if errv2 == nil {
- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_LOGS_FILTERS, data, claims.Email, true, false)
- }
- }
-
- query := ""
- if params.GroupBy != "" {
- query = fmt.Sprintf("SELECT toInt64(toUnixTimestamp(toStartOfInterval(toDateTime(timestamp/1000000000), INTERVAL %d minute))*1000000000) as ts_start_interval, toString(%s) as groupBy, "+
- "%s "+
- "FROM %s.%s WHERE (timestamp >= '%d' AND timestamp <= '%d' )",
- params.StepSeconds/60, params.GroupBy, function, r.logsDB, r.logsTable, params.TimestampStart, params.TimestampEnd)
- } else {
- query = fmt.Sprintf("SELECT toInt64(toUnixTimestamp(toStartOfInterval(toDateTime(timestamp/1000000000), INTERVAL %d minute))*1000000000) as ts_start_interval, "+
- "%s "+
- "FROM %s.%s WHERE (timestamp >= '%d' AND timestamp <= '%d' )",
- params.StepSeconds/60, function, r.logsDB, r.logsTable, params.TimestampStart, params.TimestampEnd)
- }
- if filterSql != "" {
- query = fmt.Sprintf("%s AND ( %s ) ", query, filterSql)
- }
- if params.GroupBy != "" {
- query = fmt.Sprintf("%s GROUP BY ts_start_interval, toString(%s) as groupBy ORDER BY ts_start_interval", query, params.GroupBy)
- } else {
- query = fmt.Sprintf("%s GROUP BY ts_start_interval ORDER BY ts_start_interval", query)
- }
-
- err = r.db.Select(ctx, &logAggregatesDBResponseItems, query)
- if err != nil {
- return nil, &model.ApiError{Err: err, Typ: model.ErrorInternal}
- }
-
- aggregateResponse := model.GetLogsAggregatesResponse{
- Items: make(map[int64]model.LogsAggregatesResponseItem),
- }
-
- for i := range logAggregatesDBResponseItems {
- if elem, ok := aggregateResponse.Items[int64(logAggregatesDBResponseItems[i].Timestamp)]; ok {
- if params.GroupBy != "" && logAggregatesDBResponseItems[i].GroupBy != "" {
- elem.GroupBy[logAggregatesDBResponseItems[i].GroupBy] = logAggregatesDBResponseItems[i].Value
- }
- aggregateResponse.Items[logAggregatesDBResponseItems[i].Timestamp] = elem
- } else {
- if params.GroupBy != "" && logAggregatesDBResponseItems[i].GroupBy != "" {
- aggregateResponse.Items[logAggregatesDBResponseItems[i].Timestamp] = model.LogsAggregatesResponseItem{
- Timestamp: logAggregatesDBResponseItems[i].Timestamp,
- GroupBy: map[string]interface{}{logAggregatesDBResponseItems[i].GroupBy: logAggregatesDBResponseItems[i].Value},
- }
- } else if params.GroupBy == "" {
- aggregateResponse.Items[logAggregatesDBResponseItems[i].Timestamp] = model.LogsAggregatesResponseItem{
- Timestamp: logAggregatesDBResponseItems[i].Timestamp,
- Value: logAggregatesDBResponseItems[i].Value,
- }
- }
- }
-
- }
-
- return &aggregateResponse, nil
-}
-
func (r *ClickHouseReader) QueryDashboardVars(ctx context.Context, query string) (*model.DashboardVar, error) {
var result = model.DashboardVar{VariableValues: make([]interface{}, 0)}
rows, err := r.db.Query(ctx, query)
@@ -4067,10 +3865,6 @@ func (r *ClickHouseReader) GetListResultV3(ctx context.Context, query string) ([
}
}
- // remove duplicate _ attributes for logs.
- // remove this function after a month
- removeDuplicateUnderscoreAttributes(row)
-
rowList = append(rowList, &v3.Row{Timestamp: t, Data: row})
}
@@ -4093,52 +3887,6 @@ func getPersonalisedError(err error) error {
return err
}
-func removeDuplicateUnderscoreAttributes(row map[string]interface{}) {
- if val, ok := row["attributes_int64"]; ok {
- attributes := val.(*map[string]int64)
- for key := range *attributes {
- if strings.Contains(key, ".") {
- uKey := strings.ReplaceAll(key, ".", "_")
- delete(*attributes, uKey)
- }
- }
-
- }
-
- if val, ok := row["attributes_float64"]; ok {
- attributes := val.(*map[string]float64)
- for key := range *attributes {
- if strings.Contains(key, ".") {
- uKey := strings.ReplaceAll(key, ".", "_")
- delete(*attributes, uKey)
- }
- }
-
- }
-
- if val, ok := row["attributes_bool"]; ok {
- attributes := val.(*map[string]bool)
- for key := range *attributes {
- if strings.Contains(key, ".") {
- uKey := strings.ReplaceAll(key, ".", "_")
- delete(*attributes, uKey)
- }
- }
-
- }
- for _, k := range []string{"attributes_string", "resources_string"} {
- if val, ok := row[k]; ok {
- attributes := val.(*map[string]string)
- for key := range *attributes {
- if strings.Contains(key, ".") {
- uKey := strings.ReplaceAll(key, ".", "_")
- delete(*attributes, uKey)
- }
- }
-
- }
- }
-}
func (r *ClickHouseReader) CheckClickHouse(ctx context.Context) error {
rows, err := r.db.Query(ctx, "SELECT 1")
if err != nil {
diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.go
index 724dd8d719..9c838d9bf5 100644
--- a/pkg/query-service/app/http_handler.go
+++ b/pkg/query-service/app/http_handler.go
@@ -959,7 +959,7 @@ func (aH *APIHandler) metaForLinks(ctx context.Context, rule *ruletypes.Gettable
keys := make(map[string]v3.AttributeKey)
if rule.AlertType == ruletypes.AlertTypeLogs {
- logFields, err := aH.reader.GetLogFields(ctx)
+ logFields, err := aH.reader.GetLogFieldsFromNames(ctx, logsv3.GetFieldNames(rule.PostableRule.RuleCondition.CompositeQuery))
if err == nil {
params := &v3.QueryRangeParamsV3{
CompositeQuery: rule.RuleCondition.CompositeQuery,
@@ -4056,78 +4056,15 @@ func (aH *APIHandler) logFieldUpdate(w http.ResponseWriter, r *http.Request) {
}
func (aH *APIHandler) getLogs(w http.ResponseWriter, r *http.Request) {
- params, err := logs.ParseLogFilterParams(r)
- if err != nil {
- apiErr := &model.ApiError{Typ: model.ErrorBadData, Err: err}
- RespondError(w, apiErr, "Incorrect params")
- return
- }
- res, apiErr := aH.reader.GetLogs(r.Context(), params)
- if apiErr != nil {
- RespondError(w, apiErr, "Failed to fetch logs from the DB")
- return
- }
- aH.WriteJSON(w, r, map[string]interface{}{"results": res})
+ aH.WriteJSON(w, r, map[string]interface{}{"results": []model.SignozLog{}})
}
func (aH *APIHandler) tailLogs(w http.ResponseWriter, r *http.Request) {
- params, err := logs.ParseLogFilterParams(r)
- if err != nil {
- apiErr := &model.ApiError{Typ: model.ErrorBadData, Err: err}
- RespondError(w, apiErr, "Incorrect params")
- return
- }
-
- // create the client
- client := &model.LogsTailClient{Name: r.RemoteAddr, Logs: make(chan *model.SignozLog, 1000), Done: make(chan *bool), Error: make(chan error), Filter: *params}
- go aH.reader.TailLogs(r.Context(), client)
-
- w.Header().Set("Connection", "keep-alive")
- w.Header().Set("Content-Type", "text/event-stream")
- w.Header().Set("Cache-Control", "no-cache")
- w.Header().Set("Access-Control-Allow-Origin", "*")
- w.WriteHeader(200)
-
- flusher, ok := w.(http.Flusher)
- if !ok {
- err := model.ApiError{Typ: model.ErrorStreamingNotSupported, Err: nil}
- RespondError(w, &err, "streaming is not supported")
- return
- }
- // flush the headers
- flusher.Flush()
-
- for {
- select {
- case log := <-client.Logs:
- var buf bytes.Buffer
- enc := json.NewEncoder(&buf)
- enc.Encode(log)
- fmt.Fprintf(w, "data: %v\n\n", buf.String())
- flusher.Flush()
- case <-client.Done:
- zap.L().Debug("done!")
- return
- case err := <-client.Error:
- zap.L().Error("error occured", zap.Error(err))
- return
- }
- }
+ return
}
func (aH *APIHandler) logAggregate(w http.ResponseWriter, r *http.Request) {
- params, err := logs.ParseLogAggregateParams(r)
- if err != nil {
- apiErr := &model.ApiError{Typ: model.ErrorBadData, Err: err}
- RespondError(w, apiErr, "Incorrect params")
- return
- }
- res, apiErr := aH.reader.AggregateLogs(r.Context(), params)
- if apiErr != nil {
- RespondError(w, apiErr, "Failed to fetch logs aggregate from the DB")
- return
- }
- aH.WriteJSON(w, r, res)
+ aH.WriteJSON(w, r, model.GetLogsAggregatesResponse{})
}
func parseAgentConfigVersion(r *http.Request) (int, *model.ApiError) {
@@ -4507,7 +4444,7 @@ func (aH *APIHandler) queryRangeV3(ctx context.Context, queryRangeParams *v3.Que
if queryRangeParams.CompositeQuery.QueryType == v3.QueryTypeBuilder {
// check if any enrichment is required for logs if yes then enrich them
if logsv3.EnrichmentRequired(queryRangeParams) {
- logsFields, err := aH.reader.GetLogFields(ctx)
+ logsFields, err := aH.reader.GetLogFieldsFromNames(ctx, logsv3.GetFieldNames(queryRangeParams.CompositeQuery))
if err != nil {
apiErrObj := &model.ApiError{Typ: model.ErrorInternal, Err: err}
RespondError(w, apiErrObj, errQuriesByName)
@@ -4831,7 +4768,7 @@ func (aH *APIHandler) liveTailLogsV2(w http.ResponseWriter, r *http.Request) {
// check if any enrichment is required for logs if yes then enrich them
if logsv3.EnrichmentRequired(queryRangeParams) {
// get the fields if any logs query is present
- logsFields, err := aH.reader.GetLogFields(r.Context())
+ logsFields, err := aH.reader.GetLogFieldsFromNames(r.Context(), logsv3.GetFieldNames(queryRangeParams.CompositeQuery))
if err != nil {
apiErrObj := &model.ApiError{Typ: model.ErrorInternal, Err: err}
RespondError(w, apiErrObj, nil)
@@ -4939,7 +4876,7 @@ func (aH *APIHandler) queryRangeV4(ctx context.Context, queryRangeParams *v3.Que
// check if any enrichment is required for logs if yes then enrich them
if logsv3.EnrichmentRequired(queryRangeParams) {
// get the fields if any logs query is present
- logsFields, err := aH.reader.GetLogFields(r.Context())
+ logsFields, err := aH.reader.GetLogFieldsFromNames(r.Context(), logsv3.GetFieldNames(queryRangeParams.CompositeQuery))
if err != nil {
apiErrObj := &model.ApiError{Typ: model.ErrorInternal, Err: err}
RespondError(w, apiErrObj, nil)
diff --git a/pkg/query-service/app/logs/parser.go b/pkg/query-service/app/logs/parser.go
deleted file mode 100644
index 177320805b..0000000000
--- a/pkg/query-service/app/logs/parser.go
+++ /dev/null
@@ -1,398 +0,0 @@
-package logs
-
-import (
- "fmt"
- "net/http"
- "regexp"
- "strconv"
- "strings"
-
- "github.com/SigNoz/signoz/pkg/query-service/constants"
- "github.com/SigNoz/signoz/pkg/query-service/model"
- "github.com/SigNoz/signoz/pkg/query-service/utils"
-)
-
-var operatorMapping = map[string]string{
- "lt": "<",
- "gt": ">",
- "lte": "<=",
- "gte": ">=",
- "in": "IN",
- "nin": "NOT IN",
- "contains": "ILIKE",
- "ncontains": "NOT ILIKE",
-}
-
-const (
- AND = "and"
- OR = "or"
- ORDER = "order"
- ORDER_BY = "orderBy"
- TIMESTAMP_START = "timestampStart"
- TIMESTAMP_END = "timestampEnd"
- IdGt = "idGt"
- IdLT = "idLt"
- TIMESTAMP = "timestamp"
- ASC = "asc"
- DESC = "desc"
-)
-
-var tokenRegex, _ = regexp.Compile(`(?i)(and( )*?|or( )*?)?(([\w.-]+( )+(in|nin)( )+\([^(]+\))|([\w.]+( )+(gt|lt|gte|lte)( )+(')?[\S]+(')?)|([\w.]+( )+(contains|ncontains))( )+[^\\]?'(.*?[^\\])'|([\w.]+( )+(exists|nexists)( )?))`)
-var operatorRegex, _ = regexp.Compile(`(?i)(?: )(in|nin|gte|lte|gt|lt|contains|ncontains|exists|nexists)(?: )?`)
-
-func ParseLogFilterParams(r *http.Request) (*model.LogsFilterParams, error) {
- res := model.LogsFilterParams{
- Limit: 30,
- OrderBy: "timestamp",
- Order: "desc",
- }
- var err error
- params := r.URL.Query()
- if val, ok := params["limit"]; ok {
- res.Limit, err = strconv.Atoi(val[0])
- if err != nil {
- return nil, err
- }
- }
- if val, ok := params[ORDER_BY]; ok {
- res.OrderBy = val[0]
- }
- if val, ok := params[ORDER]; ok {
- if val[0] == ASC || val[0] == DESC {
- res.Order = val[0]
- }
- }
- if val, ok := params["q"]; ok {
- res.Query = val[0]
- }
- if val, ok := params[TIMESTAMP_START]; ok {
- ts, err := strconv.Atoi(val[0])
- if err != nil {
- return nil, err
- }
- res.TimestampStart = uint64(ts)
- }
- if val, ok := params[TIMESTAMP_END]; ok {
- ts, err := strconv.Atoi(val[0])
- if err != nil {
- return nil, err
- }
- res.TimestampEnd = uint64(ts)
- }
- if val, ok := params[IdGt]; ok {
- res.IdGt = val[0]
- }
- if val, ok := params[IdLT]; ok {
- res.IdLT = val[0]
- }
- return &res, nil
-}
-
-func ParseLiveTailFilterParams(r *http.Request) (*model.LogsFilterParams, error) {
- res := model.LogsFilterParams{}
- params := r.URL.Query()
- if val, ok := params["q"]; ok {
- res.Query = val[0]
- }
- if val, ok := params[TIMESTAMP_START]; ok {
- ts, err := strconv.Atoi(val[0])
- if err != nil {
- return nil, err
- }
- res.TimestampStart = uint64(ts)
- }
- if val, ok := params[IdGt]; ok {
- res.IdGt = val[0]
- }
- return &res, nil
-}
-
-func ParseLogAggregateParams(r *http.Request) (*model.LogsAggregateParams, error) {
- res := model.LogsAggregateParams{}
- params := r.URL.Query()
- if val, ok := params[TIMESTAMP_START]; ok {
- ts, err := strconv.Atoi(val[0])
- if err != nil {
- return nil, err
- }
- res.TimestampStart = uint64(ts)
- } else {
- return nil, fmt.Errorf("timestampStart is required")
- }
- if val, ok := params[TIMESTAMP_END]; ok {
- ts, err := strconv.Atoi(val[0])
- if err != nil {
- return nil, err
- }
- res.TimestampEnd = uint64(ts)
- } else {
- return nil, fmt.Errorf("timestampEnd is required")
- }
-
- if val, ok := params["q"]; ok {
- res.Query = val[0]
- }
-
- if val, ok := params["groupBy"]; ok {
- res.GroupBy = val[0]
- }
-
- if val, ok := params["function"]; ok {
- res.Function = val[0]
- }
-
- if val, ok := params["step"]; ok {
- step, err := strconv.Atoi(val[0])
- if err != nil {
- return nil, err
- }
- res.StepSeconds = step
- } else {
- return nil, fmt.Errorf("step is required")
- }
- return &res, nil
-}
-
-func parseLogQuery(query string) ([]string, error) {
- sqlQueryTokens := []string{}
-
- filterTokens := tokenRegex.FindAllString(query, -1)
-
- if len(filterTokens) == 0 {
- sqlQueryTokens = append(sqlQueryTokens, fmt.Sprintf("body ILIKE '%%%s%%' ", query))
- return sqlQueryTokens, nil
- }
-
- // replace and check if there is something that is lying around
- if len(strings.TrimSpace(tokenRegex.ReplaceAllString(query, ""))) > 0 {
- return nil, fmt.Errorf("failed to parse query, contains unknown tokens")
- }
-
- for _, v := range filterTokens {
- op := strings.TrimSpace(operatorRegex.FindString(v))
- opLower := strings.ToLower(op)
-
- if opLower == "contains" || opLower == "ncontains" {
- searchString := strings.TrimSpace(strings.Split(v, op)[1])
-
- operatorRemovedTokens := strings.Split(operatorRegex.ReplaceAllString(v, " "), " ")
- searchCol := operatorRemovedTokens[0]
- if strings.ToLower(searchCol) == AND || strings.ToLower(searchCol) == OR {
- searchCol = operatorRemovedTokens[1]
- }
- col := searchCol
- if strings.ToLower(searchCol) == "fulltext" {
- col = "body"
- }
-
- f := fmt.Sprintf(`%s %s '%%%s%%' `, col, operatorMapping[opLower], searchString[1:len(searchString)-1])
- if strings.HasPrefix(strings.ToLower(v), AND) {
- f = "AND " + f
- } else if strings.HasPrefix(strings.ToLower(v), OR) {
- f = "OR " + f
- }
- sqlQueryTokens = append(sqlQueryTokens, f)
- } else {
- symbol := operatorMapping[strings.ToLower(op)]
- if symbol != "" {
- sqlExpr := strings.Replace(v, " "+op+" ", " "+symbol+" ", 1)
- splittedExpr := strings.Split(sqlExpr, symbol)
- if len(splittedExpr) != 2 {
- return nil, fmt.Errorf("error while splitting expression: %s", sqlExpr)
- }
- trimmedSqlExpr := fmt.Sprintf("%s %s %s ", strings.Join(strings.Fields(splittedExpr[0]), " "), symbol, strings.TrimSpace(splittedExpr[1]))
- sqlQueryTokens = append(sqlQueryTokens, trimmedSqlExpr)
- } else {
- // for exists|nexists don't process it here since we don't have metadata
- sqlQueryTokens = append(sqlQueryTokens, v)
- }
- }
- }
-
- return sqlQueryTokens, nil
-}
-
-func parseColumn(s string) (*string, error) {
- colName := ""
-
- // if has and/or as prefix
- filter := strings.Split(s, " ")
-
- first := strings.ToLower(filter[0])
- if first == AND || first == OR {
- colName = filter[1]
- } else {
- colName = filter[0]
- }
-
- return &colName, nil
-}
-
-func arrayToMap(fields []model.Field) map[string]model.Field {
- res := map[string]model.Field{}
- for _, field := range fields {
- res[field.Name] = field
- }
- return res
-}
-
-func replaceInterestingFields(allFields *model.GetFieldsResponse, queryTokens []string) ([]string, error) {
- // check if cols
- selectedFieldsLookup := arrayToMap(allFields.Selected)
- interestingFieldLookup := arrayToMap(allFields.Interesting)
-
- for index := 0; index < len(queryTokens); index++ {
- result, err := replaceFieldInToken(queryTokens[index], selectedFieldsLookup, interestingFieldLookup)
- if err != nil {
- return nil, err
- }
- queryTokens[index] = result
- }
- return queryTokens, nil
-}
-
-func replaceFieldInToken(queryToken string, selectedFieldsLookup map[string]model.Field, interestingFieldLookup map[string]model.Field) (string, error) {
- op := strings.TrimSpace(operatorRegex.FindString(queryToken))
- opLower := strings.ToLower(op)
-
- col, err := parseColumn(queryToken)
- if err != nil {
- return "", err
- }
-
- sqlColName := *col
- lowerColName := strings.ToLower(*col)
-
- if opLower == "exists" || opLower == "nexists" {
- var result string
-
- // handle static fields which are columns, timestamp and id is not required but added them regardless
- defaultValue := ""
- if lowerColName == "trace_id" || lowerColName == "span_id" || lowerColName == "severity_text" || lowerColName == "id" {
- defaultValue = "''"
- }
- if lowerColName == "trace_flags" || lowerColName == "severity_number" || lowerColName == "timestamp" {
- defaultValue = "0"
- }
-
- if defaultValue != "" {
- if opLower == "exists" {
- result = fmt.Sprintf("%s != %s", sqlColName, defaultValue)
- } else {
- result = fmt.Sprintf("%s = %s", sqlColName, defaultValue)
- }
- } else {
- // creating the query token here as we have the metadata
- field := model.Field{}
-
- if sfield, ok := selectedFieldsLookup[sqlColName]; ok {
- field = sfield
- } else if ifield, ok := interestingFieldLookup[sqlColName]; ok {
- field = ifield
- }
- result = fmt.Sprintf("has(%s_%s_key, '%s')", field.Type, strings.ToLower(field.DataType), field.Name)
- if opLower == "nexists" {
- result = "NOT " + result
- }
- }
- return strings.Replace(queryToken, sqlColName+" "+op, result, 1), nil
- }
-
- if lowerColName != "body" {
- if _, ok := selectedFieldsLookup[sqlColName]; !ok {
- if field, ok := interestingFieldLookup[sqlColName]; ok {
- if field.Type != constants.Static {
- sqlColName = fmt.Sprintf("%s_%s_value[indexOf(%s_%s_key, '%s')]", field.Type, strings.ToLower(field.DataType), field.Type, strings.ToLower(field.DataType), field.Name)
- }
- } else if strings.Compare(strings.ToLower(*col), "fulltext") != 0 && field.Type != constants.Static {
- return "", fmt.Errorf("field not found for filtering")
- }
- } else {
- field := selectedFieldsLookup[sqlColName]
- if field.Type != constants.Static {
- sqlColName = utils.GetClickhouseColumnName(field.Type, field.DataType, field.Name)
- }
- }
- }
- return strings.Replace(queryToken, *col, sqlColName, 1), nil
-}
-
-func CheckIfPrevousPaginateAndModifyOrder(params *model.LogsFilterParams) (isPaginatePrevious bool) {
- if params.IdGt != "" && params.OrderBy == TIMESTAMP && params.Order == DESC {
- isPaginatePrevious = true
- params.Order = ASC
- } else if params.IdLT != "" && params.OrderBy == TIMESTAMP && params.Order == ASC {
- isPaginatePrevious = true
- params.Order = DESC
- }
- return
-}
-
-func GenerateSQLWhere(allFields *model.GetFieldsResponse, params *model.LogsFilterParams) (string, int, error) {
- var tokens []string
- var err error
- var sqlWhere string
- var lenTokens = 0
- if params.Query != "" {
- tokens, err = parseLogQuery(params.Query)
-
- if err != nil {
- return sqlWhere, -1, err
- }
- lenTokens = len(tokens)
- }
-
- tokens, err = replaceInterestingFields(allFields, tokens)
- if err != nil {
- return sqlWhere, -1, err
- }
-
- filterTokens := []string{}
- if params.TimestampStart != 0 {
- filter := fmt.Sprintf("timestamp >= '%d' ", params.TimestampStart)
- if len(filterTokens) > 0 {
- filter = "and " + filter
- }
- filterTokens = append(filterTokens, filter)
- }
- if params.TimestampEnd != 0 {
- filter := fmt.Sprintf("timestamp <= '%d' ", params.TimestampEnd)
- if len(filterTokens) > 0 {
- filter = "and " + filter
- }
- filterTokens = append(filterTokens, filter)
- }
- if params.IdGt != "" {
- filter := fmt.Sprintf("id > '%v' ", params.IdGt)
- if len(filterTokens) > 0 {
- filter = "and " + filter
- }
- filterTokens = append(filterTokens, filter)
- }
- if params.IdLT != "" {
- filter := fmt.Sprintf("id < '%v' ", params.IdLT)
- if len(filterTokens) > 0 {
- filter = "and " + filter
- }
- filterTokens = append(filterTokens, filter)
- }
-
- lenFilterTokens := len(filterTokens)
- if lenFilterTokens > 0 {
- // add parenthesis
- filterTokens[0] = fmt.Sprintf("( %s", filterTokens[0])
- filterTokens[lenFilterTokens-1] = fmt.Sprintf("%s) ", filterTokens[lenFilterTokens-1])
-
- lenTokens := len(tokens)
- if lenTokens > 0 {
- tokens[0] = fmt.Sprintf("and ( %s", tokens[0])
- tokens[lenTokens-1] = fmt.Sprintf("%s) ", tokens[lenTokens-1])
- }
- filterTokens = append(filterTokens, tokens...)
- tokens = filterTokens
- }
-
- sqlWhere = strings.Join(tokens, "")
-
- return sqlWhere, lenTokens, nil
-}
diff --git a/pkg/query-service/app/logs/parser_test.go b/pkg/query-service/app/logs/parser_test.go
deleted file mode 100644
index 860980c5c8..0000000000
--- a/pkg/query-service/app/logs/parser_test.go
+++ /dev/null
@@ -1,484 +0,0 @@
-package logs
-
-import (
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/SigNoz/signoz/pkg/query-service/model"
- . "github.com/smartystreets/goconvey/convey"
-)
-
-var correctQueriesTest = []struct {
- Name string
- InputQuery string
- WantSqlTokens []string
-}{
- {
- `filter with fulltext`,
- `OPERATION in ('bcd') AND FULLTEXT contains 'searchstring'`,
- []string{`OPERATION IN ('bcd') `, `AND body ILIKE '%searchstring%' `},
- },
- {
- `fulltext`,
- `searchstring`,
- []string{`body ILIKE '%searchstring%' `},
- },
- {
- `fulltext with quotes and space`,
- `FULLTEXT contains 'Hello, "World"'`,
- []string{`body ILIKE '%Hello, "World"%' `},
- },
- {
- `contains search with a different attributes`,
- `resource contains 'Hello, "World" and user\'s'`,
- []string{`resource ILIKE '%Hello, "World" and user\'s%' `},
- },
- {
- `more than one continas`,
- `resource contains 'Hello, "World"' and myresource contains 'abcd'`,
- []string{`resource ILIKE '%Hello, "World"%' `, `AND myresource ILIKE '%abcd%' `},
- },
- {
- "contains with or",
- `id in ('2CkBCauK8m3nkyKR19YhCw6WbdY') or fulltext contains 'OPTIONS /api/v1/logs'`,
- []string{`id IN ('2CkBCauK8m3nkyKR19YhCw6WbdY') `, `OR body ILIKE '%OPTIONS /api/v1/logs%' `},
- },
- {
- "mixing and or",
- `id in ('2CkBCauK8m3nkyKR19YhCw6WbdY') and id in ('2CkBCauK8m3nkyKR19YhCw6WbdY','2CkBCauK8m3nkyKR19YhCw6WbdY') or fulltext contains 'OPTIONS /api/v1/logs'`,
- []string{`id IN ('2CkBCauK8m3nkyKR19YhCw6WbdY') `, `and id IN ('2CkBCauK8m3nkyKR19YhCw6WbdY','2CkBCauK8m3nkyKR19YhCw6WbdY') `, `OR body ILIKE '%OPTIONS /api/v1/logs%' `},
- },
- {
- `filters with lt,gt,lte,gte operators`,
- `id lt 100 and id gt 50 and code lte 500 and code gte 400`,
- []string{`id < 100 `, `and id > 50 `, `and code <= 500 `, `and code >= 400 `},
- },
- {
- `filters with lt,gt,lte,gte operators seprated by OR`,
- `id lt 100 or id gt 50 or code lte 500 or code gte 400`,
- []string{`id < 100 `, `or id > 50 `, `or code <= 500 `, `or code >= 400 `},
- },
- {
- `filter with number`,
- `status gte 200 AND FULLTEXT ncontains '"key"'`,
- []string{`status >= 200 `, `AND body NOT ILIKE '%"key"%' `},
- },
- {
- `characters inside string`,
- `service NIN ('name > 100') AND length gt 100`,
- []string{`service NOT IN ('name > 100') `, `AND length > 100 `},
- },
- {
- `fulltext with in`,
- `key in 2`,
- []string{`body ILIKE '%key in 2%' `},
- },
- {
- `not valid fulltext but a filter`,
- `key in (2,3)`,
- []string{`key IN (2,3) `},
- },
- {
- `filters with extra spaces`,
- `service IN ('name > 100') AND length gt 100`,
- []string{`service IN ('name > 100') `, `AND length > 100 `},
- },
- {
- `Extra space within a filter expression`,
- `service IN ('name > 100')`,
- []string{`service IN ('name > 100') `},
- },
- {
- `Extra space between a query filter`,
- `data contains 'hello world .'`,
- []string{`data ILIKE '%hello world .%' `},
- },
- {
- `filters with special characters in key name`,
- `id.userid in (100) and id_userid gt 50`,
- []string{`id.userid IN (100) `, `and id_userid > 50 `},
- },
- {
- `filters with case sensitive key name`,
- `userIdentifier in ('user') and userIdentifier contains 'user'`,
- []string{`userIdentifier IN ('user') `, `AND userIdentifier ILIKE '%user%' `},
- },
- {
- `filters with for exists`,
- `userIdentifier exists and user nexists`,
- []string{`userIdentifier exists `, `and user nexists`},
- },
-}
-
-func TestParseLogQueryCorrect(t *testing.T) {
- for _, test := range correctQueriesTest {
- Convey(test.Name, t, func() {
- query, err := parseLogQuery(test.InputQuery)
- So(err, ShouldBeNil)
- So(query, ShouldResemble, test.WantSqlTokens)
- })
- }
-}
-
-var incorrectQueries = []struct {
- Name string
- Query string
-}{
- {
- "filter without a key",
- "OPERATION in ('bcd') AND 'abcd' FULLTEXT contains 'helloxyz'",
- },
- {
- "fulltext without fulltext keyword",
- "OPERATION in ('bcd') AND 'searchstring'",
- },
- {
- "fulltext in the beginning without keyword",
- "'searchstring and OPERATION in ('bcd')",
- },
-}
-
-func TestParseLogQueryInCorrect(t *testing.T) {
- for _, test := range incorrectQueries {
- Convey(test.Name, t, func() {
- _, err := parseLogQuery(test.Query)
- So(err, ShouldBeError)
- })
- }
-}
-
-var parseCorrectColumns = []struct {
- Name string
- Filter string
- Column string
-}{
- {
- "column with IN operator",
- "id.userid IN (100) ",
- "id.userid",
- },
- {
- "column with NOT IN operator",
- "service NOT IN ('name > 100') ",
- "service",
- },
- {
- "column with > operator",
- "and id_userid > 50 ",
- "id_userid",
- },
- {
- "column with < operator",
- "and id_userid < 50 ",
- "id_userid",
- },
- {
- "column with <= operator",
- "and id_userid <= 50 ",
- "id_userid",
- },
- {
- "column with >= operator",
- "and id_userid >= 50 ",
- "id_userid",
- },
- {
- "column starting with and",
- "andor = 1",
- "andor",
- },
- {
- "column starting with and after an 'and'",
- "and andor = 1",
- "andor",
- },
- {
- "column starting with And",
- "Andor = 1",
- "Andor",
- },
- {
- "column starting with and after an 'and'",
- "and Andor = 1",
- "Andor",
- },
- {
- "column with ilike",
- `AND body ILIKE '%searchstring%' `,
- "body",
- },
- {
- "column with not ilike",
- `AND body ILIKE '%searchstring%' `,
- "body",
- },
- {
- "column with exists",
- `AND user exists`,
- "user",
- },
- {
- "column with nexists",
- `AND user nexists `,
- "user",
- },
-}
-
-func TestParseColumn(t *testing.T) {
- for _, test := range parseCorrectColumns {
- Convey(test.Name, t, func() {
- column, err := parseColumn(test.Filter)
- So(err, ShouldBeNil)
- So(*column, ShouldEqual, test.Column)
- })
- }
-}
-
-func TestReplaceInterestingFields(t *testing.T) {
- queryTokens := []string{"id.userid IN (100) ", "and id_key >= 50 ", `AND body ILIKE '%searchstring%'`}
- allFields := model.GetFieldsResponse{
- Selected: []model.Field{
- {
- Name: "id_key",
- DataType: "int64",
- Type: "attributes",
- },
- },
- Interesting: []model.Field{
- {
- Name: "id.userid",
- DataType: "int64",
- Type: "attributes",
- },
- },
- }
-
- expectedTokens := []string{"attributes_int64_value[indexOf(attributes_int64_key, 'id.userid')] IN (100) ", "and `attribute_int64_id_key` >= 50 ", `AND body ILIKE '%searchstring%'`}
- Convey("testInterestingFields", t, func() {
- tokens, err := replaceInterestingFields(&allFields, queryTokens)
- So(err, ShouldBeNil)
- So(tokens, ShouldResemble, expectedTokens)
- })
-}
-
-var previousPaginateTestCases = []struct {
- Name string
- Filter model.LogsFilterParams
- IsPaginatePrev bool
- Order string
-}{
- {
- Name: "empty",
- Filter: model.LogsFilterParams{},
- IsPaginatePrev: false,
- },
- {
- Name: "next ordery by asc",
- Filter: model.LogsFilterParams{
- OrderBy: TIMESTAMP,
- Order: ASC,
- IdGt: "myid",
- },
- IsPaginatePrev: false,
- Order: ASC,
- },
- {
- Name: "next ordery by desc",
- Filter: model.LogsFilterParams{
- OrderBy: TIMESTAMP,
- Order: DESC,
- IdLT: "myid",
- },
- IsPaginatePrev: false,
- Order: DESC,
- },
- {
- Name: "prev ordery by desc",
- Filter: model.LogsFilterParams{
- OrderBy: TIMESTAMP,
- Order: DESC,
- IdGt: "myid",
- },
- IsPaginatePrev: true,
- Order: ASC,
- },
- {
- Name: "prev ordery by asc",
- Filter: model.LogsFilterParams{
- OrderBy: TIMESTAMP,
- Order: ASC,
- IdLT: "myid",
- },
- IsPaginatePrev: true,
- Order: DESC,
- },
-}
-
-func TestCheckIfPrevousPaginateAndModifyOrder(t *testing.T) {
- for _, test := range previousPaginateTestCases {
- Convey(test.Name, t, func() {
- isPrevPaginate := CheckIfPrevousPaginateAndModifyOrder(&test.Filter)
- So(isPrevPaginate, ShouldEqual, test.IsPaginatePrev)
- So(test.Order, ShouldEqual, test.Filter.Order)
- })
- }
-}
-
-var generateSQLQueryFields = model.GetFieldsResponse{
- Selected: []model.Field{
- {
- Name: "field1",
- DataType: "int64",
- Type: "attributes",
- },
- {
- Name: "Field2",
- DataType: "double64",
- Type: "attributes",
- },
- {
- Name: "field2",
- DataType: "string",
- Type: "attributes",
- },
- {
- Name: "severity_number",
- DataType: "string",
- Type: "static",
- },
- },
- Interesting: []model.Field{
- {
- Name: "FielD1",
- DataType: "int64",
- Type: "attributes",
- },
- {
- Name: "code",
- DataType: "int64",
- Type: "attributes",
- },
- },
-}
-
-var generateSQLQueryTestCases = []struct {
- Name string
- Filter model.LogsFilterParams
- SqlFilter string
-}{
- {
- Name: "first query with more than 1 compulsory filters",
- Filter: model.LogsFilterParams{
- Query: "field1 lt 100 and field1 gt 50 and code lte 500 and code gte 400",
- TimestampStart: uint64(1657689292000),
- TimestampEnd: uint64(1657689294000),
- IdGt: "2BsKLKv8cZrLCn6rkOcRGkdjBdM",
- IdLT: "2BsKG6tRpFWjYMcWsAGKfSxoQdU",
- },
- SqlFilter: "( timestamp >= '1657689292000' and timestamp <= '1657689294000' and id > '2BsKLKv8cZrLCn6rkOcRGkdjBdM' and id < '2BsKG6tRpFWjYMcWsAGKfSxoQdU' ) and ( `attribute_int64_field1` < 100 and `attribute_int64_field1` > 50 and attributes_int64_value[indexOf(attributes_int64_key, 'code')] <= 500 and attributes_int64_value[indexOf(attributes_int64_key, 'code')] >= 400 ) ",
- },
- {
- Name: "second query with only timestamp range",
- Filter: model.LogsFilterParams{
- Query: "field1 lt 100 and field1 gt 50 and code lte 500 and code gte 400",
- TimestampStart: uint64(1657689292000),
- TimestampEnd: uint64(1657689294000),
- },
- SqlFilter: "( timestamp >= '1657689292000' and timestamp <= '1657689294000' ) and ( `attribute_int64_field1` < 100 and `attribute_int64_field1` > 50 and attributes_int64_value[indexOf(attributes_int64_key, 'code')] <= 500 and attributes_int64_value[indexOf(attributes_int64_key, 'code')] >= 400 ) ",
- },
- {
- Name: "generate case sensitive query",
- Filter: model.LogsFilterParams{
- Query: "field1 lt 100 and FielD1 gt 50 and Field2 gt 10 and code lte 500 and code gte 400",
- TimestampStart: uint64(1657689292000),
- TimestampEnd: uint64(1657689294000),
- },
- SqlFilter: "( timestamp >= '1657689292000' and timestamp <= '1657689294000' ) and ( `attribute_int64_field1` < 100 and attributes_int64_value[indexOf(attributes_int64_key, 'FielD1')] > 50 and `attribute_double64_Field2` > 10 and attributes_int64_value[indexOf(attributes_int64_key, 'code')] <= 500 and attributes_int64_value[indexOf(attributes_int64_key, 'code')] >= 400 ) ",
- },
- {
- Name: "Check exists and not exists",
- Filter: model.LogsFilterParams{
- Query: "field1 exists and Field2 nexists and Field2 gt 10",
- TimestampStart: uint64(1657689292000),
- TimestampEnd: uint64(1657689294000),
- },
- SqlFilter: "( timestamp >= '1657689292000' and timestamp <= '1657689294000' ) and ( has(attributes_int64_key, 'field1') and NOT has(attributes_double64_key, 'Field2') and `attribute_double64_Field2` > 10 ) ",
- },
- {
- Name: "Check top level key filter",
- Filter: model.LogsFilterParams{
- Query: "severity_number in (1)",
- TimestampStart: uint64(1657689292000),
- TimestampEnd: uint64(1657689294000),
- },
- SqlFilter: "( timestamp >= '1657689292000' and timestamp <= '1657689294000' ) and ( severity_number IN (1) ) ",
- },
- {
- Name: "Check exists and not exists on top level keys",
- Filter: model.LogsFilterParams{
- Query: "trace_id exists and span_id nexists and trace_flags exists and severity_number nexists",
- TimestampStart: uint64(1657689292000),
- TimestampEnd: uint64(1657689294000),
- },
- SqlFilter: "( timestamp >= '1657689292000' and timestamp <= '1657689294000' ) and ( trace_id != '' and span_id = '' and trace_flags != 0 and severity_number = 0) ",
- },
-}
-
-func TestGenerateSQLQuery(t *testing.T) {
- for _, test := range generateSQLQueryTestCases {
- Convey("testGenerateSQL", t, func() {
- res, _, err := GenerateSQLWhere(&generateSQLQueryFields, &test.Filter)
- So(err, ShouldBeNil)
- So(res, ShouldEqual, test.SqlFilter)
- })
- }
-}
-
-var parseLogFilterParams = []struct {
- Name string
- ReqParams string
- ExpectedLogFilterParams *model.LogsFilterParams
-}{
- {
- Name: "test with proper order by",
- ReqParams: "order=desc&q=service.name='myservice'&limit=10",
- ExpectedLogFilterParams: &model.LogsFilterParams{
- Limit: 10,
- OrderBy: "timestamp",
- Order: DESC,
- Query: "service.name='myservice'",
- },
- },
- {
- Name: "test with proper order by asc",
- ReqParams: "order=asc&q=service.name='myservice'&limit=10",
- ExpectedLogFilterParams: &model.LogsFilterParams{
- Limit: 10,
- OrderBy: "timestamp",
- Order: ASC,
- Query: "service.name='myservice'",
- },
- },
- {
- Name: "test with incorrect order by",
- ReqParams: "order=undefined&q=service.name='myservice'&limit=10",
- ExpectedLogFilterParams: &model.LogsFilterParams{
- Limit: 10,
- OrderBy: "timestamp",
- Order: DESC,
- Query: "service.name='myservice'",
- },
- },
-}
-
-func TestParseLogFilterParams(t *testing.T) {
- for _, test := range parseLogFilterParams {
- Convey(test.Name, t, func() {
- req := httptest.NewRequest(http.MethodGet, "/logs?"+test.ReqParams, nil)
- params, err := ParseLogFilterParams(req)
- So(err, ShouldBeNil)
- So(params, ShouldEqual, test.ExpectedLogFilterParams)
- })
- }
-}
diff --git a/pkg/query-service/app/logs/v3/enrich_query.go b/pkg/query-service/app/logs/v3/enrich_query.go
index 0ec2800ad9..34cb3131ba 100644
--- a/pkg/query-service/app/logs/v3/enrich_query.go
+++ b/pkg/query-service/app/logs/v3/enrich_query.go
@@ -81,6 +81,58 @@ func isEnriched(field v3.AttributeKey) bool {
return false
}
+// returns the name of all the fields from the query
+// this will be used to get the corresponding fields
+func GetFieldNames(compositeQuery *v3.CompositeQuery) []string {
+ fieldNames := make(map[string]struct{})
+ result := []string{}
+ if compositeQuery == nil {
+ return result
+ }
+
+ for queryName, query := range compositeQuery.BuilderQueries {
+ if query.Expression != queryName && query.DataSource != v3.DataSourceLogs {
+ continue
+ }
+
+ if query.AggregateAttribute.Key != "" {
+ fieldNames[query.AggregateAttribute.Key] = struct{}{}
+ }
+
+ // attribute
+ if query.Filters != nil && len(query.Filters.Items) != 0 {
+ for i := 0; i < len(query.Filters.Items); i++ {
+ tempItem := jsonFilterEnrich(query.Filters.Items[i])
+ if tempItem.Key.IsJSON {
+ key, found := strings.CutPrefix(tempItem.Key.Key, "body.")
+ if found {
+ fieldNames[key] = struct{}{}
+ }
+ } else {
+ fieldNames[query.Filters.Items[i].Key.Key] = struct{}{}
+ }
+ }
+ }
+
+ // groupby
+ for i := 0; i < len(query.GroupBy); i++ {
+ fieldNames[query.GroupBy[i].Key] = struct{}{}
+ }
+
+ // orderby
+ for i := 0; i < len(query.OrderBy); i++ {
+ fieldNames[query.OrderBy[i].ColumnName] = struct{}{}
+ }
+
+ }
+
+ for key := range fieldNames {
+ result = append(result, key)
+ }
+
+ return result
+}
+
func Enrich(params *v3.QueryRangeParamsV3, fields map[string]v3.AttributeKey) {
compositeQuery := params.CompositeQuery
if compositeQuery == nil {
diff --git a/pkg/query-service/app/logs/v3/enrich_query_test.go b/pkg/query-service/app/logs/v3/enrich_query_test.go
index 2cc11b281c..f73763e6b0 100644
--- a/pkg/query-service/app/logs/v3/enrich_query_test.go
+++ b/pkg/query-service/app/logs/v3/enrich_query_test.go
@@ -1,6 +1,8 @@
package v3
import (
+ "reflect"
+ "sort"
"testing"
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
@@ -808,3 +810,285 @@ func TestParseStrValue(t *testing.T) {
})
}
}
+
+func TestGetFieldNames(t *testing.T) {
+ type args struct {
+ compositeQuery *v3.CompositeQuery
+ }
+ tests := []struct {
+ name string
+ args args
+ want []string
+ }{
+ {
+ name: "nil composite query",
+ args: args{
+ compositeQuery: nil,
+ },
+ want: []string{},
+ },
+ {
+ name: "empty builder queries",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{},
+ },
+ },
+ want: []string{},
+ },
+ {
+ name: "aggregate attribute only",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{
+ "test": {
+ QueryName: "test",
+ Expression: "test",
+ DataSource: v3.DataSourceLogs,
+ AggregateAttribute: v3.AttributeKey{
+ Key: "response_time",
+ },
+ },
+ },
+ },
+ },
+ want: []string{"response_time"},
+ },
+ {
+ name: "filters only",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{
+ "test": {
+ QueryName: "test",
+ Expression: "test",
+ DataSource: v3.DataSourceLogs,
+ Filters: &v3.FilterSet{
+ Operator: "AND",
+ Items: []v3.FilterItem{
+ {Key: v3.AttributeKey{Key: "user_name"}, Value: "john", Operator: "="},
+ {Key: v3.AttributeKey{Key: "status"}, Value: "error", Operator: "!="},
+ },
+ },
+ },
+ },
+ },
+ },
+ want: []string{"user_name", "status"},
+ },
+ {
+ name: "JSON filters",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{
+ "test": {
+ QueryName: "test",
+ Expression: "test",
+ DataSource: v3.DataSourceLogs,
+ Filters: &v3.FilterSet{
+ Operator: "AND",
+ Items: []v3.FilterItem{
+ {Key: v3.AttributeKey{Key: "body.user_name"}, Value: "john", Operator: "="},
+ {Key: v3.AttributeKey{Key: "body.status.code"}, Value: 200, Operator: "="},
+ {Key: v3.AttributeKey{Key: "body.requestor_list[*]"}, Value: "index_service", Operator: "has"},
+ },
+ },
+ },
+ },
+ },
+ },
+ // requestor_list[*] is not required though
+ want: []string{"user_name", "status.code", "requestor_list[*]"},
+ },
+ {
+ name: "groupBy only",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{
+ "test": {
+ QueryName: "test",
+ Expression: "test",
+ DataSource: v3.DataSourceLogs,
+ GroupBy: []v3.AttributeKey{
+ {Key: "service_name"},
+ {Key: "host_name"},
+ },
+ },
+ },
+ },
+ },
+ want: []string{"service_name", "host_name"},
+ },
+ {
+ name: "orderBy only",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{
+ "test": {
+ QueryName: "test",
+ Expression: "test",
+ DataSource: v3.DataSourceLogs,
+ OrderBy: []v3.OrderBy{
+ {ColumnName: "timestamp", Order: "DESC"},
+ {ColumnName: "response_time", Order: "ASC"},
+ },
+ },
+ },
+ },
+ },
+ want: []string{"timestamp", "response_time"},
+ },
+ {
+ name: "all field types combined",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{
+ "test": {
+ QueryName: "test",
+ Expression: "test",
+ DataSource: v3.DataSourceLogs,
+ AggregateAttribute: v3.AttributeKey{
+ Key: "response_time",
+ },
+ Filters: &v3.FilterSet{
+ Operator: "AND",
+ Items: []v3.FilterItem{
+ {Key: v3.AttributeKey{Key: "user_name"}, Value: "john", Operator: "="},
+ {Key: v3.AttributeKey{Key: "body.status"}, Value: "error", Operator: "!="},
+ },
+ },
+ GroupBy: []v3.AttributeKey{
+ {Key: "service_name"},
+ {Key: "user_name"},
+ },
+ OrderBy: []v3.OrderBy{
+ {ColumnName: "timestamp", Order: "DESC"},
+ },
+ },
+ },
+ },
+ },
+ want: []string{"response_time", "user_name", "status", "service_name", "timestamp"},
+ },
+ {
+ name: "multiple builder queries",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{
+ "query1": {
+ QueryName: "query1",
+ Expression: "query1",
+ DataSource: v3.DataSourceLogs,
+ AggregateAttribute: v3.AttributeKey{
+ Key: "field1",
+ },
+ },
+ "query2": {
+ QueryName: "query2",
+ Expression: "query2",
+ DataSource: v3.DataSourceLogs,
+ Filters: &v3.FilterSet{
+ Operator: "AND",
+ Items: []v3.FilterItem{
+ {Key: v3.AttributeKey{Key: "field2"}, Value: "value", Operator: "="},
+ },
+ },
+ },
+ "query3": {
+ QueryName: "query3",
+ Expression: "different_expression",
+ DataSource: v3.DataSourceLogs,
+ AggregateAttribute: v3.AttributeKey{
+ Key: "field3",
+ },
+ },
+ },
+ },
+ },
+ want: []string{"field1", "field2", "field3"},
+ },
+ {
+ name: "empty aggregate attribute key and filters",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{
+ "test": {
+ QueryName: "test",
+ Expression: "test",
+ DataSource: v3.DataSourceLogs,
+ AggregateAttribute: v3.AttributeKey{
+ Key: "",
+ },
+ Filters: &v3.FilterSet{
+ Operator: "AND",
+ Items: []v3.FilterItem{
+ {Key: v3.AttributeKey{Key: "user_name"}, Value: "john", Operator: "="},
+ },
+ },
+ GroupBy: []v3.AttributeKey{
+ {Key: "service_name"},
+ },
+ },
+ },
+ },
+ },
+ want: []string{"user_name", "service_name"},
+ },
+ {
+ name: "JSON filter with array suffix - no use",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{
+ "test": {
+ QueryName: "test",
+ Expression: "test",
+ DataSource: v3.DataSourceLogs,
+ Filters: &v3.FilterSet{
+ Operator: "AND",
+ Items: []v3.FilterItem{
+ {Key: v3.AttributeKey{Key: "body.tags[*]"}, Value: "important", Operator: "has"},
+ {Key: v3.AttributeKey{Key: "body.nested.array[*]"}, Value: "value", Operator: "has"},
+ },
+ },
+ },
+ },
+ },
+ },
+ want: []string{"tags[*]", "nested.array[*]"},
+ },
+ {
+ name: "mixed JSON and regular filters",
+ args: args{
+ compositeQuery: &v3.CompositeQuery{
+ BuilderQueries: map[string]*v3.BuilderQuery{
+ "test": {
+ QueryName: "test",
+ Expression: "test",
+ DataSource: v3.DataSourceLogs,
+ Filters: &v3.FilterSet{
+ Operator: "AND",
+ Items: []v3.FilterItem{
+ {Key: v3.AttributeKey{Key: "user_name"}, Value: "john", Operator: "="},
+ {Key: v3.AttributeKey{Key: "body.status.abc"}, Value: "error", Operator: "!="},
+ {Key: v3.AttributeKey{Key: "service_name"}, Value: "api", Operator: "="},
+ },
+ },
+ },
+ },
+ },
+ },
+ want: []string{"user_name", "status.abc", "service_name"},
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := GetFieldNames(tt.args.compositeQuery)
+ // Sort both slices since order doesn't matter
+ sort.Strings(got)
+ sort.Strings(tt.want)
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("GetFieldNames() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/pkg/query-service/interfaces/interface.go b/pkg/query-service/interfaces/interface.go
index 7a5ae50072..1a44504157 100644
--- a/pkg/query-service/interfaces/interface.go
+++ b/pkg/query-service/interfaces/interface.go
@@ -75,10 +75,8 @@ type Reader interface {
GetDistributedInfoInLastHeartBeatInterval(ctx context.Context) (map[string]interface{}, error)
// Logs
GetLogFields(ctx context.Context) (*model.GetFieldsResponse, *model.ApiError)
+ GetLogFieldsFromNames(ctx context.Context, fieldNames []string) (*model.GetFieldsResponse, *model.ApiError)
UpdateLogField(ctx context.Context, field *model.UpdateField) *model.ApiError
- GetLogs(ctx context.Context, params *model.LogsFilterParams) (*[]model.SignozLog, *model.ApiError)
- TailLogs(ctx context.Context, client *model.LogsTailClient)
- AggregateLogs(ctx context.Context, params *model.LogsAggregateParams) (*model.GetLogsAggregatesResponse, *model.ApiError)
GetLogAttributeKeys(ctx context.Context, req *v3.FilterAttributeKeyRequest) (*v3.FilterAttributeKeyResponse, error)
GetLogAttributeValues(ctx context.Context, req *v3.FilterAttributeValueRequest) (*v3.FilterAttributeValueResponse, error)
GetLogAggregateAttributes(ctx context.Context, req *v3.AggregateAttributeRequest) (*v3.AggregateAttributeResponse, error)