github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/pkg/virtualtable/mappings.go (about) 1 /* 2 Copyright 2023. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package virtualtable 18 19 import ( 20 "encoding/json" 21 "strings" 22 23 log "github.com/sirupsen/logrus" 24 25 "github.com/siglens/siglens/pkg/config" 26 "github.com/siglens/siglens/pkg/utils" 27 ) 28 29 func createMappingFromEvent(incomingBody *string, indexName *string) (error, string) { 30 jsonSource := make(map[string]interface{}) 31 decoder := json.NewDecoder(strings.NewReader(*incomingBody)) 32 decoder.UseNumber() 33 err := decoder.Decode(&jsonSource) 34 indexToMapping := make(map[string]interface{}) 35 m := make(map[string]interface{}) 36 if err != nil { 37 log.Errorf("createMappingFromEvent: failed to decode json event, err=%v", err) 38 return err, "" 39 } 40 flat_json := utils.Flatten(jsonSource) 41 for key, val := range flat_json { 42 43 if val == nil { 44 continue 45 } 46 47 switch val := val.(type) { 48 case string: 49 if val == config.GetTimeStampKey() { 50 m[key] = map[string]interface{}{ 51 "type": "date"} 52 } else { 53 m[key] = map[string]interface{}{ 54 "type": "string"} 55 } 56 57 case json.Number: 58 m[key] = map[string]interface{}{ 59 "type": "number"} 60 61 case bool: 62 m[key] = map[string]interface{}{ 63 "type": "bool"} 64 65 default: 66 log.Errorf("createMappingFromEvent: dont know how to convert type=%T for colName=%v", val, key) 67 } 68 } 69 indexToMapping[*indexName] = map[string]interface{}{ 70 "mappings": m} 71 JsonBody, err := json.Marshal(indexToMapping) 72 if err != nil { 73 log.Errorf("createMappingFromEvent: cannot Marshal the data, err=%v", err) 74 return err, "" 75 } 76 return nil, string(JsonBody) 77 } 78 79 func AddMappingFromADoc(indexName *string, incomingBody *string, orgid uint64) error { 80 err, jsonBody := createMappingFromEvent(incomingBody, indexName) 81 if err != nil { 82 log.Errorf("AddMappingFromADoc: cannot create mapping from the event with indexName=%v, err=%v", indexName, err) 83 return err 84 } 85 return AddMapping(indexName, &jsonBody, orgid) 86 }