メメメモモ

プログラミング備忘録、リモートワーク生活、筋トレ、etc

Go言語でAWS ElasticSearchを操作する

package main

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "io"
    "log"
    "net/http"
    "time"
)

type User struct {
    Name      string    `json:"name"`
    Age       int       `json:"age"`
    Note      string    `json:"note"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
}

const URL = "https://xxxxxxxxxxx.ap-northeast-1.es.amazonaws.com"

func newRequest(ctx context.Context, method, url string, body io.Reader) (*http.Request, error) {
    req, err := http.NewRequest(method, url, body)
    if err != nil {
        return nil, err
    }
    req.Header.Set("Content-Type", "application/json")

    req = req.WithContext(ctx)

    return req, nil
}

func decodeBody(resp *http.Response, out interface{}) error {
    defer resp.Body.Close()
    var r io.Reader = resp.Body
    decoder := json.NewDecoder(r)
    return decoder.Decode(out)
}

func encodeBody(jsonMap interface{}) (io.Reader, error) {
    b, err := json.Marshal(jsonMap)
    if err != nil {
        return nil, err
    }
    return bytes.NewReader(b), nil
}

func describeSetting(ctx context.Context) {
    req, err := newRequest(ctx, "GET", URL, nil)
    if err != nil {
        panic(err)
    }

    httpClient := http.DefaultClient
    res, err := httpClient.Do(req)
    if err != nil {
        panic(err)
    }

    log.Printf("%#v", res)
    var ret map[string]interface{}
    if err := decodeBody(res, &ret); err != nil {
        panic(err)
    }

    log.Printf("%#v", ret)
}

func createUsers(ctx context.Context) {
    for i := 0; i < 100; i++ {
        user := User{
            Name:      fmt.Sprintf("Name_%d", i+1),
            Age:       i + 1,
            Note:      fmt.Sprintf("Note_%d", i+1),
            CreatedAt: time.Now(),
            UpdatedAt: time.Now(),
        }

        body, err := encodeBody(user)
        if err != nil {
            panic(err)
        }

        req, err := newRequest(ctx, "POST", fmt.Sprintf("%s/users/doc", URL), body)
        if err != nil {
            panic(err)
        }

        res, err := http.DefaultClient.Do(req)
        if err != nil {
            panic(err)
        }

        log.Printf("%#v", res)
    }
}

func searchByName(ctx context.Context, name string) {
    query := map[string]interface{}{
        "query": map[string]interface{}{
            "match": map[string]interface{}{
                "name": "Name_10",
            },
        },
        "sort": map[string]interface{}{
            "name": map[string]interface{}{
                "order": "desc",
            },
        },
    }
    body, err := encodeBody(query)
    if err != nil {
        panic(err)
    }

    req, err := newRequest(ctx, "GET", fmt.Sprintf("%s/users/doc/_search?pretty", URL), body)
    if err != nil {
        panic(err)
    }

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }

    var ret map[string]interface{}
    err = decodeBody(res, &ret)
    if err != nil {
        panic(err)
    }

    log.Printf("%#v", ret)
}

func main() {
    ctx := context.Background()
    searchByName(ctx, "Name_2")
}