From b474087c80081c645b0a59a1a7dbb4542dd56be6 Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Wed, 18 Oct 2023 18:59:42 +0200 Subject: [PATCH 01/12] Read --- .../data_source_mongodbatlas_search_index.go | 4 +- ...data_source_mongodbatlas_search_indexes.go | 4 +- .../resource_mongodbatlas_search_index.go | 38 +++++++++++++------ 3 files changed, 31 insertions(+), 15 deletions(-) diff --git a/mongodbatlas/data_source_mongodbatlas_search_index.go b/mongodbatlas/data_source_mongodbatlas_search_index.go index 6931118881..cc4e61d4b5 100644 --- a/mongodbatlas/data_source_mongodbatlas_search_index.go +++ b/mongodbatlas/data_source_mongodbatlas_search_index.go @@ -116,7 +116,7 @@ func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resour } if len(searchIndex.Analyzers) > 0 { - searchIndexMappingFields, err := marshallSearchIndexAnalyzers(searchIndex.Analyzers) + searchIndexMappingFields, err := marshallSearchIndexAnalyzers2(searchIndex.Analyzers) if err != nil { return diag.FromErr(err) } @@ -146,7 +146,7 @@ func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resour return diag.Errorf("error setting `mappings_dynamic` for search index (%s): %s", d.Id(), err) } - if err := d.Set("synonyms", flattenSearchIndexSynonyms(searchIndex.Synonyms)); err != nil { + if err := d.Set("synonyms", flattenSearchIndexSynonyms2(searchIndex.Synonyms)); err != nil { return diag.Errorf("error setting `synonyms` for search index (%s): %s", d.Id(), err) } diff --git a/mongodbatlas/data_source_mongodbatlas_search_indexes.go b/mongodbatlas/data_source_mongodbatlas_search_indexes.go index 0936aeadbb..372eb6a46d 100644 --- a/mongodbatlas/data_source_mongodbatlas_search_indexes.go +++ b/mongodbatlas/data_source_mongodbatlas_search_indexes.go @@ -111,7 +111,7 @@ func flattenSearchIndexes(searchIndexes []*matlas.SearchIndex) ([]map[string]int "name": searchIndexes[i].Name, "search_analyzer": searchIndexes[i].SearchAnalyzer, "status": searchIndexes[i].Status, - "synonyms": flattenSearchIndexSynonyms(searchIndexes[i].Synonyms), + "synonyms": flattenSearchIndexSynonyms2(searchIndexes[i].Synonyms), } if searchIndexes[i].Mappings.Fields != nil { @@ -123,7 +123,7 @@ func flattenSearchIndexes(searchIndexes []*matlas.SearchIndex) ([]map[string]int } if len(searchIndexes[i].Analyzers) > 0 { - searchIndexAnalyzers, err := marshallSearchIndexAnalyzers(searchIndexes[i].Analyzers) + searchIndexAnalyzers, err := marshallSearchIndexAnalyzers2(searchIndexes[i].Analyzers) if err != nil { return nil, err } diff --git a/mongodbatlas/resource_mongodbatlas_search_index.go b/mongodbatlas/resource_mongodbatlas_search_index.go index c8bcfdfa87..bdf3c20c06 100644 --- a/mongodbatlas/resource_mongodbatlas_search_index.go +++ b/mongodbatlas/resource_mongodbatlas_search_index.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "go.mongodb.org/atlas-sdk/v20231001001/admin" matlas "go.mongodb.org/atlas/mongodbatlas" ) @@ -258,25 +259,22 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { // Get client connection. - conn := meta.(*MongoDBClient).Atlas ids := decodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] indexID := ids["index_id"] - searchIndex, _, err := conn.Search.GetIndex(ctx, projectID, clusterName, indexID) + connV2 := meta.(*MongoDBClient).AtlasV2 + searchIndex, resp, err := connV2.AtlasSearchApi.GetAtlasSearchIndex(ctx, projectID, clusterName, indexID).Execute() if err != nil { - // case 404 // deleted in the backend case - reset := strings.Contains(err.Error(), "404") && !d.IsNewResource() - - if reset { + if resp.StatusCode == 404 && !d.IsNewResource() { d.SetId("") return nil } - return diag.Errorf("error getting search index information: %s", err) } + if err := d.Set("index_id", indexID); err != nil { return diag.Errorf("error setting `index_id` for search index (%s): %s", d.Id(), err) } @@ -321,7 +319,7 @@ func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resource } if searchIndex.Mappings.Fields != nil { - searchIndexMappingFields, err := marshallSearchIndexMappingsField(*searchIndex.Mappings.Fields) + searchIndexMappingFields, err := marshallSearchIndexMappingsField(searchIndex.Mappings.Fields) if err != nil { return diag.FromErr(err) } @@ -334,7 +332,19 @@ func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resource return nil } -func flattenSearchIndexSynonyms(synonyms []map[string]interface{}) []map[string]interface{} { +func flattenSearchIndexSynonyms(synonyms []admin.SearchSynonymMappingDefinition) []map[string]interface{} { + synonymsMap := make([]map[string]interface{}, len(synonyms)) + for i, s := range synonyms { + synonymsMap[i] = map[string]interface{}{ + "name": s.Name, + "analyzer": s.Analyzer, + "source_collection": s.Source.Collection, + } + } + return synonymsMap +} + +func flattenSearchIndexSynonyms2(synonyms []map[string]interface{}) []map[string]interface{} { synonymsMap := make([]map[string]interface{}, 0) for _, s := range synonyms { @@ -349,11 +359,18 @@ func flattenSearchIndexSynonyms(synonyms []map[string]interface{}) []map[string] return synonymsMap } -func marshallSearchIndexAnalyzers(fields []map[string]interface{}) (string, error) { +func marshallSearchIndexAnalyzers(fields []admin.ApiAtlasFTSAnalyzers) (string, error) { if len(fields) == 0 { return "", nil } + mappingFieldJSON, err := json.Marshal(fields) + return string(mappingFieldJSON), err +} +func marshallSearchIndexAnalyzers2(fields []map[string]interface{}) (string, error) { + if len(fields) == 0 { + return "", nil + } mappingFieldJSON, err := json.Marshal(fields) return string(mappingFieldJSON), err } @@ -362,7 +379,6 @@ func marshallSearchIndexMappingsField(fields map[string]interface{}) (string, er if len(fields) == 0 { return "", nil } - mappingFieldJSON, err := json.Marshal(fields) return string(mappingFieldJSON), err } From 79063a14a33a13dea567cef47e0de0af67976054 Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Wed, 18 Oct 2023 20:05:34 +0200 Subject: [PATCH 02/12] Delete --- mongodbatlas/resource_mongodbatlas_search_index.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/mongodbatlas/resource_mongodbatlas_search_index.go b/mongodbatlas/resource_mongodbatlas_search_index.go index bdf3c20c06..4ccf9b6021 100644 --- a/mongodbatlas/resource_mongodbatlas_search_index.go +++ b/mongodbatlas/resource_mongodbatlas_search_index.go @@ -157,18 +157,16 @@ func resourceMongoDBAtlasSearchIndexImportState(ctx context.Context, d *schema.R } func resourceMongoDBAtlasSearchIndexDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - // Get client connection. - conn := meta.(*MongoDBClient).Atlas ids := decodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] indexID := ids["index_id"] - _, err := conn.Search.DeleteIndex(ctx, projectID, clusterName, indexID) + connV2 := meta.(*MongoDBClient).AtlasV2 + _, _, err := connV2.AtlasSearchApi.DeleteAtlasSearchIndex(ctx, projectID, clusterName, indexID).Execute() if err != nil { return diag.Errorf("error deleting search index (%s): %s", d.Get("name").(string), err) } - return nil } From de689e2a1485d8ce299b8c28322475982c22ee72 Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Wed, 18 Oct 2023 20:08:04 +0200 Subject: [PATCH 03/12] change interface{} to any --- .../resource_mongodbatlas_search_index.go | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/mongodbatlas/resource_mongodbatlas_search_index.go b/mongodbatlas/resource_mongodbatlas_search_index.go index 4ccf9b6021..a9d5e4020c 100644 --- a/mongodbatlas/resource_mongodbatlas_search_index.go +++ b/mongodbatlas/resource_mongodbatlas_search_index.go @@ -118,7 +118,7 @@ func returnSearchIndexSchema() map[string]*schema.Schema { } } -func resourceMongoDBAtlasSearchIndexImportState(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { +func resourceMongoDBAtlasSearchIndexImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { conn := meta.(*MongoDBClient).Atlas parts := strings.SplitN(d.Id(), "--", 3) @@ -156,7 +156,7 @@ func resourceMongoDBAtlasSearchIndexImportState(ctx context.Context, d *schema.R return []*schema.ResourceData{d}, nil } -func resourceMongoDBAtlasSearchIndexDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceMongoDBAtlasSearchIndexDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { ids := decodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] @@ -170,7 +170,7 @@ func resourceMongoDBAtlasSearchIndexDelete(ctx context.Context, d *schema.Resour return nil } -func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Get client connection. conn := meta.(*MongoDBClient).Atlas ids := decodeStateID(d.Id()) @@ -255,7 +255,7 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour return resourceMongoDBAtlasSearchIndexRead(ctx, d, meta) } -func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Get client connection. ids := decodeStateID(d.Id()) projectID := ids["project_id"] @@ -330,10 +330,10 @@ func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resource return nil } -func flattenSearchIndexSynonyms(synonyms []admin.SearchSynonymMappingDefinition) []map[string]interface{} { - synonymsMap := make([]map[string]interface{}, len(synonyms)) +func flattenSearchIndexSynonyms(synonyms []admin.SearchSynonymMappingDefinition) []map[string]any { + synonymsMap := make([]map[string]any, len(synonyms)) for i, s := range synonyms { - synonymsMap[i] = map[string]interface{}{ + synonymsMap[i] = map[string]any{ "name": s.Name, "analyzer": s.Analyzer, "source_collection": s.Source.Collection, @@ -342,12 +342,12 @@ func flattenSearchIndexSynonyms(synonyms []admin.SearchSynonymMappingDefinition) return synonymsMap } -func flattenSearchIndexSynonyms2(synonyms []map[string]interface{}) []map[string]interface{} { - synonymsMap := make([]map[string]interface{}, 0) +func flattenSearchIndexSynonyms2(synonyms []map[string]any) []map[string]any { + synonymsMap := make([]map[string]any, 0) for _, s := range synonyms { - sourceCollection := s["source"].(map[string]interface{}) - synonym := map[string]interface{}{ + sourceCollection := s["source"].(map[string]any) + synonym := map[string]any{ "name": s["name"], "analyzer": s["analyzer"], "source_collection": sourceCollection["collection"], @@ -365,7 +365,7 @@ func marshallSearchIndexAnalyzers(fields []admin.ApiAtlasFTSAnalyzers) (string, return string(mappingFieldJSON), err } -func marshallSearchIndexAnalyzers2(fields []map[string]interface{}) (string, error) { +func marshallSearchIndexAnalyzers2(fields []map[string]any) (string, error) { if len(fields) == 0 { return "", nil } @@ -373,7 +373,7 @@ func marshallSearchIndexAnalyzers2(fields []map[string]interface{}) (string, err return string(mappingFieldJSON), err } -func marshallSearchIndexMappingsField(fields map[string]interface{}) (string, error) { +func marshallSearchIndexMappingsField(fields map[string]any) (string, error) { if len(fields) == 0 { return "", nil } @@ -381,7 +381,7 @@ func marshallSearchIndexMappingsField(fields map[string]interface{}) (string, er return string(mappingFieldJSON), err } -func resourceMongoDBAtlasSearchIndexCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceMongoDBAtlasSearchIndexCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Get client connection. conn := meta.(*MongoDBClient).Atlas projectID := d.Get("project_id").(string) @@ -442,18 +442,18 @@ func resourceMongoDBAtlasSearchIndexCreate(ctx context.Context, d *schema.Resour return resourceMongoDBAtlasSearchIndexRead(ctx, d, meta) } -func expandSearchIndexSynonyms(d *schema.ResourceData) []map[string]interface{} { - var synonymsList []map[string]interface{} +func expandSearchIndexSynonyms(d *schema.ResourceData) []map[string]any { + var synonymsList []map[string]any - synonymsDoc := map[string]interface{}{} + synonymsDoc := map[string]any{} if vSynonyms, vSynonymsOK := d.GetOk("synonyms"); vSynonymsOK { for _, s := range vSynonyms.(*schema.Set).List() { - synonym := s.(map[string]interface{}) + synonym := s.(map[string]any) synonymsDoc["name"] = synonym["name"] synonymsDoc["analyzer"] = synonym["analyzer"] - synonymsDoc["source"] = map[string]interface{}{ + synonymsDoc["source"] = map[string]any{ "collection": synonym["source_collection"], } synonymsList = append(synonymsList, synonymsDoc) @@ -463,7 +463,7 @@ func expandSearchIndexSynonyms(d *schema.ResourceData) []map[string]interface{} } func validateSearchIndexMappingDiff(k, old, newStr string, d *schema.ResourceData) bool { - var j, j2 interface{} + var j, j2 any if old == "" { old = "{}" @@ -488,7 +488,7 @@ func validateSearchIndexMappingDiff(k, old, newStr string, d *schema.ResourceDat } func validateSearchAnalyzersDiff(k, old, newStr string, d *schema.ResourceData) bool { - var j, j2 interface{} + var j, j2 any if old == "" { old = "{}" @@ -512,12 +512,12 @@ func validateSearchAnalyzersDiff(k, old, newStr string, d *schema.ResourceData) return true } -func unmarshalSearchIndexMappingFields(mappingString string) map[string]interface{} { +func unmarshalSearchIndexMappingFields(mappingString string) map[string]any { if mappingString == "" { return nil } - var fields map[string]interface{} + var fields map[string]any if err := json.Unmarshal([]byte(mappingString), &fields); err != nil { log.Printf("[ERROR] cannot unmarshal search index mapping fields: %v", err) @@ -527,12 +527,12 @@ func unmarshalSearchIndexMappingFields(mappingString string) map[string]interfac return fields } -func unmarshalSearchIndexAnalyzersFields(mappingString string) []map[string]interface{} { +func unmarshalSearchIndexAnalyzersFields(mappingString string) []map[string]any { if mappingString == "" { return nil } - var fields []map[string]interface{} + var fields []map[string]any if err := json.Unmarshal([]byte(mappingString), &fields); err != nil { log.Printf("[ERROR] cannot unmarshal search index mapping fields: %v", err) @@ -543,7 +543,7 @@ func unmarshalSearchIndexAnalyzersFields(mappingString string) []map[string]inte } func resourceSearchIndexRefreshFunc(ctx context.Context, clusterName, projectID, indexID string, client *matlas.Client) retry.StateRefreshFunc { - return func() (interface{}, string, error) { + return func() (any, string, error) { searchIndex, resp, err := client.Search.GetIndex(ctx, projectID, clusterName, indexID) if err != nil { return nil, "ERROR", err From 11e0ee15066f9c07d4b1ff05bc4eaeeb514b25e6 Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Thu, 19 Oct 2023 08:34:36 +0200 Subject: [PATCH 04/12] Create --- .../resource_mongodbatlas_search_index.go | 101 +++++++++++++----- 1 file changed, 72 insertions(+), 29 deletions(-) diff --git a/mongodbatlas/resource_mongodbatlas_search_index.go b/mongodbatlas/resource_mongodbatlas_search_index.go index a9d5e4020c..494ccc7687 100644 --- a/mongodbatlas/resource_mongodbatlas_search_index.go +++ b/mongodbatlas/resource_mongodbatlas_search_index.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/mongodb/terraform-provider-mongodbatlas/mongodbatlas/util" "go.mongodb.org/atlas-sdk/v20231001001/admin" matlas "go.mongodb.org/atlas/mongodbatlas" ) @@ -188,7 +189,7 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour } if d.HasChange("analyzers") { - searchIndex.Analyzers = unmarshalSearchIndexAnalyzersFields(d.Get("analyzers").(string)) + searchIndex.Analyzers = unmarshalSearchIndexAnalyzersFields2(d.Get("analyzers").(string)) } if d.HasChange("collection_name") { @@ -217,7 +218,7 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour } if d.HasChange("synonyms") { - synonyms := expandSearchIndexSynonyms(d) + synonyms := expandSearchIndexSynonyms2(d) searchIndex.Synonyms = synonyms } @@ -232,7 +233,7 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour stateConf := &retry.StateChangeConf{ Pending: []string{"IN_PROGRESS", "MIGRATING"}, Target: []string{"STEADY"}, - Refresh: resourceSearchIndexRefreshFunc(ctx, clusterName, projectID, dbSearchIndexRes.IndexID, conn), + Refresh: resourceSearchIndexRefreshFunc2(ctx, clusterName, projectID, dbSearchIndexRes.IndexID, conn), Timeout: timeout, MinTimeout: 1 * time.Minute, Delay: 1 * time.Minute, @@ -382,39 +383,35 @@ func marshallSearchIndexMappingsField(fields map[string]any) (string, error) { } func resourceMongoDBAtlasSearchIndexCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - // Get client connection. - conn := meta.(*MongoDBClient).Atlas + connV2 := meta.(*MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) - clusterName := d.Get("cluster_name").(string) - - indexMapping := unmarshalSearchIndexMappingFields(d.Get("mappings_fields").(string)) - - searchIndexRequest := &matlas.SearchIndex{ - Analyzer: d.Get("analyzer").(string), + dynamic := d.Get("mappings_dynamic").(bool) + searchIndexRequest := &admin.ClusterSearchIndex{ + Analyzer: stringPtr(d.Get("analyzer").(string)), Analyzers: unmarshalSearchIndexAnalyzersFields(d.Get("analyzers").(string)), CollectionName: d.Get("collection_name").(string), Database: d.Get("database").(string), - Mappings: &matlas.IndexMapping{ - Dynamic: d.Get("mappings_dynamic").(bool), - Fields: &indexMapping, + Mappings: &admin.ApiAtlasFTSMappings{ + Dynamic: &dynamic, + Fields: unmarshalSearchIndexMappingFields(d.Get("mappings_fields").(string)), }, Name: d.Get("name").(string), - SearchAnalyzer: d.Get("search_analyzer").(string), - Status: d.Get("status").(string), + SearchAnalyzer: stringPtr(d.Get("search_analyzer").(string)), + Status: stringPtr(d.Get("status").(string)), Synonyms: expandSearchIndexSynonyms(d), } - - dbSearchIndexRes, _, err := conn.Search.CreateIndex(ctx, projectID, clusterName, searchIndexRequest) + dbSearchIndexRes, _, err := connV2.AtlasSearchApi.CreateAtlasSearchIndex(ctx, projectID, clusterName, searchIndexRequest).Execute() if err != nil { return diag.Errorf("error creating index: %s", err) } + indexID := util.SafeString(dbSearchIndexRes.IndexID) if d.Get("wait_for_index_build_completion").(bool) { timeout := d.Timeout(schema.TimeoutCreate) stateConf := &retry.StateChangeConf{ Pending: []string{"IN_PROGRESS", "MIGRATING"}, Target: []string{"STEADY"}, - Refresh: resourceSearchIndexRefreshFunc(ctx, clusterName, projectID, dbSearchIndexRes.IndexID, conn), + Refresh: resourceSearchIndexRefreshFunc(ctx, clusterName, projectID, indexID, connV2), Timeout: timeout, MinTimeout: 1 * time.Minute, Delay: 1 * time.Minute, @@ -426,7 +423,7 @@ func resourceMongoDBAtlasSearchIndexCreate(ctx context.Context, d *schema.Resour d.SetId(encodeStateID(map[string]string{ "project_id": projectID, "cluster_name": clusterName, - "index_id": dbSearchIndexRes.IndexID, + "index_id": indexID, })) resourceMongoDBAtlasSearchIndexDelete(ctx, d, meta) d.SetId("") @@ -436,13 +433,31 @@ func resourceMongoDBAtlasSearchIndexCreate(ctx context.Context, d *schema.Resour d.SetId(encodeStateID(map[string]string{ "project_id": projectID, "cluster_name": clusterName, - "index_id": dbSearchIndexRes.IndexID, + "index_id": indexID, })) return resourceMongoDBAtlasSearchIndexRead(ctx, d, meta) } -func expandSearchIndexSynonyms(d *schema.ResourceData) []map[string]any { +func expandSearchIndexSynonyms(d *schema.ResourceData) []admin.SearchSynonymMappingDefinition { + var synonymsList []admin.SearchSynonymMappingDefinition + if vSynonyms, ok := d.GetOk("synonyms"); ok { + for _, s := range vSynonyms.(*schema.Set).List() { + synonym := s.(map[string]any) + synonymsDoc := admin.SearchSynonymMappingDefinition{ + Name: synonym["name"].(string), + Analyzer: synonym["analyzer"].(string), + Source: admin.SynonymSource{ + Collection: synonym["source_collection"].(string), + }, + } + synonymsList = append(synonymsList, synonymsDoc) + } + } + return synonymsList +} + +func expandSearchIndexSynonyms2(d *schema.ResourceData) []map[string]any { var synonymsList []map[string]any synonymsDoc := map[string]any{} @@ -516,33 +531,61 @@ func unmarshalSearchIndexMappingFields(mappingString string) map[string]any { if mappingString == "" { return nil } - var fields map[string]any - if err := json.Unmarshal([]byte(mappingString), &fields); err != nil { log.Printf("[ERROR] cannot unmarshal search index mapping fields: %v", err) return nil } - return fields } -func unmarshalSearchIndexAnalyzersFields(mappingString string) []map[string]any { +func unmarshalSearchIndexAnalyzersFields(mappingString string) []admin.ApiAtlasFTSAnalyzers { if mappingString == "" { return nil } + var fields []admin.ApiAtlasFTSAnalyzers + if err := json.Unmarshal([]byte(mappingString), &fields); err != nil { + log.Printf("[ERROR] cannot unmarshal search index mapping fields: %v", err) + return nil + } + return fields +} +func unmarshalSearchIndexAnalyzersFields2(mappingString string) []map[string]any { + if mappingString == "" { + return nil + } var fields []map[string]any - if err := json.Unmarshal([]byte(mappingString), &fields); err != nil { log.Printf("[ERROR] cannot unmarshal search index mapping fields: %v", err) return nil } - return fields } -func resourceSearchIndexRefreshFunc(ctx context.Context, clusterName, projectID, indexID string, client *matlas.Client) retry.StateRefreshFunc { +func resourceSearchIndexRefreshFunc(ctx context.Context, clusterName, projectID, indexID string, connV2 *admin.APIClient) retry.StateRefreshFunc { + return func() (any, string, error) { + searchIndex, resp, err := connV2.AtlasSearchApi.GetAtlasSearchIndex(ctx, projectID, clusterName, indexID).Execute() + status := util.SafeString(searchIndex.Status) + if err != nil { + return nil, "ERROR", err + } + if err != nil && searchIndex == nil && resp == nil { + return nil, "", err + } else if err != nil { + if resp.StatusCode == 404 { + return "", "DELETED", nil + } + if resp.StatusCode == 503 { + return "", "PENDING", nil + } + return nil, "", err + } + return searchIndex, status, nil + } +} + +func resourceSearchIndexRefreshFunc2(ctx context.Context, clusterName, projectID, indexID string, client *matlas.Client) retry.StateRefreshFunc { return func() (any, string, error) { searchIndex, resp, err := client.Search.GetIndex(ctx, projectID, clusterName, indexID) if err != nil { From 039268b4b85b86db4ccd207159b4ccbac5ab2d9e Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Thu, 19 Oct 2023 08:56:00 +0200 Subject: [PATCH 05/12] Update --- .../resource_mongodbatlas_search_index.go | 89 +++---------------- 1 file changed, 13 insertions(+), 76 deletions(-) diff --git a/mongodbatlas/resource_mongodbatlas_search_index.go b/mongodbatlas/resource_mongodbatlas_search_index.go index 494ccc7687..0645b27f18 100644 --- a/mongodbatlas/resource_mongodbatlas_search_index.go +++ b/mongodbatlas/resource_mongodbatlas_search_index.go @@ -15,7 +15,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/mongodbatlas/util" "go.mongodb.org/atlas-sdk/v20231001001/admin" - matlas "go.mongodb.org/atlas/mongodbatlas" ) func resourceMongoDBAtlasSearchIndex() *schema.Resource { @@ -172,24 +171,23 @@ func resourceMongoDBAtlasSearchIndexDelete(ctx context.Context, d *schema.Resour } func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - // Get client connection. - conn := meta.(*MongoDBClient).Atlas + connV2 := meta.(*MongoDBClient).AtlasV2 ids := decodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] indexID := ids["index_id"] - searchIndex, _, err := conn.Search.GetIndex(ctx, projectID, clusterName, indexID) + searchIndex, _, err := connV2.AtlasSearchApi.GetAtlasSearchIndex(ctx, projectID, clusterName, indexID).Execute() if err != nil { return diag.Errorf("error getting search index information: %s", err) } if d.HasChange("analyzer") { - searchIndex.Analyzer = d.Get("analyzer").(string) + searchIndex.Analyzer = stringPtr(d.Get("analyzer").(string)) } if d.HasChange("analyzers") { - searchIndex.Analyzers = unmarshalSearchIndexAnalyzersFields2(d.Get("analyzers").(string)) + searchIndex.Analyzers = unmarshalSearchIndexAnalyzersFields(d.Get("analyzers").(string)) } if d.HasChange("collection_name") { @@ -205,26 +203,24 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour } if d.HasChange("search_analyzer") { - searchIndex.SearchAnalyzer = d.Get("search_analyzer").(string) + searchIndex.SearchAnalyzer = stringPtr(d.Get("search_analyzer").(string)) } + dynamic := d.Get("mappings_dynamic").(bool) if d.HasChange("mappings_dynamic") { - searchIndex.Mappings.Dynamic = d.Get("mappings_dynamic").(bool) + searchIndex.Mappings.Dynamic = &dynamic } if d.HasChange("mappings_fields") { - mappingFields := unmarshalSearchIndexMappingFields(d.Get("mappings_fields").(string)) - searchIndex.Mappings.Fields = &mappingFields + searchIndex.Mappings.Fields = unmarshalSearchIndexMappingFields(d.Get("mappings_fields").(string)) } if d.HasChange("synonyms") { - synonyms := expandSearchIndexSynonyms2(d) - searchIndex.Synonyms = synonyms + searchIndex.Synonyms = expandSearchIndexSynonyms(d) } - searchIndex.IndexID = "" - dbSearchIndexRes, _, err := conn.Search.UpdateIndex(context.Background(), projectID, clusterName, indexID, searchIndex) - if err != nil { + searchIndex.IndexID = stringPtr("") + if _, _, err := connV2.AtlasSearchApi.UpdateAtlasSearchIndex(ctx, projectID, clusterName, indexID, searchIndex).Execute(); err != nil { return diag.Errorf("error updating search index (%s): %s", searchIndex.Name, err) } @@ -233,7 +229,7 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour stateConf := &retry.StateChangeConf{ Pending: []string{"IN_PROGRESS", "MIGRATING"}, Target: []string{"STEADY"}, - Refresh: resourceSearchIndexRefreshFunc2(ctx, clusterName, projectID, dbSearchIndexRes.IndexID, conn), + Refresh: resourceSearchIndexRefreshFunc(ctx, clusterName, projectID, indexID, connV2), Timeout: timeout, MinTimeout: 1 * time.Minute, Delay: 1 * time.Minute, @@ -245,7 +241,7 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour d.SetId(encodeStateID(map[string]string{ "project_id": projectID, "cluster_name": clusterName, - "index_id": dbSearchIndexRes.IndexID, + "index_id": indexID, })) resourceMongoDBAtlasSearchIndexDelete(ctx, d, meta) d.SetId("") @@ -457,26 +453,6 @@ func expandSearchIndexSynonyms(d *schema.ResourceData) []admin.SearchSynonymMapp return synonymsList } -func expandSearchIndexSynonyms2(d *schema.ResourceData) []map[string]any { - var synonymsList []map[string]any - - synonymsDoc := map[string]any{} - - if vSynonyms, vSynonymsOK := d.GetOk("synonyms"); vSynonymsOK { - for _, s := range vSynonyms.(*schema.Set).List() { - synonym := s.(map[string]any) - - synonymsDoc["name"] = synonym["name"] - synonymsDoc["analyzer"] = synonym["analyzer"] - synonymsDoc["source"] = map[string]any{ - "collection": synonym["source_collection"], - } - synonymsList = append(synonymsList, synonymsDoc) - } - } - return synonymsList -} - func validateSearchIndexMappingDiff(k, old, newStr string, d *schema.ResourceData) bool { var j, j2 any @@ -551,18 +527,6 @@ func unmarshalSearchIndexAnalyzersFields(mappingString string) []admin.ApiAtlasF return fields } -func unmarshalSearchIndexAnalyzersFields2(mappingString string) []map[string]any { - if mappingString == "" { - return nil - } - var fields []map[string]any - if err := json.Unmarshal([]byte(mappingString), &fields); err != nil { - log.Printf("[ERROR] cannot unmarshal search index mapping fields: %v", err) - return nil - } - return fields -} - func resourceSearchIndexRefreshFunc(ctx context.Context, clusterName, projectID, indexID string, connV2 *admin.APIClient) retry.StateRefreshFunc { return func() (any, string, error) { searchIndex, resp, err := connV2.AtlasSearchApi.GetAtlasSearchIndex(ctx, projectID, clusterName, indexID).Execute() @@ -584,30 +548,3 @@ func resourceSearchIndexRefreshFunc(ctx context.Context, clusterName, projectID, return searchIndex, status, nil } } - -func resourceSearchIndexRefreshFunc2(ctx context.Context, clusterName, projectID, indexID string, client *matlas.Client) retry.StateRefreshFunc { - return func() (any, string, error) { - searchIndex, resp, err := client.Search.GetIndex(ctx, projectID, clusterName, indexID) - if err != nil { - return nil, "ERROR", err - } - - if err != nil && searchIndex == nil && resp == nil { - return nil, "", err - } else if err != nil { - if resp.StatusCode == 404 { - return "", "DELETED", nil - } - if resp.StatusCode == 503 { - return "", "PENDING", nil - } - return nil, "", err - } - - if searchIndex.Status != "" { - log.Printf("[DEBUG] status for Search Index : %s: %s", clusterName, searchIndex.Status) - } - - return searchIndex, searchIndex.Status, nil - } -} From 82ed53fcba706d78390d8d007e2081d59d093a21 Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Thu, 19 Oct 2023 09:06:27 +0200 Subject: [PATCH 06/12] Import --- .../data_source_mongodbatlas_search_index.go | 2 +- ...data_source_mongodbatlas_search_indexes.go | 2 +- .../resource_mongodbatlas_search_index.go | 22 ++++++++----------- 3 files changed, 11 insertions(+), 15 deletions(-) diff --git a/mongodbatlas/data_source_mongodbatlas_search_index.go b/mongodbatlas/data_source_mongodbatlas_search_index.go index cc4e61d4b5..b2cabffda5 100644 --- a/mongodbatlas/data_source_mongodbatlas_search_index.go +++ b/mongodbatlas/data_source_mongodbatlas_search_index.go @@ -151,7 +151,7 @@ func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resour } if searchIndex.Mappings.Fields != nil { - searchIndexMappingFields, err := marshallSearchIndexMappingsField(*searchIndex.Mappings.Fields) + searchIndexMappingFields, err := marshallSearchIndexMappingsField2(*searchIndex.Mappings.Fields) if err != nil { return diag.FromErr(err) } diff --git a/mongodbatlas/data_source_mongodbatlas_search_indexes.go b/mongodbatlas/data_source_mongodbatlas_search_indexes.go index 372eb6a46d..0f290cfb39 100644 --- a/mongodbatlas/data_source_mongodbatlas_search_indexes.go +++ b/mongodbatlas/data_source_mongodbatlas_search_indexes.go @@ -115,7 +115,7 @@ func flattenSearchIndexes(searchIndexes []*matlas.SearchIndex) ([]map[string]int } if searchIndexes[i].Mappings.Fields != nil { - searchIndexMappingFields, err := marshallSearchIndexMappingsField(*searchIndexes[i].Mappings.Fields) + searchIndexMappingFields, err := marshallSearchIndexMappingsField2(*searchIndexes[i].Mappings.Fields) if err != nil { return nil, err } diff --git a/mongodbatlas/resource_mongodbatlas_search_index.go b/mongodbatlas/resource_mongodbatlas_search_index.go index 0645b27f18..a7bd519b5d 100644 --- a/mongodbatlas/resource_mongodbatlas_search_index.go +++ b/mongodbatlas/resource_mongodbatlas_search_index.go @@ -119,7 +119,7 @@ func returnSearchIndexSchema() map[string]*schema.Schema { } func resourceMongoDBAtlasSearchIndexImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { - conn := meta.(*MongoDBClient).Atlas + connV2 := meta.(*MongoDBClient).AtlasV2 parts := strings.SplitN(d.Id(), "--", 3) if len(parts) != 3 { @@ -130,7 +130,7 @@ func resourceMongoDBAtlasSearchIndexImportState(ctx context.Context, d *schema.R clusterName := parts[1] indexID := parts[2] - _, _, err := conn.Search.GetIndex(ctx, projectID, clusterName, indexID) + _, _, err := connV2.AtlasSearchApi.GetAtlasSearchIndex(ctx, projectID, clusterName, indexID).Execute() if err != nil { return nil, fmt.Errorf("couldn't import search index (%s) in projectID (%s) and Cluster (%s), error: %s", indexID, projectID, clusterName, err) } @@ -253,7 +253,6 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour } func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - // Get client connection. ids := decodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] @@ -279,7 +278,7 @@ func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resource } if len(searchIndex.Analyzers) > 0 { - searchIndexMappingFields, err := marshallSearchIndexAnalyzers(searchIndex.Analyzers) + searchIndexMappingFields, err := marshalSearchIndex(searchIndex.Analyzers) if err != nil { return diag.FromErr(err) } @@ -313,8 +312,8 @@ func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resource return diag.Errorf("error setting `synonyms` for search index (%s): %s", d.Id(), err) } - if searchIndex.Mappings.Fields != nil { - searchIndexMappingFields, err := marshallSearchIndexMappingsField(searchIndex.Mappings.Fields) + if len(searchIndex.Mappings.Fields) > 0 { + searchIndexMappingFields, err := marshalSearchIndex(searchIndex.Mappings.Fields) if err != nil { return diag.FromErr(err) } @@ -354,12 +353,9 @@ func flattenSearchIndexSynonyms2(synonyms []map[string]any) []map[string]any { return synonymsMap } -func marshallSearchIndexAnalyzers(fields []admin.ApiAtlasFTSAnalyzers) (string, error) { - if len(fields) == 0 { - return "", nil - } - mappingFieldJSON, err := json.Marshal(fields) - return string(mappingFieldJSON), err +func marshalSearchIndex(fields any) (string, error) { + bytes, err := json.Marshal(fields) + return string(bytes), err } func marshallSearchIndexAnalyzers2(fields []map[string]any) (string, error) { @@ -370,7 +366,7 @@ func marshallSearchIndexAnalyzers2(fields []map[string]any) (string, error) { return string(mappingFieldJSON), err } -func marshallSearchIndexMappingsField(fields map[string]any) (string, error) { +func marshallSearchIndexMappingsField2(fields map[string]any) (string, error) { if len(fields) == 0 { return "", nil } From ba806c1e55def0170c1ecd2a8496aa4ecd51208b Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Thu, 19 Oct 2023 09:19:09 +0200 Subject: [PATCH 07/12] single data source --- .../data_source_mongodbatlas_search_index.go | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/mongodbatlas/data_source_mongodbatlas_search_index.go b/mongodbatlas/data_source_mongodbatlas_search_index.go index b2cabffda5..649d3fb337 100644 --- a/mongodbatlas/data_source_mongodbatlas_search_index.go +++ b/mongodbatlas/data_source_mongodbatlas_search_index.go @@ -91,8 +91,7 @@ func returnSearchIndexDSSchema() map[string]*schema.Schema { } func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - // Get client connection. - conn := meta.(*MongoDBClient).Atlas + connV2 := meta.(*MongoDBClient).AtlasV2 projectID, projectIDOk := d.GetOk("project_id") clusterName, clusterNameOK := d.GetOk("cluster_name") @@ -102,7 +101,7 @@ func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resour return diag.Errorf("project_id, cluster_name and index_id must be configured") } - searchIndex, _, err := conn.Search.GetIndex(ctx, projectID.(string), clusterName.(string), indexID.(string)) + searchIndex, _, err := connV2.AtlasSearchApi.GetAtlasSearchIndex(ctx, projectID.(string), clusterName.(string), indexID.(string)).Execute() if err != nil { return diag.Errorf("error getting search index information: %s", err) } @@ -116,7 +115,7 @@ func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resour } if len(searchIndex.Analyzers) > 0 { - searchIndexMappingFields, err := marshallSearchIndexAnalyzers2(searchIndex.Analyzers) + searchIndexMappingFields, err := marshalSearchIndex(searchIndex.Analyzers) if err != nil { return diag.FromErr(err) } @@ -146,12 +145,12 @@ func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resour return diag.Errorf("error setting `mappings_dynamic` for search index (%s): %s", d.Id(), err) } - if err := d.Set("synonyms", flattenSearchIndexSynonyms2(searchIndex.Synonyms)); err != nil { + if err := d.Set("synonyms", flattenSearchIndexSynonyms(searchIndex.Synonyms)); err != nil { return diag.Errorf("error setting `synonyms` for search index (%s): %s", d.Id(), err) } - if searchIndex.Mappings.Fields != nil { - searchIndexMappingFields, err := marshallSearchIndexMappingsField2(*searchIndex.Mappings.Fields) + if len(searchIndex.Mappings.Fields) > 0 { + searchIndexMappingFields, err := marshalSearchIndex(searchIndex.Mappings.Fields) if err != nil { return diag.FromErr(err) } From 3c75563f4a17d634b2bac51230a76eca383603b4 Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Thu, 19 Oct 2023 10:12:37 +0200 Subject: [PATCH 08/12] list data source --- .../data_source_mongodbatlas_search_index.go | 3 +- ...data_source_mongodbatlas_search_indexes.go | 26 ++++++-------- .../resource_mongodbatlas_search_index.go | 34 +------------------ 3 files changed, 13 insertions(+), 50 deletions(-) diff --git a/mongodbatlas/data_source_mongodbatlas_search_index.go b/mongodbatlas/data_source_mongodbatlas_search_index.go index 649d3fb337..c0a3327b93 100644 --- a/mongodbatlas/data_source_mongodbatlas_search_index.go +++ b/mongodbatlas/data_source_mongodbatlas_search_index.go @@ -91,8 +91,6 @@ func returnSearchIndexDSSchema() map[string]*schema.Schema { } func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - connV2 := meta.(*MongoDBClient).AtlasV2 - projectID, projectIDOk := d.GetOk("project_id") clusterName, clusterNameOK := d.GetOk("cluster_name") indexID, indexIDOk := d.GetOk("index_id") @@ -101,6 +99,7 @@ func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resour return diag.Errorf("project_id, cluster_name and index_id must be configured") } + connV2 := meta.(*MongoDBClient).AtlasV2 searchIndex, _, err := connV2.AtlasSearchApi.GetAtlasSearchIndex(ctx, projectID.(string), clusterName.(string), indexID.(string)).Execute() if err != nil { return diag.Errorf("error getting search index information: %s", err) diff --git a/mongodbatlas/data_source_mongodbatlas_search_indexes.go b/mongodbatlas/data_source_mongodbatlas_search_indexes.go index 0f290cfb39..91d18f9653 100644 --- a/mongodbatlas/data_source_mongodbatlas_search_indexes.go +++ b/mongodbatlas/data_source_mongodbatlas_search_indexes.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - matlas "go.mongodb.org/atlas/mongodbatlas" + "go.mongodb.org/atlas-sdk/v20231001001/admin" ) func dataSourceMongoDBAtlasSearchIndexes() *schema.Resource { @@ -53,9 +53,6 @@ func dataSourceMongoDBAtlasSearchIndexes() *schema.Resource { } func dataSourceMongoDBAtlasSearchIndexesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - // Get client connection. - conn := meta.(*MongoDBClient).Atlas - projectID, projectIDOK := d.GetOk("project_id") clusterName, clusterNameOk := d.GetOk("cluster_name") databaseName, databaseNameOK := d.GetOk("database") @@ -65,17 +62,14 @@ func dataSourceMongoDBAtlasSearchIndexesRead(ctx context.Context, d *schema.Reso return diag.Errorf("project_id, cluster_name, database and collection_name must be configured") } - options := &matlas.ListOptions{ - PageNum: d.Get("page_num").(int), - ItemsPerPage: d.Get("items_per_page").(int), - } + connV2 := meta.(*MongoDBClient).AtlasV2 + searchIndexes, _, err := connV2.AtlasSearchApi.ListAtlasSearchIndexes(ctx, projectID.(string), clusterName.(string), collectionName.(string), databaseName.(string)).Execute() - searchIndexes, _, err := conn.Search.ListIndexes(ctx, projectID.(string), clusterName.(string), databaseName.(string), collectionName.(string), options) if err != nil { return diag.Errorf("error getting search indexes information: %s", err) } - flattedSearchIndexes, err := flattenSearchIndexes(searchIndexes) + flattedSearchIndexes, err := flattenSearchIndexes(searchIndexes, projectID.(string), clusterName.(string)) if err != nil { return diag.FromErr(err) } @@ -93,7 +87,7 @@ func dataSourceMongoDBAtlasSearchIndexesRead(ctx context.Context, d *schema.Reso return nil } -func flattenSearchIndexes(searchIndexes []*matlas.SearchIndex) ([]map[string]interface{}, error) { +func flattenSearchIndexes(searchIndexes []admin.ClusterSearchIndex, projectID, clusterName string) ([]map[string]interface{}, error) { var searchIndexesMap []map[string]interface{} if len(searchIndexes) == 0 { @@ -103,6 +97,8 @@ func flattenSearchIndexes(searchIndexes []*matlas.SearchIndex) ([]map[string]int for i := range searchIndexes { searchIndexesMap[i] = map[string]interface{}{ + "project_id": projectID, + "cluster_name": clusterName, "analyzer": searchIndexes[i].Analyzer, "collection_name": searchIndexes[i].CollectionName, "database": searchIndexes[i].Database, @@ -111,11 +107,11 @@ func flattenSearchIndexes(searchIndexes []*matlas.SearchIndex) ([]map[string]int "name": searchIndexes[i].Name, "search_analyzer": searchIndexes[i].SearchAnalyzer, "status": searchIndexes[i].Status, - "synonyms": flattenSearchIndexSynonyms2(searchIndexes[i].Synonyms), + "synonyms": flattenSearchIndexSynonyms(searchIndexes[i].Synonyms), } - if searchIndexes[i].Mappings.Fields != nil { - searchIndexMappingFields, err := marshallSearchIndexMappingsField2(*searchIndexes[i].Mappings.Fields) + if len(searchIndexes[i].Mappings.Fields) > 0 { + searchIndexMappingFields, err := marshalSearchIndex(searchIndexes[i].Mappings.Fields) if err != nil { return nil, err } @@ -123,7 +119,7 @@ func flattenSearchIndexes(searchIndexes []*matlas.SearchIndex) ([]map[string]int } if len(searchIndexes[i].Analyzers) > 0 { - searchIndexAnalyzers, err := marshallSearchIndexAnalyzers2(searchIndexes[i].Analyzers) + searchIndexAnalyzers, err := marshalSearchIndex(searchIndexes[i].Analyzers) if err != nil { return nil, err } diff --git a/mongodbatlas/resource_mongodbatlas_search_index.go b/mongodbatlas/resource_mongodbatlas_search_index.go index a7bd519b5d..3591a65876 100644 --- a/mongodbatlas/resource_mongodbatlas_search_index.go +++ b/mongodbatlas/resource_mongodbatlas_search_index.go @@ -119,8 +119,6 @@ func returnSearchIndexSchema() map[string]*schema.Schema { } func resourceMongoDBAtlasSearchIndexImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { - connV2 := meta.(*MongoDBClient).AtlasV2 - parts := strings.SplitN(d.Id(), "--", 3) if len(parts) != 3 { return nil, errors.New("import format error: to import a search index, use the format {project_id}--{cluster_name}--{index_id}") @@ -130,6 +128,7 @@ func resourceMongoDBAtlasSearchIndexImportState(ctx context.Context, d *schema.R clusterName := parts[1] indexID := parts[2] + connV2 := meta.(*MongoDBClient).AtlasV2 _, _, err := connV2.AtlasSearchApi.GetAtlasSearchIndex(ctx, projectID, clusterName, indexID).Execute() if err != nil { return nil, fmt.Errorf("couldn't import search index (%s) in projectID (%s) and Cluster (%s), error: %s", indexID, projectID, clusterName, err) @@ -338,42 +337,11 @@ func flattenSearchIndexSynonyms(synonyms []admin.SearchSynonymMappingDefinition) return synonymsMap } -func flattenSearchIndexSynonyms2(synonyms []map[string]any) []map[string]any { - synonymsMap := make([]map[string]any, 0) - - for _, s := range synonyms { - sourceCollection := s["source"].(map[string]any) - synonym := map[string]any{ - "name": s["name"], - "analyzer": s["analyzer"], - "source_collection": sourceCollection["collection"], - } - synonymsMap = append(synonymsMap, synonym) - } - return synonymsMap -} - func marshalSearchIndex(fields any) (string, error) { bytes, err := json.Marshal(fields) return string(bytes), err } -func marshallSearchIndexAnalyzers2(fields []map[string]any) (string, error) { - if len(fields) == 0 { - return "", nil - } - mappingFieldJSON, err := json.Marshal(fields) - return string(mappingFieldJSON), err -} - -func marshallSearchIndexMappingsField2(fields map[string]any) (string, error) { - if len(fields) == 0 { - return "", nil - } - mappingFieldJSON, err := json.Marshal(fields) - return string(mappingFieldJSON), err -} - func resourceMongoDBAtlasSearchIndexCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { connV2 := meta.(*MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) From ea41526b6fb4fd7d5e2a3fa65b6f0f57c1b67956 Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Thu, 19 Oct 2023 10:36:01 +0200 Subject: [PATCH 09/12] fix doc for resource --- website/docs/r/search_index.html.markdown | 32 +++++++++++------------ 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/website/docs/r/search_index.html.markdown b/website/docs/r/search_index.html.markdown index 9841fc7448..d3220a3d44 100644 --- a/website/docs/r/search_index.html.markdown +++ b/website/docs/r/search_index.html.markdown @@ -31,8 +31,8 @@ resource "mongodbatlas_search_index" "test-basic-search-index" { ### Advanced (with custom analyzers) ```terraform resource "mongodbatlas_search_index" "test-advanced-search-index" { - project_id = "%[1]s" - cluster_name = "%[2]s" + project_id = "" + cluster_name = "" analyzer = "lucene.standard" collection_name = "collection_test" database = "database_test" @@ -74,20 +74,20 @@ EOF analyzers = <<-EOF [{ "name": "index_analyzer_test_name", - "charFilters": { + "charFilters": [{ "type": "mapping", "mappings": {"\\" : "/"} - }, + }], "tokenizer": { "type": "nGram", "minGram": 2, "maxGram": 5 }, - "tokenFilters": { + "tokenFilters": [{ "type": "length", "min": 20, "max": 33 - } + }] }] EOF synonyms { @@ -114,20 +114,20 @@ EOF analyzers = <<-EOF [{ "name": "index_analyzer_test_name", - "charFilters": { + "charFilters": [{ "type": "mapping", "mappings": {"\\" : "/"} - }, + }], "tokenizer": { "type": "nGram", "minGram": 2, "maxGram": 5 }, - "tokenFilters": { + "tokenFilters": [{ "type": "length", "min": 20, "max": 33 - } + }] }] EOF ``` @@ -186,10 +186,10 @@ An [Atlas Search analyzer](https://docs.atlas.mongodb.com/reference/atlas-search * `mongodb` * `charFilters` - Array containing zero or more character filters. Always require a `type` field, and some take additional options as well ```terraform - "charFilters":{ + "charFilters":[{ "type": "", "ADDITIONAL_OPTION": VALUE - } + }] ``` Atlas search supports four `types` of character filters: * [htmlStrip](https://docs.atlas.mongodb.com/reference/atlas-search/analyzers/custom/#std-label-htmlStrip-ref) - Strips out HTML constructs @@ -198,10 +198,10 @@ An [Atlas Search analyzer](https://docs.atlas.mongodb.com/reference/atlas-search ```terraform analyzers = <<-EOF [{ "name": "analyzer_test", - "charFilters":{ + "charFilters":[{ "type": "htmlStrip", "ignoredTags": ["a"] - } + }] }] ``` * [icuNormalize](https://docs.atlas.mongodb.com/reference/atlas-search/analyzers/custom/#std-label-icuNormalize-ref) - Normalizes text with the [ICU](http://site.icu-project.org/) Normalizer. Based on Lucene's [ICUNormalizer2CharFilter](https://lucene.apache.org/core/8_3_0/analyzers-icu/org/apache/lucene/analysis/icu/ICUNormalizer2CharFilter.html) @@ -258,10 +258,10 @@ An [Atlas Search analyzer](https://docs.atlas.mongodb.com/reference/atlas-search * `token_filters` - Array containing zero or more token filters. Always require a type field, and some take additional options as well: ```terraform - "tokenFilters":{ + "tokenFilters":[{ "type": "", "ADDITIONAL-OPTIONS": VALUE - } + }] ``` Atlas Search supports the following token filters: * [daitchMokotoffSoundex](https://docs.atlas.mongodb.com/reference/atlas-search/analyzers/custom/#std-label-daitchmokotoffsoundex-tf-ref) - Creates tokens for words that sound the same based on [Daitch-Mokotoff Soundex](https://en.wikipedia.org/wiki/Daitch%E2%80%93Mokotoff_Soundex) phonetic algorithm. This filter can generate multiple encodings for each input, where each encoded token is a 6 digit number: From c03499189fdcb5d3b82e253d206da42d9ab8a311 Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Thu, 19 Oct 2023 11:10:52 +0200 Subject: [PATCH 10/12] change interface{} to any --- mongodbatlas/data_source_mongodbatlas_search_index.go | 2 +- .../data_source_mongodbatlas_search_indexes.go | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/mongodbatlas/data_source_mongodbatlas_search_index.go b/mongodbatlas/data_source_mongodbatlas_search_index.go index c0a3327b93..4cbddf71a6 100644 --- a/mongodbatlas/data_source_mongodbatlas_search_index.go +++ b/mongodbatlas/data_source_mongodbatlas_search_index.go @@ -90,7 +90,7 @@ func returnSearchIndexDSSchema() map[string]*schema.Schema { } } -func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { projectID, projectIDOk := d.GetOk("project_id") clusterName, clusterNameOK := d.GetOk("cluster_name") indexID, indexIDOk := d.GetOk("index_id") diff --git a/mongodbatlas/data_source_mongodbatlas_search_indexes.go b/mongodbatlas/data_source_mongodbatlas_search_indexes.go index 91d18f9653..0231d25de8 100644 --- a/mongodbatlas/data_source_mongodbatlas_search_indexes.go +++ b/mongodbatlas/data_source_mongodbatlas_search_indexes.go @@ -52,7 +52,7 @@ func dataSourceMongoDBAtlasSearchIndexes() *schema.Resource { } } -func dataSourceMongoDBAtlasSearchIndexesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceMongoDBAtlasSearchIndexesRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { projectID, projectIDOK := d.GetOk("project_id") clusterName, clusterNameOk := d.GetOk("cluster_name") databaseName, databaseNameOK := d.GetOk("database") @@ -87,16 +87,16 @@ func dataSourceMongoDBAtlasSearchIndexesRead(ctx context.Context, d *schema.Reso return nil } -func flattenSearchIndexes(searchIndexes []admin.ClusterSearchIndex, projectID, clusterName string) ([]map[string]interface{}, error) { - var searchIndexesMap []map[string]interface{} +func flattenSearchIndexes(searchIndexes []admin.ClusterSearchIndex, projectID, clusterName string) ([]map[string]any, error) { + var searchIndexesMap []map[string]any if len(searchIndexes) == 0 { return nil, nil } - searchIndexesMap = make([]map[string]interface{}, len(searchIndexes)) + searchIndexesMap = make([]map[string]any, len(searchIndexes)) for i := range searchIndexes { - searchIndexesMap[i] = map[string]interface{}{ + searchIndexesMap[i] = map[string]any{ "project_id": projectID, "cluster_name": clusterName, "analyzer": searchIndexes[i].Analyzer, From 744921dca7424ed7652d0741ac783ff9340ab762 Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Thu, 19 Oct 2023 11:20:59 +0200 Subject: [PATCH 11/12] apply feedback to move var inside if block --- mongodbatlas/resource_mongodbatlas_search_index.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mongodbatlas/resource_mongodbatlas_search_index.go b/mongodbatlas/resource_mongodbatlas_search_index.go index 3591a65876..b5c9c71cec 100644 --- a/mongodbatlas/resource_mongodbatlas_search_index.go +++ b/mongodbatlas/resource_mongodbatlas_search_index.go @@ -205,8 +205,8 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour searchIndex.SearchAnalyzer = stringPtr(d.Get("search_analyzer").(string)) } - dynamic := d.Get("mappings_dynamic").(bool) if d.HasChange("mappings_dynamic") { + dynamic := d.Get("mappings_dynamic").(bool) searchIndex.Mappings.Dynamic = &dynamic } From d12ef1e77f8e2ed261be14288afa5769cfcc1919 Mon Sep 17 00:00:00 2001 From: Leo Antoli Date: Thu, 19 Oct 2023 11:46:16 +0200 Subject: [PATCH 12/12] upgrade test --- ...resource_mongodbatlas_search_index_test.go | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/mongodbatlas/resource_mongodbatlas_search_index_test.go b/mongodbatlas/resource_mongodbatlas_search_index_test.go index 6c8a22fddf..25fabde862 100644 --- a/mongodbatlas/resource_mongodbatlas_search_index_test.go +++ b/mongodbatlas/resource_mongodbatlas_search_index_test.go @@ -9,12 +9,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" - matlas "go.mongodb.org/atlas/mongodbatlas" ) func TestAccClusterRSSearchIndex_basic(t *testing.T) { var ( - index matlas.SearchIndex resourceName = "mongodbatlas_search_index.test" clusterName = acctest.RandomWithPrefix("test-acc-index") projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") @@ -30,7 +28,7 @@ func TestAccClusterRSSearchIndex_basic(t *testing.T) { { Config: testAccMongoDBAtlasSearchIndexConfig(projectID, clusterName), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasSearchIndexExists(resourceName, &index), + testAccCheckMongoDBAtlasSearchIndexExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttr(resourceName, "project_id", projectID), resource.TestCheckResourceAttr(resourceName, "cluster_name", clusterName), @@ -59,7 +57,6 @@ func TestAccClusterRSSearchIndex_basic(t *testing.T) { func TestAccClusterRSSearchIndex_withMapping(t *testing.T) { var ( - index matlas.SearchIndex resourceName = "mongodbatlas_search_index.test" clusterName = acctest.RandomWithPrefix("test-acc-index") projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") @@ -74,7 +71,7 @@ func TestAccClusterRSSearchIndex_withMapping(t *testing.T) { { Config: testAccMongoDBAtlasSearchIndexConfigAdvanced(projectID, clusterName), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasSearchIndexExists(resourceName, &index), + testAccCheckMongoDBAtlasSearchIndexExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttr(resourceName, "project_id", projectID), resource.TestCheckResourceAttr(resourceName, "cluster_name", clusterName), @@ -87,7 +84,6 @@ func TestAccClusterRSSearchIndex_withMapping(t *testing.T) { func TestAccClusterRSSearchIndex_withSynonyms(t *testing.T) { var ( - index matlas.SearchIndex resourceName = "mongodbatlas_search_index.test" datasourceName = "data.mongodbatlas_search_indexes.data_index" clusterName = acctest.RandomWithPrefix("test-acc-index") @@ -104,7 +100,7 @@ func TestAccClusterRSSearchIndex_withSynonyms(t *testing.T) { { Config: testAccMongoDBAtlasSearchIndexConfigSynonyms(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasSearchIndexExists(resourceName, &index), + testAccCheckMongoDBAtlasSearchIndexExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttr(resourceName, "cluster_name", clusterName), resource.TestCheckResourceAttr(resourceName, "analyzer", updatedAnalyzer), @@ -131,7 +127,6 @@ func TestAccClusterRSSearchIndex_withSynonyms(t *testing.T) { func TestAccClusterRSSearchIndex_importBasic(t *testing.T) { var ( - index matlas.SearchIndex resourceName = "mongodbatlas_search_index.test" clusterName = acctest.RandomWithPrefix("test-acc-index") projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") @@ -145,7 +140,7 @@ func TestAccClusterRSSearchIndex_importBasic(t *testing.T) { { Config: testAccMongoDBAtlasSearchIndexConfig(projectID, clusterName), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasSearchIndexExists(resourceName, &index), + testAccCheckMongoDBAtlasSearchIndexExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttr(resourceName, "project_id", projectID), resource.TestCheckResourceAttr(resourceName, "cluster_name", clusterName), @@ -162,10 +157,8 @@ func TestAccClusterRSSearchIndex_importBasic(t *testing.T) { }) } -func testAccCheckMongoDBAtlasSearchIndexExists(resourceName string, index *matlas.SearchIndex) resource.TestCheckFunc { +func testAccCheckMongoDBAtlasSearchIndexExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := testAccProviderSdkV2.Meta().(*MongoDBClient).Atlas - rs, ok := s.RootModule().Resources[resourceName] if !ok { return fmt.Errorf("not found: %s", resourceName) @@ -174,16 +167,14 @@ func testAccCheckMongoDBAtlasSearchIndexExists(resourceName string, index *matla if rs.Primary.ID == "" { return fmt.Errorf("no ID is set") } - ids := decodeStateID(rs.Primary.ID) - indexResponse, _, err := conn.Search.GetIndex(context.Background(), ids["project_id"], ids["cluster_name"], ids["index_id"]) - if err == nil { - *index = *indexResponse - return nil + connV2 := testAccProviderSdkV2.Meta().(*MongoDBClient).AtlasV2 + _, _, err := connV2.AtlasSearchApi.GetAtlasSearchIndex(context.Background(), ids["project_id"], ids["cluster_name"], ids["index_id"]).Execute() + if err != nil { + return fmt.Errorf("index (%s) does not exist", ids["index_id"]) } - - return fmt.Errorf("index (%s) does not exist", ids["index_id"]) + return nil } }