go操作Elasticsearch簡單示例


 

go操作Elasticsearch主要有以下兩個sdk

  • github.com/olivere/elastic 
  • github.com/elastic/go-elasticsearch 
  • 我們這里選擇第一個
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)
 
}



//修改
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)
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM