Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions go/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ Install these dependencies using the go build command.
```bash
go build
```

If you plan to access the Analytics API, please run this command, too.

```bash
go get github.com/algolia/algoliasearch-client-go
```

Once setup, you can run each of the script in this folder using the Go command line.
Example: to execute the `simple.go` script:

Expand All @@ -46,4 +53,9 @@ go run simple.go
| ------------- | ------------- |
| [simple.go](./simple.go) | Index a single object and run a search query |
| [indexing.go](./indexing.go) | Showcase of the main indexing methods |
| [change-index-settings.go](./change-index-settings.go) | Change index settings |
| [rules.go](./rules.go) | Export rules and add a new rule to an index |
| [backup.go](./backup.go) | Backup an index |
| [restore.go](./restore.go) | Restore an index |
| [return_top_hits.go](./rest_api_return_top_hits.go) | Get top 1000 searches with Analytics REST API |
| [generate_key.go](./generate_key.go) | Generate a rate limted search API key |
171 changes: 171 additions & 0 deletions go/backup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
package main

import (
"fmt"
"log"
"os"
"github.com/algolia/algoliasearch-client-go/v4/algolia/search"
"github.com/joho/godotenv"
"encoding/json"
)

func PrintErrAndExit(err error) {
fmt.Println(err)
os.Exit(1)
}


func PrintCurrentObjects() {
appID, apiKey, indexName := os.Getenv("ALGOLIA_APP_ID"), os.Getenv("ALGOLIA_API_KEY"), os.Getenv("ALGOLIA_INDEX_NAME")
client, err := search.NewClient(appID, apiKey)
if err != nil {
// The client can fail to initialize if you pass an invalid parameter.
fmt.Printf("Client error")
panic(err)
}
resSearch, err := client.SearchSingleIndex(client.NewApiSearchSingleIndexRequest(indexName))
if err != nil {
// handle the eventual error
panic(err)
}
fmt.Println("Current objects: ", resSearch.Hits, "\n")
}

func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
// Algolia client credentials
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/libraries/sdk/methods/search#go
client, err := search.NewClient(appID, apiKey)
if err != nil {
// The client can fail to initialize if you pass an invalid parameter.
fmt.Printf("Client error")
panic(err)
}

// Get all records from an index
// https://www.algolia.com/doc/api-reference/api-methods/browse/#get-all-records-from-an-index
// Use an API key with `browse` ACL
resBrowseObj, err := client.Browse(client.NewApiBrowseRequest(
indexName))

if err != nil {
// handle the eventual error
panic(err)
}

fmt.Println("Current objects")
PrintCurrentObjects()

// Encode array to json
resEncodeObjJson, err := json.Marshal(resBrowseObj.Hits)
if err != nil {
log.Fatal(err)
}

// Write json to file
err = os.WriteFile(indexName + "_records.json", resEncodeObjJson, 0644) // 0644 gives read/write permissions for the owner, and read for others
if err != nil {
log.Fatalf("Error writing to file: %v", err)
}

// Retrieve settings for an index
// https://www.algolia.com/doc/api-reference/api-methods/get-settings/#retrieve-settings-for-an-index
resGetSettings, err := client.GetSettings(client.NewApiGetSettingsRequest(
indexName).WithGetVersion(2))
if err != nil {
// handle the eventual error
panic(err)
}

fmt.Println("Current settings")
fmt.Println(resGetSettings)

// Encode array to json
resEncodeSettingsJson, err := json.Marshal(resGetSettings)
if err != nil {
log.Fatal(err)
}

// Write json to file
err = os.WriteFile(indexName + "_settings.json", resEncodeSettingsJson, 0644) // 0644 grants read/write permissions for the owner
if err != nil {
log.Fatalf("Error writing to file: %v", err)
}

// Export rules
// https://www.algolia.com/doc/api-reference/api-methods/export-rules/
var rules []search.Rule

err = client.BrowseRules(
indexName,
*search.NewEmptySearchRulesParams(),
search.WithAggregator(func(r any, err error) {
if err != nil {
log.Fatalf("There was an error: %v", err)
}

rules = append(rules, r.(*search.SearchRulesResponse).Hits...)
}),
)
if err != nil {
log.Fatal(err)
}

fmt.Println("Current rules:")
for _, rule := range rules {
fmt.Printf("- Rule: %s\n", rule.ObjectID)
}

// Encode array to json
resEncodeRulesJson, err := json.Marshal(rules)
if err != nil {
log.Fatal(err)
}

// Write json to file
err = os.WriteFile(indexName + "_rules.json", resEncodeRulesJson, 0644) // 0644 grants read/write permissions for the owner
if err != nil {
log.Fatalf("Error writing to file: %v", err)
}

// Export synonyms
// https://www.algolia.com/doc/api-reference/api-methods/export-synonyms/
var synonyms []search.SynonymHit

err = client.BrowseSynonyms(
indexName,
*search.NewEmptySearchSynonymsParams(),
search.WithAggregator(func(r any, err error) {
if err != nil {
log.Fatalf("There was an error: %v", err)
}

synonyms = append(synonyms, r.(*search.SearchSynonymsResponse).Hits...)
}),
)
if err != nil {
log.Fatal(err)
}

for _, synonym := range synonyms {
fmt.Printf("- Synonym: %s\n", synonym.ObjectID)
}

// Encode array to json
resEncodeSynonymsJson, err := json.Marshal(synonyms)
if err != nil {
log.Fatal(err)
}

// Write json to file
err = os.WriteFile(indexName + "_synonyms.json", resEncodeSynonymsJson, 0644) // 0644 grants read/write permissions for the owner
if err != nil {
log.Fatalf("Error writing to file: %v", err)
}
}
60 changes: 60 additions & 0 deletions go/change_index_settings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"fmt"
"log"
"os"
"github.com/algolia/algoliasearch-client-go/v4/algolia/search"
"github.com/joho/godotenv"
)

func PrintErrAndExit(err error) {
fmt.Println(err)
os.Exit(1)
}

func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
// Algolia client credentials
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/libraries/sdk/methods/search#go
client, err := search.NewClient(appID, apiKey)
if err != nil {
// The client can fail to initialize if you pass an invalid parameter.
fmt.Printf("Client error")
panic(err)
}

//Setting settings
//https://www.algolia.com/doc/libraries/sdk/methods/search/set-settings
resSetSettings, err := client.SetSettings(client.NewApiSetSettingsRequest(
indexName,
search.NewEmptyIndexSettings().SetSearchableAttributes(
[]string{"actors", "genre"},
)).WithForwardToReplicas(true),
)
if err != nil {
PrintErrAndExit(err)
}
_, err = client.WaitForTask(indexName, resSetSettings.TaskID)
if err != nil {
PrintErrAndExit(err)
}

//Printing settings
//https://www.algolia.com/doc/api-reference/api-methods/get-settings/
fmt.Println("Index settings:")
resGetSettings, err := client.GetSettings(client.NewApiGetSettingsRequest(
indexName).WithGetVersion(2))
if err != nil {
// handle the eventual error
panic(err)
}

fmt.Println(resGetSettings)
}
66 changes: 36 additions & 30 deletions go/generate_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,66 +10,72 @@ import (
"fmt"
"log"
"os"

"github.com/algolia/algoliasearch-client-go/v3/algolia/search"
"github.com/algolia/algoliasearch-client-go/v4/algolia/search"
"github.com/joho/godotenv"
)

func main() {
var err error

err = godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
if err := godotenv.Load(); err != nil {
log.Fatalf("godotenv.Load: %v", err)
}
// 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:

// Algolia client credentials
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)
// https://www.algolia.com/doc/libraries/sdk/methods/search#go
client, err := search.NewClient(appID, apiKey)
if err != nil {
// The client can fail to initialize if you pass an invalid parameter.
fmt.Printf("Client error")
panic(err)
}

// Create the API key.
// https://www.algolia.com/doc/api-reference/api-methods/add-api-key/?client=go
fmt.Println("Generating key...")

keyParams := search.Key{
ACL: []string{"search"},
Description: "Restricted search-only API key for algolia.com",
MaxQueriesPerIPPerHour: 100,
}

var key string
var keyRes search.CreateKeyRes

keyRes, err = client.AddAPIKey(keyParams)
err = keyRes.Wait()
keyRes, err := client.AddApiKey(client.NewApiAddApiKeyRequest(
search.NewEmptyApiKey().SetAcl(
[]search.Acl{search.Acl("search")}).SetDescription("Restricted search-only API key for algolia.com")))
if err != nil {
panic(errors.New("Error generating key."))
} else {
key = keyRes.Key
fmt.Println("Key generated successfully:", key)
}

// Wait for API key
// https://www.algolia.com/doc/libraries/sdk/methods/search/wait-for-api-key
resWaitForKey, err := client.WaitForApiKey(
key, search.ApiKeyOperation("add"))
if err != nil {
// handle the eventual error
panic(err)
} else {
fmt.Println("Task is complete.")
fmt.Println(resWaitForKey)
}

// Test the new key
fmt.Println("Testing key...")

// Initialise a new client with the generated key
client = search.NewClient(appID, key)

// 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)
newClient, err := search.NewClient(appID, key)
if err != nil {
// The client can fail to initialize if you pass an invalid parameter.
fmt.Printf("Client error")
panic(err)
}

// Search the index with an empty string
// https://www.algolia.com/doc/api-reference/api-methods/search/
var indexRes search.QueryRes

indexRes, err = index.Search("")
indexRes, err := newClient.SearchSingleIndex(newClient.NewApiSearchSingleIndexRequest(indexName))
if err != nil {
panic(errors.New("Error testing key."))
fmt.Println(err)
} else {
fmt.Println("Key tested successfully.", indexRes.NbHits, "hits found.")
fmt.Println("Key tested successfully.", len(indexRes.Hits), "hits found.")
}
}
13 changes: 11 additions & 2 deletions go/go.mod
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
module github.com/algolia-samples/api-clients-quickstart

go 1.16
go 1.21.11

require github.com/algolia/algoliasearch-client-go/v3 v3.4.0

require (
github.com/algolia/algoliasearch-client-go/v3 v3.4.0
github.com/algolia/algoliasearch-client-go v2.25.0+incompatible // indirect
github.com/algolia/algoliasearch-client-go/v4 v4.34.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/joho/godotenv v1.4.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.1.0 // indirect
github.com/stretchr/testify v1.4.0 // indirect
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 // indirect
gopkg.in/yaml.v2 v2.2.2 // indirect
)
4 changes: 4 additions & 0 deletions go/go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
github.com/algolia/algoliasearch-client-go v2.25.0+incompatible h1:FGQr9l++u4uQPDXrW8jM5kNJm3Iw5SxEJJtYXSFmPRY=
github.com/algolia/algoliasearch-client-go v2.25.0+incompatible/go.mod h1:4NR25U+0vkfx/0J5l+kOHJ1iPnqOTTBxfd3aALKU+aw=
github.com/algolia/algoliasearch-client-go/v3 v3.4.0 h1:eeVU30L5DkKUK2q/EjXw+8o7reoK4QB1mS+BG0Jbd4Y=
github.com/algolia/algoliasearch-client-go/v3 v3.4.0/go.mod h1:d0/D54BCmkwhLxT5VIQBeYLAz2GbZHFX9OptYyohTr0=
github.com/algolia/algoliasearch-client-go/v4 v4.34.1 h1:I7LDIRpyrhYG5FYb5NM7aYbZ/OTUBb6d94NSw2qdEDY=
github.com/algolia/algoliasearch-client-go/v4 v4.34.1/go.mod h1:2bHeze2/5+jvT8IYVq8j2NDLr/4R6erGxgud7ESuXww=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down
Loading