From 6ed1acb13d281c0602b758dea75a770c4ecc1ae1 Mon Sep 17 00:00:00 2001 From: Jakob Hahn <jakob.hahn@hetzner.com> Date: Mon, 20 Nov 2023 16:22:24 +0100 Subject: [PATCH] samples: add sample files Signed-off-by: Jakob Hahn <jakob.hahn@hetzner.com> --- _samples/README.md | 21 +++ _samples/advanced_index_actions.go | 190 ++++++++++++++++++++ _samples/bulk.go | 175 +++++++++++++++++++ _samples/data_stream.go | 101 +++++++++++ _samples/document_lifecycle.go | 269 +++++++++++++++++++++++++++++ _samples/index_lifecycle.go | 130 ++++++++++++++ _samples/json.go | 125 ++++++++++++++ _samples/search.go | 259 +++++++++++++++++++++++++++ 8 files changed, 1270 insertions(+) create mode 100644 _samples/README.md create mode 100644 _samples/advanced_index_actions.go create mode 100644 _samples/bulk.go create mode 100644 _samples/data_stream.go create mode 100644 _samples/document_lifecycle.go create mode 100644 _samples/index_lifecycle.go create mode 100644 _samples/json.go create mode 100644 _samples/search.go diff --git a/_samples/README.md b/_samples/README.md new file mode 100644 index 000000000..4617a896f --- /dev/null +++ b/_samples/README.md @@ -0,0 +1,21 @@ +# OpenSearch Golang Samples + +Most samples can be run using OpenSearch installed locally with docker. + +Start container: + +``` +make cluster.build cluster.start +``` + +Stop and cleanup: + +``` +make cluster.stop cluster.clean +``` + +## Run Samples + +``` +go run _samples/json.go +``` diff --git a/_samples/advanced_index_actions.go b/_samples/advanced_index_actions.go new file mode 100644 index 000000000..aff9010aa --- /dev/null +++ b/_samples/advanced_index_actions.go @@ -0,0 +1,190 @@ +package main + +import ( + "context" + "fmt" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) + +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + ctx := context.Background() + exampleIndex := "movies" + + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: exampleIndex}) + if err != nil { + return err + } + fmt.Printf("Index created: %t\n", createResp.Acknowledged) + + clearCacheResp, err := client.Indices.ClearCache(ctx, &opensearchapi.IndicesClearCacheReq{Indices: []string{exampleIndex}}) + if err != nil { + return err + } + fmt.Printf("Cach cleared for %d shards\n", clearCacheResp.Shards.Total) + + clearCacheResp, err = client.Indices.ClearCache( + ctx, + &opensearchapi.IndicesClearCacheReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.IndicesClearCacheParams{ + Fielddata: opensearchapi.ToPointer(true), + Request: opensearchapi.ToPointer(true), + Query: opensearchapi.ToPointer(true), + }, + }, + ) + if err != nil { + return err + } + fmt.Printf("Cach cleared for %d shards\n", clearCacheResp.Shards.Total) + + flushResp, err := client.Indices.Flush(ctx, &opensearchapi.IndicesFlushReq{Indices: []string{exampleIndex}}) + if err != nil { + return err + } + fmt.Printf("Flushed shards: %d\n", flushResp.Shards.Total) + + refreshResp, err := client.Indices.Refresh(ctx, &opensearchapi.IndicesRefreshReq{Indices: []string{exampleIndex}}) + if err != nil { + return err + } + fmt.Printf("Refreshed shards: %d\n", refreshResp.Shards.Total) + + closeResp, err := client.Indices.Close(ctx, opensearchapi.IndicesCloseReq{Index: exampleIndex}) + if err != nil { + return err + } + fmt.Printf("Index closed: %t\n", closeResp.Acknowledged) + + openResp, err := client.Indices.Open(ctx, opensearchapi.IndicesOpenReq{Index: exampleIndex}) + if err != nil { + return err + } + fmt.Printf("Index opended: %t\n", openResp.Acknowledged) + + mergeResp, err := client.Indices.Forcemerge( + ctx, + &opensearchapi.IndicesForcemergeReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.IndicesForcemergeParams{ + MaxNumSegments: opensearchapi.ToPointer(1), + }, + }, + ) + if err != nil { + return err + } + fmt.Printf("Forcemerged Shards: %d\n", mergeResp.Shards.Total) + + blockResp, err := client.Indices.Block( + ctx, + opensearchapi.IndicesBlockReq{ + Indices: []string{exampleIndex}, + Block: "write", + }, + ) + if err != nil { + return err + } + fmt.Printf("Index write blocked: %t\n", blockResp.Acknowledged) + + cloneResp, err := client.Indices.Clone( + ctx, + opensearchapi.IndicesCloneReq{ + Index: exampleIndex, + Target: "movies_cloned", + }, + ) + if err != nil { + return err + } + fmt.Printf("Cloned: %t\n", cloneResp.Acknowledged) + + settingResp, err := client.Indices.Settings.Put( + ctx, + opensearchapi.SettingsPutReq{ + Indices: []string{exampleIndex}, + Body: strings.NewReader(`{"index":{"blocks":{"write":null}}}`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Settings updated: %t\n", settingResp.Acknowledged) + + createResp, err = client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: "books", + Body: strings.NewReader(`{ + "settings": { + "index": { + "number_of_shards": 5, + "number_of_routing_shards": 30, + "blocks": { + "write": true + } + } + } + }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Index created: %t\n", createResp.Acknowledged) + + splitResp, err := client.Indices.Split( + ctx, + opensearchapi.IndicesSplitReq{ + Index: "books", + Target: "books-large", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards": 10}}}`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Index splited: %t\n", splitResp.Acknowledged) + + settingResp, err = client.Indices.Settings.Put( + ctx, + opensearchapi.SettingsPutReq{ + Indices: []string{"books"}, + Body: strings.NewReader(`{"index":{"blocks":{"write":null}}}`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Settings updated: %t\n", settingResp.Acknowledged) + + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"movies*", "books*"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) + + return nil +} diff --git a/_samples/bulk.go b/_samples/bulk.go new file mode 100644 index 000000000..77763f6cd --- /dev/null +++ b/_samples/bulk.go @@ -0,0 +1,175 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) + +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + ctx := context.Background() + + movies := "movies" + books := "books" + + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: movies}) + if err != nil { + return err + } + fmt.Printf("Index created: %t\n", createResp.Acknowledged) + + createResp, err = client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: books}) + if err != nil { + return err + } + fmt.Printf("Index created: %t\n", createResp.Acknowledged) + + bulkResp, err := client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader(`{ "index": { "_index": "movies", "_id": 1 } } +{ "title": "Beauty and the Beast", "year": 1991 } +{ "index": { "_index": "movies", "_id": 2 } } +{ "title": "Beauty and the Beast - Live Action", "year": 2017 } +{ "index": { "_index": "books", "_id": 1 } } +{ "title": "The Lion King", "year": 1994 } +`), + }, + ) + if err != nil { + return err + } + respAsJson, err := json.MarshalIndent(bulkResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Bulk Resp:\n%s\n", string(respAsJson)) + + bulkResp, err = client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader(`{ "create": { "_index": "movies" } } +{ "title": "Beauty and the Beast 2", "year": 2030 } +{ "create": { "_index": "movies", "_id": 1 } } +{ "title": "Beauty and the Beast 3", "year": 2031 } +{ "create": { "_index": "movies", "_id": 2 } } +{ "title": "Beauty and the Beast 4", "year": 2049 } +{ "create": { "_index": "books" } } +{ "title": "The Lion King 2", "year": 1998 } +`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(bulkResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Bulk Resp:\n%s\n", string(respAsJson)) + + bulkResp, err = client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader(`{ "update": { "_index": "movies", "_id": 1 } } +{ "doc": { "year": 1992 } } +{ "update": { "_index": "movies", "_id": 1 } } +{ "doc": { "year": 2018 } } +`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(bulkResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Bulk Resp:\n%s\n", string(respAsJson)) + + bulkResp, err = client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader(`{ "delete": { "_index": "movies", "_id": 1 } } +{ "delete": { "_index": "movies", "_id": 2 } } +`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(bulkResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Bulk Resp:\n%s\n", string(respAsJson)) + + bulkResp, err = client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader(`{ "create": { "_index": "movies", "_id": 3 } } +{ "title": "Beauty and the Beast 5", "year": 2050 } +{ "create": { "_index": "movies", "_id": 4 } } +{ "title": "Beauty and the Beast 6", "year": 2051 } +{ "update": { "_index": "movies", "_id": 3 } } +{ "doc": { "year": 2052 } } +{ "delete": { "_index": "movies", "_id": 4 } } +`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(bulkResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Bulk Resp:\n%s\n", string(respAsJson)) + + bulkResp, err = client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader("{\"delete\":{\"_index\":\"movies\",\"_id\":1}}\n"), + }, + ) + if err != nil { + return err + } + for _, item := range bulkResp.Items { + for operation, resp := range item { + if resp.Status > 299 { + fmt.Printf("Bulk %s Error: %s\n", operation, resp.Result) + } + } + } + + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"movies", "books"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) + + return nil +} diff --git a/_samples/data_stream.go b/_samples/data_stream.go new file mode 100644 index 000000000..20b4acd74 --- /dev/null +++ b/_samples/data_stream.go @@ -0,0 +1,101 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) + +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + ctx := context.Background() + + tempCreateResp, err := client.IndexTemplate.Create( + ctx, + opensearchapi.IndexTemplateCreateReq{ + IndexTemplate: "books", + Body: strings.NewReader(`{ + "index_patterns": ["books-nonfiction"], + "template": { + "settings": { + "index": { + "number_of_shards": 3, + "number_of_replicas": 0 + } + } + }, + "data_stream": {}, + "priority": 50 + }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Index Tempalte created: %t\n", tempCreateResp.Acknowledged) + + createResp, err := client.DataStream.Create(ctx, opensearchapi.DataStreamCreateReq{DataStream: "books-nonfiction"}) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) + + getResp, err := client.DataStream.Get(ctx, nil) + if err != nil { + return err + } + respAsJson, err := json.MarshalIndent(getResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Get DataStream:\n%s\n", string(respAsJson)) + + getResp, err = client.DataStream.Get(ctx, &opensearchapi.DataStreamGetReq{DataStreams: []string{"books-nonfiction"}}) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(getResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Get DataStream:\n%s\n", string(respAsJson)) + + statsResp, err := client.DataStream.Stats(ctx, nil) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(statsResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Stats DataStream:\n%s\n", string(respAsJson)) + + delResp, err := client.DataStream.Delete(ctx, opensearchapi.DataStreamDeleteReq{DataStream: "books-nonfiction"}) + if err != nil { + return err + } + fmt.Printf("DataStream deleted: %t\n", delResp.Acknowledged) + + delTempResp, err := client.IndexTemplate.Delete(ctx, opensearchapi.IndexTemplateDeleteReq{IndexTemplate: "books"}) + if err != nil { + return err + } + fmt.Printf("Deleted templates: %t\n", delTempResp.Acknowledged) + + return nil +} diff --git a/_samples/document_lifecycle.go b/_samples/document_lifecycle.go new file mode 100644 index 000000000..2b88b7b39 --- /dev/null +++ b/_samples/document_lifecycle.go @@ -0,0 +1,269 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) + +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + ctx := context.Background() + + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: "movies"}) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) + + docCreateResp, err := client.Document.Create( + ctx, + opensearchapi.DocumentCreateReq{ + Index: "movies", + DocumentID: "1", + Body: strings.NewReader(`{"title": "Beauty and the Beast", "year": 1991 }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Document: %s\n", docCreateResp.Result) + + docCreateResp, err = client.Document.Create( + ctx, + opensearchapi.DocumentCreateReq{ + Index: "movies", + DocumentID: "2", + Body: strings.NewReader(`{"title": "Beauty and the Beast - Live Action", "year": 2017 }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Document: %s\n", docCreateResp.Result) + + _, err = client.Document.Create( + ctx, + opensearchapi.DocumentCreateReq{ + Index: "movies", + DocumentID: "2", + Body: strings.NewReader(`{"title": "Just Another Movie" }`), + }, + ) + if err != nil { + fmt.Println(err) + } + + indexResp, err := client.Index( + ctx, + opensearchapi.IndexReq{ + Index: "movies", + DocumentID: "2", + Body: strings.NewReader(`{"title": "Updated Title" }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Document: %s\n", indexResp.Result) + + // + + indexResp, err = client.Index( + ctx, + opensearchapi.IndexReq{ + Index: "movies", + Body: strings.NewReader(`{ "title": "The Lion King 2", "year": 1978}`), + }, + ) + if err != nil { + return err + } + respAsJson, err := json.MarshalIndent(indexResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Index:\n%s\n", respAsJson) + + // + + getResp, err := client.Document.Get(ctx, opensearchapi.DocumentGetReq{Index: "movies", DocumentID: "1"}) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(getResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", respAsJson) + + // + + getResp, err = client.Document.Get( + ctx, + opensearchapi.DocumentGetReq{ + Index: "movies", + DocumentID: "1", + Params: opensearchapi.DocumentGetParams{SourceIncludes: []string{"title"}}, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(getResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", respAsJson) + + getResp, err = client.Document.Get( + ctx, + opensearchapi.DocumentGetReq{ + Index: "movies", + DocumentID: "1", + Params: opensearchapi.DocumentGetParams{SourceExcludes: []string{"title"}}, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(getResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", respAsJson) + + // + + mgetResp, err := client.MGet( + ctx, + opensearchapi.MGetReq{ + Index: "movies", + Body: strings.NewReader(`{ "docs": [{ "_id": "1" }, { "_id": "2" }] }`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(mgetResp, "", " ") + if err != nil { + return err + } + fmt.Printf("MGet Document:\n%s\n", respAsJson) + + // + + existsResp, err := client.Document.Exists(ctx, opensearchapi.DocumentExistsReq{Index: "movies", DocumentID: "1"}) + if err != nil { + return err + } + fmt.Println(existsResp.Status()) + + // + + updateResp, err := client.Update( + ctx, + opensearchapi.UpdateReq{ + Index: "movies", + DocumentID: "1", + Body: strings.NewReader(`{ "script": { "source": "ctx._source.year += 5" } }`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(updateResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Update:\n%s\n", respAsJson) + + // + + _, err = client.Indices.Refresh(ctx, &opensearchapi.IndicesRefreshReq{Indices: []string{"movies"}}) + if err != nil { + return err + } + + upByQueryResp, err := client.UpdateByQuery( + ctx, + opensearchapi.UpdateByQueryReq{ + Indices: []string{"movies"}, + Params: opensearchapi.UpdateByQueryParams{Query: "year:<1990"}, + Body: strings.NewReader(`{"script": { "source": "ctx._source.year -= 1" } }`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(upByQueryResp, "", " ") + if err != nil { + return err + } + fmt.Printf("UpdateByQuery:\n%s\n", respAsJson) + + // + + docDelResp, err := client.Document.Delete(ctx, opensearchapi.DocumentDeleteReq{Index: "movies", DocumentID: "1"}) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(docDelResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Del Doc:\n%s\n", respAsJson) + + // + _, err = client.Indices.Refresh(ctx, &opensearchapi.IndicesRefreshReq{Indices: []string{"movies"}}) + if err != nil { + return err + } + + delByQueryResp, err := client.Document.DeleteByQuery( + ctx, + opensearchapi.DocumentDeleteByQueryReq{ + Indices: []string{"movies"}, + Body: strings.NewReader(`{ "query": { "match": { "title": "The Lion King" } } }`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(delByQueryResp, "", " ") + if err != nil { + return err + } + fmt.Printf("DelByQuery Doc:\n%s\n", respAsJson) + + // + + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"movies", "paintings", "burner"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) + + return nil +} diff --git a/_samples/index_lifecycle.go b/_samples/index_lifecycle.go new file mode 100644 index 000000000..f98b1be1b --- /dev/null +++ b/_samples/index_lifecycle.go @@ -0,0 +1,130 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) + +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + ctx := context.Background() + + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: "paintings"}) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) + + createResp, err = client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: "movies", + Body: strings.NewReader(`{ + "settings": { + "index": { + "number_of_shards": 2, + "number_of_replicas": 1 + } + }, + "mappings": { + "properties": { + "title": { + "type": "text" + }, + "year": { + "type": "integer" + } + } + } + }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) + + _, err = client.Indices.Exists(ctx, opensearchapi.IndicesExistsReq{Indices: []string{"burner"}}) + fmt.Printf("%s\n", err) + + indexResp, err := client.Index(ctx, opensearchapi.IndexReq{Index: "burner", Body: strings.NewReader(`{"foo": "bar"}`)}) + if err != nil { + return err + } + fmt.Printf("Index: %s\n", indexResp.Result) + + existsResp, err := client.Indices.Exists(ctx, opensearchapi.IndicesExistsReq{Indices: []string{"burner"}}) + if err != nil { + return err + } + fmt.Printf("%s\n", existsResp) + + settingsPutResp, err := client.Indices.Settings.Put( + ctx, + opensearchapi.SettingsPutReq{ + Indices: []string{"burner"}, + Body: strings.NewReader(`{"index":{"number_of_replicas":0}}`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Settings updated: %t\n", settingsPutResp.Acknowledged) + + mappingPutResp, err := client.Indices.Mapping.Put( + ctx, + opensearchapi.MappingPutReq{ + Indices: []string{"movies"}, + Body: strings.NewReader(`{"properties":{ "director":{"type":"text"}}}`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Mappings updated: %t\n", mappingPutResp.Acknowledged) + + getResp, err := client.Indices.Get( + ctx, + opensearchapi.IndicesGetReq{ + Indices: []string{"movies"}, + }, + ) + if err != nil { + return err + } + respAsJson, err := json.MarshalIndent(getResp.Indices, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", string(respAsJson)) + + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"movies", "paintings", "burner"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) + + return nil +} diff --git a/_samples/json.go b/_samples/json.go new file mode 100644 index 000000000..4b785a1e6 --- /dev/null +++ b/_samples/json.go @@ -0,0 +1,125 @@ +package main + +import ( + "fmt" + "io/ioutil" + "net/http" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) + +const IndexName = "go-test-index1" + +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + /// + + infoRequest, err := http.NewRequest("GET", "/", nil) + if err != nil { + return err + } + + infoResponse, err := client.Client.Perform(infoRequest) + if err != nil { + return err + } + + resBody, err := ioutil.ReadAll(infoResponse.Body) + if err != nil { + return err + } + fmt.Printf("client info: %s\n", resBody) + + /// + + var index_body = strings.NewReader(`{ + "settings": { + "index": { + "number_of_shards": 2, + "number_of_replicas": 1 + } + }, + "mappings": { + "properties": { + "title": { + "type": "text" + }, + "year": { + "type": "integer" + } + } + } +}`) + + createIndexRequest, err := http.NewRequest("PUT", "/movies", index_body) + if err != nil { + return err + } + createIndexRequest.Header["Content-Type"] = []string{"application/json"} + createIndexResp, err := client.Client.Perform(createIndexRequest) + if err != nil { + return err + } + createIndexRespBody, err := ioutil.ReadAll(createIndexResp.Body) + if err != nil { + return err + } + fmt.Println("create index: ", string(createIndexRespBody)) + + /// + + query := strings.NewReader(`{ + "size": 5, + "query": { + "multi_match": { + "query": "miller", + "fields": ["title^2", "director"] + } + } +}`) + searchRequest, err := http.NewRequest("POST", "/movies/_search", query) + if err != nil { + return err + } + searchRequest.Header["Content-Type"] = []string{"application/json"} + searchResp, err := client.Client.Perform(searchRequest) + if err != nil { + return err + } + searchRespBody, err := ioutil.ReadAll(searchResp.Body) + if err != nil { + return err + } + fmt.Println("search: ", string(searchRespBody)) + + /// + + deleteIndexRequest, err := http.NewRequest("DELETE", "/movies", nil) + if err != nil { + return err + } + deleteIndexResp, err := client.Client.Perform(deleteIndexRequest) + if err != nil { + return err + } + deleteIndexRespBody, err := ioutil.ReadAll(deleteIndexResp.Body) + if err != nil { + return err + } + fmt.Println("delete index: ", string(deleteIndexRespBody)) + + return nil +} diff --git a/_samples/search.go b/_samples/search.go new file mode 100644 index 000000000..b12e288d7 --- /dev/null +++ b/_samples/search.go @@ -0,0 +1,259 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + "strconv" + "strings" + "time" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) + +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + ctx := context.Background() + exampleIndex := "movies" + + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: exampleIndex}) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) + + for i := 1; i < 11; i++ { + _, err = client.Index( + ctx, + opensearchapi.IndexReq{ + Index: exampleIndex, + DocumentID: strconv.Itoa(i), + Body: strings.NewReader(fmt.Sprintf(`{"title": "The Dark Knight %d", "director": "Christopher Nolan", "year": %d}`, i, 2008+i)), + }, + ) + if err != nil { + return err + } + } + + _, err = client.Index( + ctx, + opensearchapi.IndexReq{ + Index: exampleIndex, + Body: strings.NewReader(`{"title": "The Godfather", "director": "Francis Ford Coppola", "year": 1972}`), + }, + ) + if err != nil { + return err + } + + _, err = client.Index( + ctx, + opensearchapi.IndexReq{ + Index: exampleIndex, + Body: strings.NewReader(`{"title": "The Shawshank Redemption", "director": "Frank Darabont", "year": 1994}`), + }, + ) + if err != nil { + return err + } + + _, err = client.Indices.Refresh(ctx, &opensearchapi.IndicesRefreshReq{Indices: []string{exampleIndex}}) + if err != nil { + return err + } + + searchResp, err := client.Search(ctx, &opensearchapi.SearchReq{Indices: []string{exampleIndex}}) + if err != nil { + return err + } + respAsJson, err := json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) + + // + + searchResp, err = client.Search( + ctx, + &opensearchapi.SearchReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.SearchParams{Query: `title: "dark knight"`}, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) + + // + + searchResp, err = client.Search( + ctx, + &opensearchapi.SearchReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.SearchParams{ + Query: `title: "dark knight"`, + Size: opensearchapi.ToPointer(2), + From: opensearchapi.ToPointer(5), + Sort: []string{"year:desc"}, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) + + // + + searchResp, err = client.Search( + ctx, + &opensearchapi.SearchReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.SearchParams{ + Query: `title: "dark knight"`, + Size: opensearchapi.ToPointer(2), + Sort: []string{"year:desc"}, + Scroll: time.Minute, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) + + // + + pitCreateResp, err := client.PointInTime.Create( + ctx, + opensearchapi.PointInTimeCreateReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.PointInTimeCreateParams{KeepAlive: time.Minute}, + }, + ) + if err != nil { + return err + } + + searchResp, err = client.Search( + ctx, + &opensearchapi.SearchReq{ + Body: strings.NewReader(fmt.Sprintf(`{ "pit": { "id": "%s", "keep_alive": "1m" } }`, pitCreateResp.PitID)), + Params: opensearchapi.SearchParams{ + Size: opensearchapi.ToPointer(5), + Sort: []string{"year:desc"}, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) + + searchResp, err = client.Search( + ctx, + &opensearchapi.SearchReq{ + Body: strings.NewReader(fmt.Sprintf(`{ "pit": { "id": "%s", "keep_alive": "1m" }, "search_after": [ "1994" ] }`, pitCreateResp.PitID)), + Params: opensearchapi.SearchParams{ + Size: opensearchapi.ToPointer(5), + Sort: []string{"year:desc"}, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) + + _, err = client.PointInTime.Delete(ctx, opensearchapi.PointInTimeDeleteReq{PitID: []string{pitCreateResp.PitID}}) + if err != nil { + return err + } + + sourceResp, err := client.Document.Source( + ctx, + opensearchapi.DocumentSourceReq{ + Index: "movies", + DocumentID: "1", + Params: opensearchapi.DocumentSourceParams{ + SourceIncludes: []string{"title"}, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(sourceResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Source Response:\n%s\n", string(respAsJson)) + + sourceResp, err = client.Document.Source( + ctx, + opensearchapi.DocumentSourceReq{ + Index: "movies", + DocumentID: "1", + Params: opensearchapi.DocumentSourceParams{ + SourceExcludes: []string{"title"}, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(sourceResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Source Response:\n%s\n", string(respAsJson)) + + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"movies"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) + + return nil +}