-
Notifications
You must be signed in to change notification settings - Fork 51
/
simple.go
69 lines (58 loc) · 1.88 KB
/
simple.go
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
package main
// Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/go/?client=go
import (
"fmt"
"os"
"github.com/algolia/algoliasearch-client-go/v3/algolia/search"
"github.com/joho/godotenv"
"log"
)
type Contact struct {
ObjectID string `json:"objectID"`
Name string `json:"name"`
}
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
// Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys
// and choose a name for your index. Add these environment variables to a `.env` file:
appID, apiKey, indexName := os.Getenv("ALGOLIA_APP_ID"), os.Getenv("ALGOLIA_API_KEY"), os.Getenv("ALGOLIA_INDEX_NAME")
// Start the API client
// https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/
client := search.NewClient(appID, apiKey)
// Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists)
// https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index
index := client.InitIndex(indexName)
// Add new objects to the index
// https://www.algolia.com/doc/api-reference/api-methods/add-objects/
resSave, err := index.SaveObjects([]Contact{
{ObjectID: "1", Name: "Foo"},
})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Wait for the indexing task to complete
// https://www.algolia.com/doc/api-reference/api-methods/wait-task/
err = resSave.Wait()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search the index for "Fo"
// https://www.algolia.com/doc/api-reference/api-methods/search/
res, err := index.Search("Foo")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var contacts []Contact
err = res.UnmarshalHits(&contacts)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("search results: ", contacts)
}