-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapping.go
264 lines (243 loc) · 7.22 KB
/
mapping.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package elasticorm
import (
"fmt"
"reflect"
"strings"
"github.com/pkg/errors"
)
// MappingConfig is a struct which marshals to a valid elasticsearch mapping configuration
type MappingConfig struct {
Properties map[string]MappingFieldConfig `json:"properties,omitempty"`
}
func (m *MappingConfig) Analyzers() []string {
list := make(map[string]bool, 0)
for _, pm := range m.Properties {
addAnalyzers(list, pm)
}
analyzers := make([]string, 0)
for name, _ := range list {
analyzers = append(analyzers, name)
}
return analyzers
}
func addAnalyzers(res map[string]bool, mapping MappingFieldConfig) {
if mapping.Analyzer != "" {
res[mapping.Analyzer] = true
}
for _, m := range mapping.Properties {
addAnalyzers(res, m)
}
}
// AddField adds a new field to the mapping
func (m *MappingConfig) AddField(name string, cfg MappingFieldConfig) {
if m.Properties == nil {
m.Properties = make(map[string]MappingFieldConfig)
}
m.Properties[name] = cfg
}
func (m MappingConfig) elasticFieldName(structFieldName string) (string, error) {
return elasticFieldNameFromMappingFieldConfigs(m.Properties, structFieldName)
}
func elasticFieldNameFromMappingFieldConfigs(fieldConfigs map[string]MappingFieldConfig, structFieldName string) (string, error) {
structFieldNameParts := strings.Split(structFieldName, `.`)
structFieldName = structFieldNameParts[0]
for propertyName, propertyMapping := range fieldConfigs {
if propertyMapping.structFieldName == structFieldName {
if len(structFieldNameParts) > 1 {
subStructFieldPath := strings.Join(structFieldNameParts[1:], `.`)
subElasticFieldPath, err := elasticFieldNameFromMappingFieldConfigs(propertyMapping.Properties, subStructFieldPath)
if err != nil {
return ``, err
}
propertyName = fmt.Sprintf("%s.%s", propertyName, subElasticFieldPath)
}
return propertyName, nil
}
}
return ``, errors.New(`Mapping configuration has no mapping for struct field`)
}
// MappingFieldConfig is a struct which represents the elasticsearch mapping configuration of one field. It is used in the MappingConfig.
type MappingFieldConfig struct {
Type string `json:"type"`
Analyzer string `json:"analyzer,omitempty"`
structFieldName string `json:"-"`
Properties map[string]MappingFieldConfig `json:"properties,omitempty"`
Fields map[string]MappingFieldConfig `json:"fields,omitempty"`
Similarity string `json:"similarity,omitempty"`
}
// MappingFromStruct returns the MappingConfig for a passed in struct (pointer). The mapping is configurable via json tags, which can change the name of the field, and elasticorm tags. The elasticorm tags can include
func MappingFromStruct(i interface{}) (MappingConfig, error) {
mapping := MappingConfig{}
var err error
v := reflect.ValueOf(i).Elem()
for n := 0; n < v.NumField(); n++ {
field := v.Type().Field(n)
if !shouldMapField(field) {
continue
}
fieldMapping, propErr := mappingForField(field)
if propErr != nil {
err = propErr
}
name := nameForField(field)
mapping.AddField(name, fieldMapping)
}
return mapping, err
}
func mappingForField(field reflect.StructField) (MappingFieldConfig, error) {
var err error
propMapping := MappingFieldConfig{
Type: typeForField(field),
structFieldName: field.Name,
}
propMapping.Properties, err = propertiesForField(field)
if err != nil {
return propMapping, err
}
if tag := field.Tag.Get(`elasticorm`); tag != `` {
options := optionsFromTag(tag)
for name, value := range options {
switch name {
case `type`:
propMapping.Type = value
case `analyzer`:
propMapping.Analyzer = value
case `sortable`:
propMapping.Fields = rawFieldForField(field)
case `id`:
case "ref_id":
propMapping.Type = "keyword"
if propMapping.Analyzer == "case_insensitive_ref_id" {
propMapping.Type = "text"
}
case `case_sensitive`:
if value != "true" && value != "false" {
return propMapping, errors.Wrap(ErrInvalidOption, "flag case_sensitive must be true or false")
}
if propMapping.Analyzer != "" && value == "false" {
return propMapping, errors.Wrap(ErrInvalidOption, fmt.Sprintf(
`trying to set case_sensitivity to false on \"%s\" while the analyzer is already set to \"%s\"`,
field.Name,
propMapping.Analyzer,
))
}
if value == "false" {
propMapping.Analyzer = "case_insensitive_ref_id"
if propMapping.Type == "keyword" {
propMapping.Type = "text"
}
}
default:
return propMapping, errors.Wrap(ErrInvalidOption, fmt.Sprintf("parsing option %s=%s failed", name, value))
}
}
}
return propMapping, err
}
func typeForField(f reflect.StructField) string {
if val, ok := optionValueForField(f, `type`); ok {
return val
}
return elasticTypeForGoType(f.Type)
}
func elasticTypeForGoType(t reflect.Type) string {
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.PkgPath() == `time` && t.Name() == `Time` {
return `date`
}
switch t.Kind() {
case reflect.Slice:
subtype := elasticTypeForGoType(t.Elem())
if subtype == `object` {
return `nested`
}
return subtype
case reflect.Struct:
return `object`
case reflect.Bool:
return `boolean`
case reflect.Float32:
return `float`
case reflect.Float64:
return `double`
case reflect.Int8:
return `byte`
case reflect.Int16:
return `short`
case reflect.Int32:
fallthrough
case reflect.Int:
return `integer`
case reflect.Int64:
return `long`
default:
return `text`
}
}
func optionValueForField(f reflect.StructField, name string) (string, bool) {
o := optionsForField(f)
v, ok := o[name]
return v, ok
}
func optionsForField(f reflect.StructField) map[string]string {
o := make(map[string]string, 2)
tag := f.Tag.Get(`elasticorm`)
if tag == `` {
return o
}
return optionsFromTag(tag)
}
func propertiesForField(f reflect.StructField) (map[string]MappingFieldConfig, error) {
t := f.Type
if t.Kind() == reflect.Ptr || t.Kind() == reflect.Slice {
t = t.Elem()
}
if typeForField(f) != `nested` && typeForField(f) != `object` {
return nil, nil
}
properties := make(map[string]MappingFieldConfig, t.NumField())
var err error
for n := 0; n < t.NumField(); n++ {
field := t.Field(n)
if shouldMapField(field) {
properties[nameForField(field)], err = mappingForField(field)
}
}
return properties, err
}
func rawFieldForField(f reflect.StructField) map[string]MappingFieldConfig {
cfg := make(map[string]MappingFieldConfig, 1)
cfg[`raw`] = MappingFieldConfig{
Type: `keyword`,
}
return cfg
}
func shouldMapField(f reflect.StructField) bool {
_, isId := optionValueForField(f, `id`)
return !(isId || f.Tag.Get(`json`) == `-`)
}
func optionsFromTag(tag string) map[string]string {
options := make(map[string]string, 2)
definitions := strings.Split(tag, `,`)
for _, definition := range definitions {
kv := strings.Split(definition, `=`)
if len(kv) > 1 {
options[kv[0]] = kv[1]
} else {
options[kv[0]] = "true"
}
}
return options
}
func nameForField(field reflect.StructField) string {
name := field.Name
if json := field.Tag.Get(`json`); json != `` {
if i := strings.Index(json, `,`); i > -1 {
json = json[:strings.Index(json, `,`)]
}
name = json
}
return name
}