/
mapping.go
67 lines (58 loc) · 1.68 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
package esutils
import (
"context"
"github.com/Jeffail/gabs/v2"
"github.com/olivere/elastic"
"github.com/pkg/errors"
)
// MappingPayload defines request payload for es index mapping
type MappingPayload struct {
Base
Fields []Field `json:"fields"`
}
// NewMapping return es mapping json string from mp
func NewMapping(mp MappingPayload) string {
var (
mapping *gabs.Container
properties *gabs.Container
)
mapping = gabs.New()
mapping.SetP("60s", "settings.refresh_interval")
mapping.SetP("1", "settings.number_of_replicas")
mapping.SetP("15", "settings.number_of_shards")
properties = gabs.New()
for _, f := range mp.Fields {
properties.Set(f.Type, f.Name, "type")
}
mapping.Set(properties, "mappings", mp.Type, "properties")
return mapping.String()
}
// PutMapping updates mapping
func (es *Es) PutMapping(ctx context.Context, mp MappingPayload) error {
var (
mapping *gabs.Container
properties *gabs.Container
res *elastic.PutMappingResponse
err error
)
mapping = gabs.New()
properties = gabs.New()
for _, f := range mp.Fields {
properties.Set(f.Type, f.Name, "type")
}
mapping.Set(properties, "properties")
if res, err = es.client.PutMapping().Index(mp.Index).Type(mp.Type).BodyString(mapping.String()).Do(ctx); err != nil {
return errors.Wrap(err, "call PutMapping() error")
}
if !res.Acknowledged {
return errors.New("putmapping failed!!!")
}
return nil
}
// CheckTypeExists assert the es type exists
func (es *Es) CheckTypeExists(ctx context.Context) (b bool, err error) {
if b, err = es.client.TypeExists().Index(es.esIndex).Type(es.esType).Do(ctx); err != nil {
return false, errors.Wrap(err, "call TypeExists() error")
}
return
}