go-elasticsearch的简单例子

夏俊杰
2023-12-01

简单的例子:

package main

import (
   "bytes"
   "context"
   "encoding/json"
   "fmt"
   "github.com/elastic/go-elasticsearch/v8"
   "github.com/elastic/go-elasticsearch/v8/esapi"
   "log"
)

var client *elasticsearch.Client

func main()  {
   var err error
   if err = InitEsClient();err !=nil{
      log.Println(err)
   }
   query:=map[string]interface{}{
      "query":"select caseid,title from xc_cases where title like '%中国电信%'",//这里使用mysql的方式来请求,非常简单,符合开发习惯,简化es入门门槛,支持order,支持Limit,那么排序和分页就自己写好了
   }
   jsonBody , _ := json.Marshal(query)
   req := esapi.SQLQueryRequest{Body: bytes.NewReader(jsonBody)}
   res, _ := req.Do(context.Background(),client)
   defer res.Body.Close()
   fmt.Println(res.String())
}

func InitEsClient() (err error){
   config := elasticsearch.Config{}
   config.Addresses = []string{"http://39.105.8.84:9200"}
   client , err = elasticsearch.NewClient(config)
   return err
}

分词代码,结合原生http请求:(根据官方文档:https://github.com/elastic/go-elasticsearch/blob/master/_examples/extension/main.go 42行改装)

func GetIkInfo(){
   query := map[string]interface{}{
      "analyzer":"ik_smart",//智能分词用:ik_smart,最大化分词用:ik_max_word
      "text":"美国总统大选",
   }
   jsonBody, _ := json.Marshal(query)
   req,_ :=http.NewRequest("GET","/_analyze?pretty=true",bytes.NewReader(jsonBody))
   req.Header.Add("Content-type","application/json")
   res ,err := client.Perform(req)
   if err !=nil{
      return
   }
   defer res.Body.Close()
   buf := new(bytes.Buffer)
   buf.ReadFrom(res.Body)
   fmt.Println(buf.String())
}
 类似资料: