刘启洪 發表於 2020-7-28 15:13:00

Go操作Elasticsearch

<h4 id="安装es">安装ES</h4>
<h5 id="拉取es到本地">拉取es到本地</h5>
<pre><code class="language-go">docker pull docker.elastic.co/elasticsearch/elasticsearch:7.3.0
</code></pre>
<h5 id="创建一个网络">创建一个网络</h5>
<pre><code class="language-go">docker network create esnet
</code></pre>
<h5 id="启动容器">启动容器</h5>
<pre><code class="language-go">docker run --name es-p 9200:9200 -p 9300:9300--network esnet -e "discovery.type=single-node" bdaab402b220
</code></pre>
<h5 id="安装elistichd">安装ElisticHD</h5>
<pre><code class="language-go">docker run -p 9800:9800 -d --link es:demo--network esnet -e "discovery.type=single-node"containerize/elastichd
</code></pre>
<p><img src="https://img2020.cnblogs.com/blog/1871335/202007/1871335-20200728151228132-403069436.png" alt="" loading="lazy"></p>
<h4 id="下载依赖库">下载依赖库</h4>
<pre><code class="language-go"> go get github.com/olivere/elastic/v7
</code></pre>
<h4 id="操作案例">操作案例</h4>
<h5 id="创建索引">创建索引</h5>
<pre><code class="language-go">package main

import (
        "context"
        "fmt"
        "github.com/olivere/elastic"
)

var client *elastic.Client

var host = "http://192.168.43.176:9200"


type Employee struct {
        FirstName string   `json:"first_name"`
        LastNamestring   `json:"last_name"`
        Age       int      `json:"age"`
        About   string   `json:"about"`
        Interests []string `json:"interests"`
}

//初始化
func init() {
        //errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
        var err error
        //这个地方有个小坑 不加上elastic.SetSniff(false) 会连接不上
        client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(host))
        if err != nil {
                panic(err)
        }
        _,_,err = client.Ping(host).Do(context.Background())
        if err != nil {
                panic(err)
        }
        //fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

        _,err = client.ElasticsearchVersion(host)
        if err != nil {
                panic(err)
        }
        //fmt.Printf("Elasticsearch version %s\n", esversion)
}

//创建
func create() {

        //使用结构体
        e1 := Employee{"Jane", "Smith", 32, "I like to collect rock albums", []string{"music"}}
        put1, err := client.Index().
                Index("megacorp").
                Type("employee").
                Id("1").
                BodyJson(e1).
                Do(context.Background())
        if err != nil {
                panic(err)
        }
        fmt.Printf("Indexed tweet %s to index s%s, type %s\n", put1.Id, put1.Index, put1.Type)

        //使用字符串
        e2 := `{"first_name":"John","last_name":"Smith","age":25,"about":"I love to go rock climbing","interests":["sports","music"]}`
        put2, err := client.Index().
                Index("megacorp").
                Type("employee").
                Id("2").
                BodyJson(e2).
                Do(context.Background())
        if err != nil {
                panic(err)
        }
        fmt.Printf("Indexed tweet %s to index s%s, type %s\n", put2.Id, put2.Index, put2.Type)

        e3 := `{"first_name":"Douglas","last_name":"Fir","age":35,"about":"I like to build cabinets","interests":["forestry"]}`
        put3, err := client.Index().
                Index("megacorp").
                Type("employee").
                Id("3").
                BodyJson(e3).
                Do(context.Background())
        if err != nil {
                panic(err)
        }
        fmt.Printf("Indexed tweet %s to index s%s, type %s\n", put3.Id, put3.Index, put3.Type)
}

func main(){
        create()
}
</code></pre>
<h5 id="查找">查找</h5>
<pre><code class="language-go">package main

import (
        "context"
        "encoding/json"
        "fmt"
        "github.com/olivere/elastic"
)

var client *elastic.Client

var host = "http://192.168.43.176:9200"

type Employee struct {
        FirstName string   `json:"first_name"`
        LastNamestring   `json:"last_name"`
        Age       int      `json:"age"`
        About   string   `json:"about"`
        Interests []string `json:"interests"`
}

//初始化
func init() {
        //errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
        var err error
        //这个地方有个小坑 不加上elastic.SetSniff(false) 会连接不上
        client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(host))
        if err != nil {
                panic(err)
        }
        _, _, err = client.Ping(host).Do(context.Background())
        if err != nil {
                panic(err)
        }
        //fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

        _, err = client.ElasticsearchVersion(host)
        if err != nil {
                panic(err)
        }
        //fmt.Printf("Elasticsearch version %s\n", esversion)
}

//查找
func gets() {
        //通过id查找
        get1, err := client.Get().Index("megacorp").Type("employee").Id("2").Do(context.Background())
        if err != nil {
                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)
                var bb Employee
                err := json.Unmarshal(get1.Source, &amp;bb)
                if err != nil {
                        fmt.Println(err)
                }
                fmt.Println(bb.FirstName)
                fmt.Println(string(get1.Source))
        }
}

func main() {
        //create()
        gets()
}
</code></pre>
<h5 id="删除">删除</h5>
<pre><code class="language-go">//删除
func delete() {
        res, err := client.Delete().Index("megacorp").
                Type("employee").
                Id("1").
                Do(context.Background())
        if err != nil {
                println(err.Error())
                return
        }
        fmt.Printf("delete result %s\n", res.Result)
}

func main() {
        //create()
        //gets()
        delete()
}
</code></pre>
<h5 id="修改">修改</h5>
<pre><code class="language-go">//修改
func update() {
        res, err := client.Update().
                Index("megacorp").
                Type("employee").
                Id("2").
                Doc(mapinterface{}{"age": 88}).
                Do(context.Background())
        if err != nil {
                println(err.Error())
        }
        fmt.Printf("update age %s\n", res.Result)

}

func main() {
        //create()
        //gets()
        //delete()
        update()
}
</code></pre>
<h5 id="搜索">搜索</h5>
<pre><code class="language-go">////搜索
func query() {
        var res *elastic.SearchResult
        var err error
        //取所有
        res, err = client.Search("megacorp").Type("employee").Do(context.Background())
        printEmployee(res, err)

        //字段相等
        q := elastic.NewQueryStringQuery("last_name:Smith")
        res, err = client.Search("megacorp").Type("employee").Query(q).Do(context.Background())
        if err != nil {
                println(err.Error())
        }
        printEmployee(res, err)



        //条件查询
        //年龄大于30岁的
        boolQ := elastic.NewBoolQuery()
        boolQ.Must(elastic.NewMatchQuery("last_name", "smith"))
        boolQ.Filter(elastic.NewRangeQuery("age").Gt(30))
        res, err = client.Search("megacorp").Type("employee").Query(q).Do(context.Background())
        printEmployee(res, err)

        //短语搜索 搜索about字段中有 rock climbing
        matchPhraseQuery := elastic.NewMatchPhraseQuery("about", "rock climbing")
        res, err = client.Search("megacorp").Type("employee").Query(matchPhraseQuery).Do(context.Background())
        printEmployee(res, err)

        //分析 interests
        aggs := elastic.NewTermsAggregation().Field("interests")
        res, err = client.Search("megacorp").Type("employee").Aggregation("all_interests", aggs).Do(context.Background())
        printEmployee(res, err)

}
//
////简单分页
func list(size,page int) {
        if size &lt; 0 || page &lt; 1 {
                fmt.Printf("param error")
                return
        }
        res,err := client.Search("megacorp").
                Type("employee").
                Size(size).
                From((page-1)*size).
                Do(context.Background())
        printEmployee(res, err)

}
//
//打印查询到的Employee
func printEmployee(res *elastic.SearchResult, err error) {
        if err != nil {
                print(err.Error())
                return
        }
        var typ Employee
        for _, item := range res.Each(reflect.TypeOf(typ)) { //从搜索结果中取数据的方法
                t := item.(Employee)
                fmt.Printf("%#v\n", t)
        }
}


func main() {
        //create()
        //gets()
        //delete()
        //update()
        gets()
        query()
        list(2,1)
}
</code></pre><br><br>
来源:https://www.cnblogs.com/you-men/p/13391265.html
頁: [1]
查看完整版本: Go操作Elasticsearch