File: main.go

package info (click to toggle)
golang-github-meilisearch-meilisearch-go 0.34.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,084 kB
  • sloc: makefile: 9
file content (146 lines) | stat: -rw-r--r-- 4,251 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/meilisearch/meilisearch-go"
)

func main() {
	// Initialize the Meilisearch client
	host := getenv("MEILI_HOST", "http://localhost:7700")
	apiKey := os.Getenv("MEILI_API_KEY")
	client := meilisearch.New(host, meilisearch.WithAPIKey(apiKey))
	defer client.Close()

	// Test connection
	fmt.Println("Testing connection to Meilisearch...")
	if !client.IsHealthy() {
		log.Fatal("Meilisearch is not available")
	}
	fmt.Println("āœ… Connected to Meilisearch")

	fmt.Println("\nšŸ—ļø  Index Creation and Settings Examples")
	fmt.Println("========================================")

	// 1. Create basic index
	fmt.Println("1. Creating basic index:")
	indexUID := "articles"
	task, err := client.CreateIndex(&meilisearch.IndexConfig{
		Uid:        indexUID,
		PrimaryKey: "id",
	})
	if err != nil {
		log.Printf("Index might already exist: %v", err)
	} else {
		if err := waitForTask(client, task.TaskUID); err != nil {
			log.Fatalf("Failed to create index: %v", err)
		}
		fmt.Printf("āœ… Created index '%s' (Task ID: %d)\n", indexUID, task.TaskUID)
	}

	index := client.Index(indexUID)

	// 2. Configure comprehensive settings
	fmt.Println("\n2. Configuring index settings:")
	settings := &meilisearch.Settings{
		// Searchable attributes - fields that are searched
		SearchableAttributes: []string{"title", "content", "author", "tags"},
		
		// Displayed attributes - fields returned in search results
		DisplayedAttributes: []string{"id", "title", "author", "publish_date", "category", "summary"},
		
		// Filterable attributes - fields that can be used in filters
		FilterableAttributes: []string{"category", "author", "publish_date", "status", "featured"},
		
		// Sortable attributes - fields that can be used for sorting
		SortableAttributes: []string{"publish_date", "title", "author"},
		
		// Ranking rules - control result relevance
		RankingRules: []string{
			"words",
			"typo", 
			"proximity",
			"attribute",
			"sort",
			"exactness",
		},
		
		// Stop words - words ignored during search
		StopWords: []string{"the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with", "by"},
		
		// Synonyms - alternative words
		Synonyms: map[string][]string{
			"programming": {"coding", "development"},
			"javascript":  {"js", "ecmascript"},
			"golang":      {"go"},
		},
		
		// Distinct attribute - deduplicate results
		DistinctAttribute: stringPtr("title"),
		
		// Typo tolerance settings
		TypoTolerance: &meilisearch.TypoTolerance{
			Enabled: true,
			MinWordSizeForTypos: meilisearch.MinWordSizeForTypos{
				OneTypo:  5,
				TwoTypos: 9,
			},
		},
		
		// Pagination settings
		Pagination: &meilisearch.Pagination{
			MaxTotalHits: 1000,
		},
	}

	settingsTask, err := index.UpdateSettings(settings)
	if err != nil {
		log.Fatalf("Failed to update settings: %v", err)
	}
	
	if err := waitForTask(client, settingsTask.TaskUID); err != nil {
		log.Fatalf("Failed to wait for settings update: %v", err)
	}
	fmt.Printf("āœ… Updated index settings (Task ID: %d)\n", settingsTask.TaskUID)

	// 3. Retrieve and display current settings
	fmt.Println("\n3. Current index settings:")
	currentSettings, err := index.GetSettings()
	if err != nil {
		log.Fatalf("Failed to get settings: %v", err)
	}
	
	fmt.Printf("Searchable attributes: %v\n", currentSettings.SearchableAttributes)
	fmt.Printf("Filterable attributes: %v\n", currentSettings.FilterableAttributes)
	fmt.Printf("Sortable attributes: %v\n", currentSettings.SortableAttributes)

	fmt.Println("\nIndex creation and settings examples completed successfully! šŸŽ‰")
}

// waitForTask waits for a task to complete
func waitForTask(client meilisearch.ServiceManager, taskUID int64) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	_, err := client.WaitForTaskWithContext(ctx, taskUID, 100*time.Millisecond)
	return err
}

// stringPtr returns a pointer to a string
func stringPtr(s string) *string {
	return &s
}

// getenv returns the value of the environment variable named by the key,
// or def if the variable is not present or empty.
func getenv(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}