Files
2022-01-18 16:29:29 +08:00

99 lines
2.0 KiB
Go

package es
import (
"SciencesServer/utils"
"context"
"encoding/json"
"fmt"
"github.com/olivere/elastic/v7"
"testing"
)
var (
dataIndex = "test"
//client *elastic.Client
host = "http://192.168.0.188:9200"
)
type Student struct {
ID uint64 `json:"id"`
Name string `json:"name"`
Age int64 `json:"age"`
}
func _new() *elastic.Client {
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 {
panic(err)
}
return client
}
func TestNewInstanceCreate(t *testing.T) {
client := _new()
//client.Delete()
src := Student{ID: 2, Name: "henry", Age: 28}
client.Index().Index("student").Id(fmt.Sprintf("%d", src.ID)).BodyJson(utils.AnyToJSON(src)).
Do(context.Background())
}
func TestNewInstanceUpdate(t *testing.T) {
client := _new()
//client.Delete()
src := &Student{ID: 1, Name: "Henry", Age: 28}
_, err := client.Update().Index("student").Id(fmt.Sprintf("%d", src.ID)).Doc(map[string]interface{}{
"age": 29,
}).Do(context.Background())
t.Log(err)
}
func TestNewInstanceSearch(t *testing.T) {
client := _new()
//client.Delete()
query := elastic.NewBoolQuery()
//query.Must(elastic.NewMatchQuery("age", "27"))
service := client.Search().Index("student")
result, err := service.Pretty(true).Query(query).Do(context.Background())
t.Log(err)
t.Log(utils.AnyToJSON(result))
src := new(Student)
for _, hit := range result.Hits.Hits {
if err = json.Unmarshal(hit.Source, src); err != nil {
t.Log(err)
return
}
fmt.Println(utils.AnyToJSON(src))
}
}
func TestNewInstance2(t *testing.T) {
client := _new()
query := elastic.NewBoolQuery()
query.Must(elastic.NewMatchQuery("title", "一种"))
query.Must(elastic.NewMatchPhraseQuery("industry", "你是"))
service := client.Search().Index("es_patent_index")
result, err := service.Pretty(true).Query(query).Do(context.Background())
if err != nil {
panic(err)
}
for _, v := range result.Hits.Hits {
t.Log(string(v.Source))
}
}