-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.go
74 lines (67 loc) · 2.27 KB
/
index.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
package main
import (
"context"
"fmt"
"github.com/olivere/elastic"
)
const (
USER_INDEX = "user"
POST_INDEX = "post"
//do not use localhost: cannot use when DB is separate from the go
//use external need to change the URL everytime as it changes every time
ES_URL = "http://10.150.0.2:9200"
)
func main() {
//create a connection client
client, err := elastic.NewClient(elastic.SetURL(ES_URL))
if err != nil {
// handle error
panic(err)
}
// check if the index exists or not
// Do is the real part that execute the previous codes, context.background
exists, err := client.IndexExists(POST_INDEX).Do(context.Background())
if err != nil {
panic(err)
}
if !exists {
// index schema
mapping := `{
"mappings": {
"properties": {
"user": { "type": "keyword", "index": false },
"message": { "type": "keyword", "index": false },
"location": { "type": "geo_point" },
"url": { "type": "keyword", "index": false },
"type": { "type": "keyword", "index": false },
"face": { "type": "float" }
}
}
}`
_, err := client.CreateIndex(POST_INDEX).Body(mapping).Do(context.Background())
if err != nil {
panic(err)
}
}
exists, err = client.IndexExists(USER_INDEX).Do(context.Background())
if err != nil {
panic(err)
}
if !exists {
mapping := `{
"mappings": {
"properties": {
"username": {"type": "keyword"},
"password": {"type": "keyword", "index": false},
"age": {"type": "long", "index": false},
"gender": {"type": "keyword", "index": false}
}
}
}`
_, err = client.CreateIndex(USER_INDEX).Body(mapping).Do(context.Background())
if err != nil {
panic(err)
}
}
fmt.Println("Post index is created.")
}