github.com/sereiner/library@v0.0.0-20200518095232-1fa3e640cc5f/elastic/elastic_test.go (about)

     1  package elastic
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"reflect"
     7  	"testing"
     8  
     9  	"github.com/olivere/elastic"
    10  )
    11  
    12  type SpuItem struct {
    13  	Author           string             `json:"author"`
    14  	CategoryID       int                `json:"category_id"`
    15  	DescriptionUnits []*DescriptionUnit `json:"description_units"`
    16  	ID               string             `json:"id"`
    17  	Isbn             string             `json:"isbn"`
    18  	Status           int                `json:"status"`
    19  	Stock            int                `json:"stock"`
    20  	SubTitle         string             `json:"sub_title"`
    21  	Tags             []string           `json:"tags"`
    22  	Title            string             `json:"title"`
    23  	Image            string             `json:"image"`
    24  	OriginalPrice    string             `json:"original_price"`
    25  	SellingPrice     string             `json:"selling_price"`
    26  }
    27  
    28  type DescriptionUnit struct {
    29  	Name  string `json:"name"`
    30  	Value string `json:"value"`
    31  }
    32  
    33  func TestNew(t *testing.T) {
    34  	es, err := New(ESConfigOption{
    35  		Host:  []string{"http://39.98.58.40:9200/"},
    36  		Index: "spu",
    37  		Type:  "spu",
    38  		Sniff: false,
    39  	})
    40  	if err != nil {
    41  		t.Log(err)
    42  	}
    43  
    44  	keyword := "中国文学"
    45  
    46  	boolQuery := elastic.NewBoolQuery()
    47  	// boolQuery.Must(elastic.NewMatchQuery("status", 1))
    48  	boolQuery.Should(elastic.NewMatchPhraseQuery("tags", keyword))
    49  	fmt.Println(boolQuery.Source())
    50  	datas, err := es.Conn.Search().
    51  		Index("spu").
    52  		Type("spu").
    53  		Query(boolQuery).
    54  		Do(context.Background())
    55  	if err != nil {
    56  		return
    57  	}
    58  
    59  	fmt.Println(datas.Profile)
    60  
    61  	var typ SpuItem
    62  	for k, item := range datas.Each(reflect.TypeOf(typ)) { //从搜索结果中取数据的方法
    63  		t := item.(SpuItem)
    64  		fmt.Printf("key:%v,%#v\n", k, t)
    65  	}
    66  }