go 操作elasticsearch

olivere/elastic 包

github.com/olivere/elastic

doc:

https://pkg.go.dev/github.com/olivere/elastic?utm_source=godoc

初使货es



package elasticsearch

import (
	"github.com/olivere/elastic"
	"go-admin/common/log"
	"go-admin/tools"
)

var host = "http://127.0.0.1:9200"
var ElaticClent *elastic.Client
//基本参考:
//https://blog.csdn.net/chen_peng7/article/details/90700910
// https://blog.csdn.net/Xiao_W_u/article/details/118908282
//批量操作参考:https://zhuanlan.zhihu.com/p/238206335
func InitElasticClient() (err error) {
	ElaticClent, err = elastic.NewClient(
		elastic.SetURL(host),
		elastic.SetSniff(false), 				// SetSniff启用或禁用嗅探器(默认情况下启用)。
		elastic.SetBasicAuth("Username", "Password"),	// 账号密码
	)
	if err != nil {
		log.Fatal(tools.Red("elasticsearch connect failed !"), err)
		return err
	}
	//do, i, _ := ElaticClent.Ping(host).Do(context.Background())
	//fmt.Println("do:",do)
	//fmt.Println("i:",i)

	version, _ := ElaticClent.ElasticsearchVersion(host)
	//http://172.27.0.2:9200 [dead=false,failures=0,deadSince=<nil>] <nil>
	log.Info(tools.Green("elasticsearch connect success ! version:"+version))
	return nil
}

package main
  
import (
    "context"
    "fmt"
    "github.com/olivere/elastic"
)
  
创建索引:
func main(){
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
    fmt.Println(Client, err)
    name := "people2"
    Client.CreateIndex(name).Do(context.Background())
}
 
插入数据
func main(){
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
    fmt.Println(Client, err)
    name := "people2"
    data := `{
    "name": "wali",
    "country": "Chian",
    "age": 30,
    "date": "1987-03-07"
    }`
    _, err = Client.Index().Index(name).Type("man1").Id("1").BodyJson(data).Do(context.Background())
  
}
  
查找数据: //通过id查找
func main(){
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
    fmt.Println(Client, err)
    name := "people2"
    get, err := Client.Get().Index(name).Type("man1").Id("1").Do(context.Background())
    fmt.Println(get, err)
    source, _ := get.Source.MarshalJSON()
    fmt.Printf("id:%s Source:%s \n", get.Id, string(source))
}
 
组合查询:
func main(){
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
    fmt.Println(Client, err)
    query := elastic.NewBoolQuery()
	ip := "106.75.96.205"
	port := "8082"
	app := "NGINX"
	if len(ip) > 0 {
		query = query.Must(elastic.NewTermQuery("ip.ip_raw", ip))
	}
	if len(port) > 0 {
		query = query.Must(elastic.NewTermQuery("port.port_raw", port))
	}
	if len(app) > 0 {
		query = query.Must(elastic.NewTermQuery("product.raw", app))
	}

	source, _ := query.Source()
	marshalSource, _ := json.Marshal(source)
	fmt.Println("source:--->", string(marshalSource)) //打印query语句
	pageIndex:= 1
	pageSize:= 10
	fmt.Println("pageIndex", pageIndex) //打印query语句
	sr, err := Client.Search("fofapro_subdomain", "fofapro_service").
		Query(query).
		From((pageIndex - 1) * pageSize).
		Size(pageSize).
		Do(context.Background())
	fmt.Printf("err:%#v , AssetManagementSearch22----->:%#v \n", err, sr)
	if err != nil {
		return err
	}
	fmt.Printf("sr.Hits.Hits:%#v \n", sr.Hits.Hits)
	countTmp := sr.TotalHits()
	fmt.Printf("countTmp:%#v \n", countTmp)
	count = &countTmp
	var resjson string
	for _, item := range sr.Hits.Hits {
		b, _ := item.Source.MarshalJSON()
		fmt.Println("b:--->", string(b))
		resjson += string(b) + "\r\n"
	}
}
 
//修改
func main() {
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
        res, err := client.Update().
        Index("megacorp").
        Type("employee").
        Id("2").
        Doc(map[string]interface{}{"age": 88}).
        Do(context.Background())
        if err != nil {
            println(err.Error())
        }
        fmt.Printf("update age %s\n", res.Result)
  
}
 
 
 
删除数据
func main(){
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
    //使用结构体
        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)
        }
    //删除
    get, err := Client.Get().Index("megacorp").Type("employee").Id("1").Do(context.Background())
    fmt.Println(get, err)
}



参考:
https://www.cnblogs.com/-wenli/p/12737196.html


官方包

参考:
https://blog.csdn.net/Xiao_W_u/article/details/118908282

https://www.cnblogs.com/gwyy/p/13356345.html
https://github.com/elastic/go-elasticsearch 来连接ES并进行操作。
https://www.cnblogs.com/binHome/p/12345413.html

posted @ 2021-03-05 09:39  HaimaBlog  阅读(135)  评论(0编辑  收藏  举报