Ejemplo simple de go-elasticsearch

Un ejemplo simple de segmentación de palabras ik api de go-elasticsearch


Referencia: https://godoc.org/github.com/elastic/go-elasticsearch

Ejemplo simple:

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
}

Código de segmentación de palabras, combinado con solicitud http nativa: (Según el documento oficial: https://github.com/elastic/go-elasticsearch/blob/master/_examples/extension/main.go línea 42 modificación)

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())
}

Supongo que te gusta

Origin blog.csdn.net/XiaoAnGeGe/article/details/107958410
Recomendado
Clasificación