meilisearch/README.md

1.7 KiB

meilisearch

package main

import (
	"fmt"
	"git.selly.red/Selly-Modules/logger"
	"git.selly.red/Selly-Modules/meilisearch"
)

func main() {
	logger.Init("demo", "hello")

	if err := meilisearch.Connect(meilisearch.Config{
		URL:    "http://localhost:7700",
		APIKey: "meili_key",
	}); err != nil {
		panic(err)
	}

	demo()
}

func demo() {
	type Player struct {
		ID     string `json:"_id"`
		Name   string `json:"name"`
		Age    int    `json:"age"`
		Number int    `json:"number"`
	}

	var index = meilisearch.Index{
		Name: "player",
	}

	if err := index.Create(); err != nil {
		fmt.Println("error when create index")
		panic(err)
	}

	if err := index.UpdateSettings(meilisearch.IndexSettings{
		SearchableAttributes: []string{"name"},
		FilterableAttributes: []string{"age"},
		SortableAttributes:   []string{"number"},
	}); err != nil {
		fmt.Println("error when update index setting")
		panic(err)
	}

	if err := index.AddDocuments([]Player{
		{ID: "1", Name: "Messi", Age: 34, Number: 30},
		{ID: "2", Name: "Ronaldo", Age: 37, Number: 7},
		{ID: "3", Name: "Kevin De Bruyne", Age: 30, Number: 17},
		{ID: "4", Name: "Ronaldo De Lima", Age: 46, Number: 10},
	}); err != nil {
		fmt.Println("error when insert documents")
		panic(err)
	}

	var data = make([]Player, 0)
	total, err := meilisearch.Search("player", meilisearch.SearchPayload{
		Query: "ronaldo",
		Filter: [][]string{
			[]string{"age > 40"},
		},
		Pagination: meilisearch.SearchPagination{
			Offset: 0,
			Limit:  5,
		},
		Sort: nil,
	}, &data)

	fmt.Println("total", total)
	fmt.Println("err", err)
	fmt.Println("data", data)

	//if err := index.DeleteDocumentsByPrimaryKeys([]string{"2", "3"}); err != nil {
	//	fmt.Println("error when delete documents")
	//	panic(err)
	//}
}