es包
gopkg.in/olivere/elastic.v3
Golang操作es 过程中,定义struct 结果写入es的内容总是为空,后来发现,定义struct 首字母小写了,Golang中首字母小写表示私有,所以无法成功写入,改成共有的即可。
刚学习,还不熟悉,做个记录
// qnzsEs project main.go
package main
import (
"fmt"
"log"
"os"
"database/sql"
"time"
_ "github.com/go-sql-driver/mysql"
"gopkg.in/olivere/elastic.v3"
)
var client *elastic.Client
var db *sql.DB
type ques struct {
qid string
title string
added string
orgid string
}
type Ques2 struct {
Content string
}
func init() {
var err error
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)))
if err != 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()
}
func main() {
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()
if err != nil {
// Handle error
panic(err)
}
}
func getFromMysql() map[string]string {
record := make(map[string]string)
rows, err := db.Query("SELECT * FROM q_questions limit 998, 1")
defer rows.Close()
//checkErr(err)
if err != nil {
fmt.Println(err)
return record
}
columns, _ := rows.Columns()
scanArgs := make([]interface{}, len(columns))
values := make([]interface{}, len(columns))
for j := range values {
scanArgs[j] = &values[j]
}
for rows.Next() {
//将行数据保存到record字典
err = rows.Scan(scanArgs...)
for i, col := range values {
if col != nil {
record[columns[i]] = string(col.([]byte))
}
}
}
return record
}
/**
* 从es搜索
*/
func esSearch() {
termQuery := elastic.NewTermQuery("content", "中国")
searchResult, err := client.Search().
Index("ikindex").Type("fulltext"). // search in index "twitter"
Query(termQuery). // specify the query
//Sort("user", true). // sort by "user" field, ascending
From(0).Size(10). // take documents 0-9
Pretty(true). // pretty print request and response JSON
Do() // execute
if err != nil {
// Handle error
panic(err)
}
// searchResult is of type SearchResult and returns hits, suggestions,
// and all kinds of other information from Elasticsearch.
fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
fmt.Println(searchResult.Hits.TotalHits)
fmt.Println("Hello World!")
}