zoukankan      html  css  js  c++  java
  • 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
    ", 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)
    }
    

      

  • 相关阅读:
    CF1033F Boolean Computer
    CF1027G X-mouse in the Campus
    LOJ2570 [ZJOI2017]线段树
    清华强基&交大浙大三一
    java制作unicode代码在excel中批量导入图片
    laravel8新功能和笔记
    缩小图片比例大小和占用空间
    2018-2019-2 20175216张雪原 实验五《网络编程与安全》实验报告
    2018-2019-2 20175216张雪原 实验四《Android程序设计》实验报告
    20175216 《Java程序设计》第十一周学习总结
  • 原文地址:https://www.cnblogs.com/-wenli/p/12737196.html
Copyright © 2011-2022 走看看