当前位置:   article > 正文

go语言操作es_go es

go es

go语言操作es

go get github.com/olivere/elastic
  • 1

解决golang使用elastic连接elasticsearch时自动转换连接地址

image-20220313132256334

 elastic.SetSniff(false)
  • 1
client, _ := elastic.NewClient(
  // ...
  // 将sniff设置为false后,便不会自动转换地址
   elastic.SetSniff(false),
)
  • 1
  • 2
  • 3
  • 4
  • 5

image-20220313133130410

初始化

var client *elastic.Client

var host = "http://xxx:9200"

//初始化es驱动
func init() {

   errorlog := log.New(os.Stdout, "app", log.LstdFlags)

   var err error
   client, err = elastic.NewClient(elastic.SetErrorLog(errorlog), elastic.SetURL(host), elastic.SetSniff(false))
   if err != nil {
      panic(err)
   }
   info, code, err := client.Ping(host).Do(context.Background())
   if err != nil {
      panic(err)
   }
   fmt.Printf("Es return with code %d and version %s \n", code, info.Version.Number)
   esversionCode, err := client.ElasticsearchVersion(host)
   if err != nil {
      panic(err)
   }
   fmt.Printf("es version %s\n", esversionCode)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

数据创建

info —>employee -------FirstName,LastName,Age,About,Interests

结构体方式
type Employee struct {
	FirstName string `json:"firstname"`
	LastName string `json:"lastname"`
	Age int `json:"age"`
	About string `json:"about"`
	Interests []string `json:"interests"`
}

//创建索引
func create() {
	//1.使用结构体方式存入到es里面
	e1 := Employee{"jane", "Smith", 20, "I like music", []string{"music"}}
	put, err := client.Index().Index("info").Type("employee").Id("1").BodyJson(e1).Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Printf("indexed %d to index %s, type %s \n", put.Id, put.Index, put.Type)
}

func main() {
	create()
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
字符串方式:
func create1() {
   //使用字符串
   e1 := `{"firstname":"john","lastname":"smith","age":22,"about":"i like book","interests":["book","music"]}`
   put, err := client.Index().Index("info").Type("employee").Id("2").BodyJson(e1).Do(context.Background())
   if err != nil {
      panic(err)
   }
   fmt.Printf("indexed %d to index %s, type %s \n", put.Id, put.Index, put.Type)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

查找

//查找
func get() {
   get, err := client.Get().Index("info").Type("employee").Id("1").Do(context.Background())
   if err != nil {
      panic(err)
   }
   if get.Found {
      fmt.Printf("got document %s in version %d from index %s,type %s \n", get.Id, get.Version, get.Index, get.Type)
   }
}

func main() {
   get()
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

修改

func update() {
   res, err := client.Update().Index("info").Type("employee").Id("1").Doc(map[string]interface{}{"age": 88}).Do(context.Background())
   if err != nil {
      fmt.Println(err.Error())
   }
   fmt.Printf("update age %s \n", res.Result)
}

func main() {
   update()
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

删除

//删除
func delete() {
   res, err := client.Delete().Index("info").Type("employee").Id("1").Do(context.Background())
   if err != nil {
      fmt.Println(err.Error())
   }
   fmt.Printf("delete result %s", res.Result)
}

func main() {
   delete()
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

查找

func query() {
   var res *elastic.SearchResult
   var err error
   res, err = client.Search("info").Type("employee").Do(context.Background())
   printEmployee(res, err)

}

//打印查询的employee
func printEmployee(res *elastic.SearchResult, err error) {
   if err != nil {
      fmt.Print(err.Error())
      return
   }

   var typ Employee
   for _, item := range res.Each(reflect.TypeOf(typ)) {
      t := item.(Employee)
      fmt.Printf("%#v\n", t)
   }
}

//条件查找
func query1() {
   var res *elastic.SearchResult
   var err error
   //查找方式一:
   q := elastic.NewQueryStringQuery("lastname:smith")
   res, err = client.Search("info").Type("employee").Query(q).Do(context.Background())
   printEmployee(res, err)
   //查找方法二:
   if res.Hits.TotalHits > 0 {
      fmt.Printf("found a total fo %d Employee", res.Hits.TotalHits)

      for _, hit := range res.Hits.Hits {
         var t Employee
         err := json.Unmarshal(*hit.Source, &t) //另一种取出的方法
         if err != nil {
            fmt.Println("failed")
         }
         fmt.Printf("employee name %s:%s\n", t.FirstName, t.LastName)
      }
   } else {
      fmt.Printf("found no employee \n")
   }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

年龄大于21的查找

//年龄大于21的
func query3() {
	var res *elastic.SearchResult
	var err error
	boolq := elastic.NewBoolQuery()
	boolq.Must(elastic.NewMatchQuery("lastname", "smith"))
	boolq.Filter(elastic.NewRangeQuery("age").Gt(21))
	res, err = client.Search("info").Type("employee").Query(boolq).Do(context.Background())
	printEmployee(res, err)
}

//打印查询的employee
func printEmployee(res *elastic.SearchResult, err error) {
   if err != nil {
      fmt.Print(err.Error())
      return
   }

   var typ Employee
   for _, item := range res.Each(reflect.TypeOf(typ)) {
      t := item.(Employee)
      fmt.Printf("%#v\n", t)
   }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

包含book的

//包含book的
func query4() {
   var res *elastic.SearchResult
   var err error
   matchPhrase := elastic.NewMatchPhraseQuery("about", "book")
   res, err = client.Search("info").Type("employee").Query(matchPhrase).Do(context.Background())
   printEmployee(res, err)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

分页

//分页
func list(size, page int) {
   var res *elastic.SearchResult
   var err error
   if size < 0 || page < 1 {
      fmt.Printf("param error")
      return
   }
   res, err = client.Search("info").Type("employee").Size(size).From((page - 1) * size).Do(context.Background())
   printEmployee(res, err)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

集群搭建

配置文件修改

node.name : node-102
node.name : node-103

network.host: 192.168.1.102
network.host: 192.168.1.103

discovery.zen.ping.unicast.hosts: ["s201","s202","s203"]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

image-20220313152546924

image-20220313152935387

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/734099
推荐阅读
相关标签
  

闽ICP备14008679号