参考文档
package main
import (
"context"
"fmt"
"reflect"
"github.com/olivere/elastic/v7"
)
var client *elastic.Client
var host="http://127.0.0.1:9200"
type School struct {
TeacherName string `json:"teacher_name"`
StudentName string `json:"student_name"`
}
// 初始化es
func init (){
clients,err:=elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"))
if err !=nil {
panic(err)
}
client=clients
}
/*
es CURD 简单操作
*/
// 不同数据类型 create
func create (){
// struct
//for i:=0;i<8;i++ {
es:=School{"m","s"}
res,err:=client.Index().
Index("struct").
Type("struct").
Id("8").BodyJson(es).BodyJson(es).
Do(context.Background())
if err !=nil {
panic(err)
}
fmt.Printf("document ID. %s, Index is the name of the index. %s, Type is the type of the document. %s\n", res.Id, res.Index, res.Type)
//}
/*
// string
es1:=`{"name":"tom"}`
res1,err:=client.Index().
Index("string").
Type("string").BodyJson(es1).
Id("2").
Do(context.Background())
fmt.Printf("document ID. %s, Index is the name of the index. %s, Type is the type of the document. %s\n", res1.Id, res1.Index, res1.Type)
*/
}
// update
func update (){
res,err:=client.Update().
Index("string").
Type("string").
Id("2").
Doc(map[string]interface{}{"name":"tomms"}).
Do(context.Background())
if err!=nil {
panic(err.Error())
}
fmt.Printf("update name %s\n",res.Result)
}
//find
func gets (){
//通过主键id 查找
res,err:=client.Get().Index("string").Type("string").Id("2").Do(context.Background())
if err !=nil {
panic(err)
}
if res.Found {
fmt.Printf("document ID. %s, Index is the name of the index. %s, Type is the type of the document. %s\n", res.Id, res.Index, res.Type)
}
}
//delete
func delete (){
res,err:=client.Delete().Index("string").
Type("string").Id("2").Do(context.Background())
if err !=nil {
panic(err.Error())
return
}
fmt.Printf("delete result %s\n", res.Result)
}
//search
func search(){
var res *elastic.SearchResult
var err error
/*
//取所有
res, err = client.Search("struct").Type("struct").Do(context.Background())
printEmployee(res, err)
*/
//字段值匹配 teacher_name:m
q:=elastic.NewQueryStringQuery("teacher_name:m")
res,err=client.Search("struct").Type("struct").Query(q).Do(context.Background())
if err !=nil {
println(err.Error())
}
printEmployee(res, err)
}
// 输出信息到struct
func printEmployee(res *elastic.SearchResult, err error) {
if err != nil {
print(err.Error())
return
}
var typ School
for _, item := range res.Each(reflect.TypeOf(typ)) {
t := item.(School)
fmt.Printf("%#v\n", t)
}
}
//分页
func list(size, page int) {
if size <0 || page <1 {
fmt.Println("param error")
return
}
res,err:=client.Search("struct").
Type("struct").
Size(size).
From((page - 1) * size).
Do(context.Background())
printEmployee(res, err)
}
func main (){
//create()
//update()
//gets()
//delete()
// search()
list(5,1)
}
测试运行结果
有疑问加站长微信联系(非本文作者)