在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
安装go package: go get github.com/olivere/elastic
开撸: /**
* es demo
* author:JetWu
* date:2020.06.10
*/
package es
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"encoding/json"
"github.com/olivere/elastic"
)
type Student struct {
Name string `json:"name"`
Age int `json:"age"`
City string `json:"city"`
Interests []string `json:"interests"`
Introduction string `json:"introduction"`
}
var client *elastic.Client
var host = "http://127.0.0.1:9200/"
/**
* 连接es
*/
func init() {
log.Println("Connecting to elasticsearch server...")
//连接es
var err error
client, err = elastic.NewSimpleClient(elastic.SetURL(host))
if err != nil {
log.Println("Connected failed: ", err)
return
}
log.Println("Connected succeed!")
//测试es连接
info, _, err := client.Ping(host).Do(context.Background())
if err != nil {
log.Println("Ping elasticsearch server failed: ", err)
return
}
log.Println("elasticsearch version: ", info.Version.Number)
}
/**
* 打印查询语句
*/
func PrintQuery(src interface{}) {
data, err := json.MarshalIndent(src, "", "")
if err != nil {
log.Println("PrintQuery Error: ", err)
return
}
fmt.Println("PrintQuery:\n", string(data))
}
/**
* 搜索
*/
func Search(keyword string) []*Student {
queryStr := `{
"bool": {
"should": [
{
"match": {"name":"%s"}
},
{
"match": {"city":"%s"}
},
{
"match": {"interests":"%s"}
},
{
"match": {"introduction":"%s"}
}
]
}
}`
rawQuery := elastic.NewRawStringQuery(fmt.Sprintf(queryStr, keyword, keyword, keyword, keyword))
PrintQuery(rawQuery)
searchResult, err := client.Search("school").Type("student").
Query(rawQuery).From(0).Size(10).Do(context.Background())
if err != nil {
log.Println("Search Error: ", err)
return nil
}
fmt.Printf("Query took %d milliseconds, total: %d\n", searchResult.TookInMillis, searchResult.Hits.TotalHits)
var students []*Student
var stuType Student
for _, item := range searchResult.Each(reflect.TypeOf(stuType)) {
if stu, ok := item.(Student); ok {
students = append(students, &stu)
}
}
return students
}
/**
* 添加/修改
*/
func Add(indexId string, stu *Student) error {
if stu == nil {
return errors.New("Add Error: data empty!")
}
ret, err := client.Index().Index("school").Type("student").
Id(indexId).BodyJson(stu).Do(context.Background())
if err != nil {
log.Println("Add Error: ", err)
return err
}
fmt.Printf("Indexed %s to index %s, type %s\n", ret.Id, ret.Index, ret.Type)
return nil
}
/**
* 删除
*/
func Remove(indexId string) error {
ret, err := client.Delete().Index("school").Type("student").
Id(indexId).Do(context.Background())
if err != nil {
log.Println("Remove Error: ", err)
return err
}
fmt.Printf("delete result: %d, %s\n", ret.Status, ret.Result)
return nil
}
|
请发表评论