4、go 中使用 elasticsearch

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "github.com/olivere/elastic/v7"
    "log"
    "os"
    "reflect"
)

type User struct {
    Name string `json:"name"`
    Age  uint   `json:"age"`
}

const mapping = `
{
    "settings":{
        "number_of_shards": 1,
        "number_of_replicas": 0
    },
    "mappings":{
        "user":{
            "properties":{
                "name":{
                    "type":"text",
                    "analyzer":"ik_max_word"
                },
                "age":{
                    "type":"long"
                }
            }
        }
    }
}`

func main() {
    url := "http://172.31.224.1:9200/"

    ctx := context.Background()

    logger := log.New(os.Stdout, "看看", log.LstdFlags)

    //elastic.SetSniff(false),防止elastic对ip进行转变
    client, err := elastic.NewClient(elastic.SetURL(url), elastic.SetSniff(false), elastic.SetTraceLog(logger))
    if err != nil {
        // Handle error
        panic(err)
    }

    // ping es数据库,查看是否ping通,并获取 es 版本号
    info, code, err := client.Ping(url).Do(ctx)
    if err != nil {
        // Handle error
        panic(err)
    }
    fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

    // 直接获取 es 版本号
    esversion, err := client.ElasticsearchVersion(url)
    if err != nil {
        // Handle error
        panic(err)
    }
    fmt.Printf("Elasticsearch version %s\n", esversion)

    // 查看 user 是否存在
    exists, err := client.IndexExists("user").Do(ctx)
    if err != nil {
        // Handle error
        panic(err)
    }
    fmt.Printf("user索引是否存在 %t \n", exists)

    // 若不存在就创建
    if !exists {
        // 创建 user 索引
        createIndex, err := client.CreateIndex("user").BodyString(mapping).Do(ctx)
        if err != nil {
            // Handle error
            panic(err)
        }
        if !createIndex.Acknowledged {
            // Not acknowledged
        }
    }

    // post 方式 给 user 添加数据
    user1 := User{Name: "新名字", Age: 99}
    put1, err := client.Index().
        Index("user").
        BodyJson(user1).
        Do(ctx)
    if err != nil {
        // Handle error
        panic(err)
    }
    fmt.Printf("Indexed user %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)

    // 刷新确保文件被写入
    _, err = client.Flush().Index("user").Do(ctx)
    if err != nil {
        panic(err)
    }

    // 获取某条数据
    get1, err := client.Get().
        Index("user").
        Id("4QTnFX8BjicySfgw5Njd").
        Do(ctx)
    if err != nil {
        // Handle error
        panic(err)
    }
    if get1.Found {
        fmt.Printf("Got document %s in version %d from index %s, type %s\n", get1.Id, get1.Version, get1.Index, get1.Type)
        fmt.Println(string(get1.Source)) // 字符串数据
        u := User{}
        json.Unmarshal(get1.Source, &u) // 将byte转为struct
        fmt.Println(u)
    }

    // term 级别的查询
    termQuery := elastic.NewTermQuery("age", "99")
    searchResult, err := client.Search().
        Index("user").
        Query(termQuery).
        //Sort("age", true). // sort by "age" field, ascending
        //From(0).Size(10).   // take documents 0-9
        Pretty(true). // pretty print request and response JSON
        Do(ctx)       // execute
    if err != nil {
        // Handle error
        panic(err)
    }
    fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis) // 查询耗时x毫秒

    // 将结果,循环打印出来
    var ttyp User
    for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
        if t, ok := item.(User); ok {
            fmt.Printf("User by %s: %d\n", t.Name, t.Age)
        }
    }

    fmt.Printf("Found a total of %d user\n", searchResult.TotalHits()) // 一共 xx 条

    /************************************************************************************/

    // Here's how you iterate through results with full control over each step.
    if searchResult.Hits.TotalHits > 0 {
        fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)

        // Iterate through results
        for _, hit := range searchResult.Hits.Hits {
            // hit.Index contains the name of the index

            // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
            var t Tweet
            err := json.Unmarshal(*hit.Source, &t)
            if err != nil {
                // Deserialization failed
            }

            // Work with tweet
            fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
        }
    } else {
        // No hits
        fmt.Print("Found no tweets\n")
    }

    // Update a tweet by the update API of Elasticsearch.
    // We just increment the number of retweets.
    update, err := client.Update().Index("twitter").Type("tweet").Id("1").
        Script(elastic.NewScriptInline("ctx._source.retweets += params.num").Lang("painless").Param("num", 1)).
        Upsert(map[string]interface{}{"retweets": 0}).
        Do(ctx)
    if err != nil {
        // Handle error
        panic(err)
    }
    fmt.Printf("New version of tweet %q is now %d\n", update.Id, update.Version)

    // ...

    // Delete an index.
    deleteIndex, err := client.DeleteIndex("twitter").Do(ctx)
    if err != nil {
        // Handle error
        panic(err)
    }
    if !deleteIndex.Acknowledged {
        // Not acknowledged
    }
}

 

posted @ 2022-02-20 17:13  JaydenQiu  阅读(306)  评论(0)    收藏  举报