Golang elasticsearch 对接问题

前端之家收集整理的这篇文章主要介绍了Golang elasticsearch 对接问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

es包

gopkg.in/olivere/elastic.v3


Golang操作es 过程中,定义struct 结果写入es的内容总是为空,后来发现,定义struct 首字母小写了,Golang中首字母小写表示私有,所以无法成功写入,改成共有的即可。

刚学习,还不熟悉,做个记录



//qnzsEsprojectmain.go
packagemain

import(
"fmt"
"log"
"os"

"database/sql"
"time"

_"github.com/go-sql-driver/MysqL"
"gopkg.in/olivere/elastic.v3"
)

varclient*elastic.Client
vardb*sql.DB

typequesstruct{
qidstring
titlestring
addedstring
orgidstring
}

typeQues2struct{
Contentstring
}

funcinit(){
varerrerror
client,err=elastic.NewClient(
elastic.SetURL("http://127.0.0.1:9200"),
elastic.SetSniff(false),
elastic.SetHealthcheckInterval(10*time.Second),
elastic.SetMaxRetries(5),
elastic.SetErrorLog(log.New(os.Stderr,"ELASTIC",log.LstdFlags)),
elastic.SetInfoLog(log.New(os.Stdout,"",log.LstdFlags)))
iferr!=nil{
fmt.Println(err)
}
//初始化MysqL
db,_=sql.Open("MysqL","root:123456@tcp(127.0.0.1:3306)/youth_qnzs")
db.SetMaxOpenConns(2000)
db.SetMaxIdleConns(1000)
db.Ping()
}

funcmain(){
quesRow:=getFromMysqL()
//fmt.Println(ques["orgstrid"])
//quesContent:=ques{qid:quesRow["q_id"],title:quesRow["q_title"],added:quesRow["q_added"],orgid:quesRow["orgid"]}
quesContent:=Ques2{Content:quesRow["q_title"]}
fmt.Println(quesContent)
_,err:=client.Index().
Index("ikindex").
Type("fulltext").
Id(quesRow["q_id"]).
BodyJson(quesContent).
Refresh(true).
Do()
iferr!=nil{
//Handleerror
panic(err)
}

}

funcgetFromMysqL()map[string]string{
record:=make(map[string]string)
rows,err:=db.Query("SELECT*FROMq_questionslimit998,1")
deferrows.Close()
//checkErr(err)
iferr!=nil{
fmt.Println(err)
returnrecord
}

columns,_:=rows.Columns()
scanArgs:=make([]interface{},len(columns))
values:=make([]interface{},len(columns))
forj:=rangevalues{
scanArgs[j]=&values[j]
}

forrows.Next(){
//将行数据保存到record字典
err=rows.Scan(scanArgs...)
fori,col:=rangevalues{
ifcol!=nil{
record[columns[i]]=string(col.([]byte))
}
}
}
returnrecord
}

/**
*从es搜索
*/
funcesSearch(){
termQuery:=elastic.NewTermQuery("content","中国")
searchResult,err:=client.Search().
Index("ikindex").Type("fulltext").//searchinindex"twitter"
Query(termQuery).//specifythequery
//Sort("user",true).//sortby"user"field,ascending
From(0).Size(10).//takedocuments0-9
Pretty(true).//prettyprintrequestandresponseJSON
Do()//execute
iferr!=nil{
//Handleerror
panic(err)
}

//searchResultisoftypeSearchResultandreturnshits,suggestions,
//andallkindsofotherinformationfromElasticsearch.
fmt.Printf("Querytook%dmilliseconds\n",searchResult.TookInMillis)
fmt.Println(searchResult.Hits.TotalHits)

fmt.Println("HelloWorld!")
}
原文链接:https://www.f2er.com/go/189467.html

猜你在找的Go相关文章