Files
2021-12-22 14:11:14 +08:00

103 lines
2.1 KiB
Go

package es
import (
"context"
"encoding/json"
"fmt"
"github.com/olivere/elastic/v7"
"strings"
"testing"
)
var (
dataIndex = "test"
//client *elastic.Client
host = "http://192.168.0.188:9200"
)
type Student struct {
Name string `json:"name"`
Age int64 `json:"age"`
AverageScore float64 `json:"average_score"`
}
func TestNewInstance(t *testing.T) {
client, err := elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(host))
if err != nil {
panic(err)
}
if _, _, err = client.Ping(host).Do(context.Background()); err != nil {
t.Log(err)
return
}
//newStudent := Student{
// Name: "熊,桥,顺",
// Age: 10,
// AverageScore: 99.9,
//}
//dataJSON, _ := json.Marshal(newStudent)
//
//_, err = client.Index().
// Index("students").
// BodyJson(string(dataJSON)).
// Do(context.Background())
//
//if err != nil {
// panic(err)
//}
var students []Student
searchSource := elastic.NewSearchSource()
searchSource.Query(elastic.NewMatchQuery("name", "顺"))
queryStr, _ := searchSource.Source()
queryJs, _ := json.Marshal(queryStr)
fmt.Println("[esclient]Final ESQuery=\n", string(queryJs))
searchService := client.Search().Index("students").SearchSource(searchSource)
searchResult, err1 := searchService.Do(context.Background())
if err1 != nil {
fmt.Println("[ProductsES][GetPIds]Error=", err1)
return
}
for _, hit := range searchResult.Hits.Hits {
var student Student
err := json.Unmarshal(hit.Source, &student)
if err != nil {
fmt.Println("[Getting Students][Unmarshal] Err=", err)
}
students = append(students, student)
}
t.Log(students)
}
func TestNewInstance1(t *testing.T) {
NewInstance(
WithEsAddress([]string{"http://192.168.0.188:9200"}),
).Init().Local()
var b strings.Builder
b.WriteString(`{"title" : "`)
b.WriteString("我是好人")
b.WriteString(`"}`)
//resp, err := client.Create(dataIndex, "2", strings.NewReader(b.String()))
//t.Log(err)
//t.Log(resp)
}
func TestNewInstance2(t *testing.T) {
NewInstance(
WithEsAddress([]string{"http://192.168.0.188:9200"}),
).Init().Local()
//client.Search(func(request *esapi.SearchRequest) {
//
//})
}