Skip to content

Commit

Permalink
Merge pull request #102 from k-yomo/add-primary-index-name-field
Browse files Browse the repository at this point in the history
Add primary index name field
  • Loading branch information
k-yomo authored May 23, 2022
2 parents 2cb6853 + 115c14d commit 68274d1
Show file tree
Hide file tree
Showing 12 changed files with 219 additions and 70 deletions.
1 change: 1 addition & 0 deletions docs/data-sources/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ data "algolia_index" "example" {
- `languages_config` (List of Object) The configuration for languages in index setting. (see [below for nested schema](#nestedatt--languages_config))
- `pagination_config` (Block List) The configuration for pagination in index setting. (see [below for nested schema](#nestedblock--pagination_config))
- `performance_config` (List of Object) The configuration for performance in index setting. (see [below for nested schema](#nestedatt--performance_config))
- `primary_index_name` (String) The name of the existing primary index name. This field is filled when the index is a replica index.
- `query_strategy_config` (List of Object) The configuration for query strategy in index setting. (see [below for nested schema](#nestedatt--query_strategy_config))
- `ranking_config` (List of Object) The configuration for ranking. (see [below for nested schema](#nestedatt--ranking_config))
- `typos_config` (List of Object) The configuration for typos in index setting. (see [below for nested schema](#nestedatt--typos_config))
Expand Down
1 change: 1 addition & 0 deletions docs/data-sources/virtual_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ data "algolia_virtual_index" "example" {
- `languages_config` (List of Object) The configuration for languages in index setting. (see [below for nested schema](#nestedatt--languages_config))
- `pagination_config` (Block List) The configuration for pagination in index setting. (see [below for nested schema](#nestedblock--pagination_config))
- `performance_config` (List of Object) The configuration for performance in index setting. (see [below for nested schema](#nestedatt--performance_config))
- `primary_index_name` (String) The name of the existing primary index name. This field is filled when the index is a replica index.
- `query_strategy_config` (List of Object) The configuration for query strategy in index setting. (see [below for nested schema](#nestedatt--query_strategy_config))
- `ranking_config` (List of Object) The configuration for ranking. (see [below for nested schema](#nestedatt--ranking_config))
- `typos_config` (List of Object) The configuration for typos in index setting. (see [below for nested schema](#nestedatt--typos_config))
Expand Down
2 changes: 1 addition & 1 deletion docs/resources/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ resource "algolia_index" "example" {
- `languages_config` (Block List, Max: 1) The configuration for languages in index setting. (see [below for nested schema](#nestedblock--languages_config))
- `pagination_config` (Block List, Max: 1) The configuration for pagination in index setting. (see [below for nested schema](#nestedblock--pagination_config))
- `performance_config` (Block List, Max: 1) The configuration for performance in index setting. (see [below for nested schema](#nestedblock--performance_config))
- `primary_index_name` (String) The name of the existing primary index name. This field is used to create a replica index.
- `query_strategy_config` (Block List, Max: 1) The configuration for query strategy in index setting. (see [below for nested schema](#nestedblock--query_strategy_config))
- `ranking_config` (Block List, Max: 1) The configuration for ranking. (see [below for nested schema](#nestedblock--ranking_config))
- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts))
Expand Down Expand Up @@ -207,7 +208,6 @@ Optional:
- `custom_ranking` (List of String) List of attributes for custom ranking criterion.
- `ranking` (List of String) List of ranking criteria.
- `relevancy_strictness` (Number) Relevancy threshold below which less relevant results aren’t included in the results
- `replicas` (Set of String) List of replica names. Names of virtual replicas should be surrounded with `virtual()`.


<a id="nestedblock--timeouts"></a>
Expand Down
6 changes: 3 additions & 3 deletions docs/resources/virtual_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,11 @@ resource "algolia_index" "example" {
]
attributes_to_retrieve = ["*"]
}
replicas = ["virtual(example_replica)"]
}
resource "algolia_virtual_index" "example_virtual_replica" {
name = "example_replica"
name = "example_replica"
primary_index_name = algolia_index.example.name
attributes_config {
unretrievable_attributes = [
Expand Down Expand Up @@ -58,6 +57,7 @@ resource "algolia_virtual_index" "example_virtual_replica" {
### Required

- `name` (String) Name of the virtual index. Its name should NOT be surrounded with `virtual()`.
- `primary_index_name` (String) The name of the existing primary index name.

### Optional

Expand Down
5 changes: 2 additions & 3 deletions examples/resources/algolia_virtual_index/resource.tf
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@ resource "algolia_index" "example" {
]
attributes_to_retrieve = ["*"]
}

replicas = ["virtual(example_replica)"]
}

resource "algolia_virtual_index" "example_virtual_replica" {
name = "example_replica"
name = "example_replica"
primary_index_name = algolia_index.example.name

attributes_config {
unretrievable_attributes = [
Expand Down
5 changes: 5 additions & 0 deletions internal/provider/data_source_index.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ func dataSourceIndex() *schema.Resource {
ForceNew: true,
Description: "Name of the index.",
},
"primary_index_name": {
Type: schema.TypeString,
Computed: true,
Description: "The name of the existing primary index name. This field is filled when the index is a replica index.",
},
"virtual": {
Type: schema.TypeBool,
Computed: true,
Expand Down
1 change: 0 additions & 1 deletion internal/provider/data_source_index_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ func TestAccDataSourceIndex(t *testing.T) {
testCheckResourceListAttr(dataSourceName, "attributes_config.0.unretrievable_attributes", []string{"author_email"}),
testCheckResourceListAttr(dataSourceName, "attributes_config.0.attributes_to_retrieve", []string{"body", "category", "description", "tag", "title"}),
testCheckResourceListAttr(dataSourceName, "ranking_config.0.ranking", []string{"words", "proximity"}),
resource.TestCheckNoResourceAttr(dataSourceName, "ranking_config.0.replicas.0"),
resource.TestCheckResourceAttr(dataSourceName, "faceting_config.0.max_values_per_facet", "50"),
resource.TestCheckResourceAttr(dataSourceName, "faceting_config.0.sort_facet_values_by", "alpha"),
),
Expand Down
5 changes: 5 additions & 0 deletions internal/provider/data_source_virtual_index.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ func dataSourceVirtualIndex() *schema.Resource {
ForceNew: true,
Description: "Name of the index.",
},
"primary_index_name": {
Type: schema.TypeString,
Computed: true,
Description: "The name of the existing primary index name. This field is filled when the index is a replica index.",
},
"attributes_config": {
Type: schema.TypeList,
Computed: true,
Expand Down
86 changes: 68 additions & 18 deletions internal/provider/resource_index.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ func resourceIndex() *schema.Resource {
ForceNew: true,
Description: "Name of the index / replica index. For creating virtual replica, use `algolia_virtual_index` resource instead.",
},
"primary_index_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The name of the existing primary index name. This field is used to create a replica index.",
},
"virtual": {
Type: schema.TypeBool,
Optional: true,
Expand Down Expand Up @@ -113,13 +119,6 @@ func resourceIndex() *schema.Resource {
ValidateFunc: validation.IntBetween(0, 100),
Description: "Relevancy threshold below which less relevant results aren’t included in the results",
},
"replicas": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Optional: true,
Description: "List of replica names. Names of virtual replicas should be surrounded with `virtual()`.",
},
},
},
},
Expand Down Expand Up @@ -583,6 +582,33 @@ func resourceIndexCreate(ctx context.Context, d *schema.ResourceData, m interfac
apiClient := m.(*apiClient)

indexName := d.Get("name").(string)

if primaryIndexName, ok := d.GetOk("primary_index_name"); ok {
primaryIndex := apiClient.searchClient.InitIndex(primaryIndexName.(string))
primaryIndexSettings, err := primaryIndex.GetSettings(ctx)
if err != nil {
return diag.FromErr(err)
}
replicaExist := false
for _, replica := range primaryIndexSettings.Replicas.Get() {
if replica == indexName {
replicaExist = true
}
}
if !replicaExist {
newReplicas := append(primaryIndexSettings.Replicas.Get(), indexName)
res, err := primaryIndex.SetSettings(search.Settings{
Replicas: opt.Replicas(newReplicas...),
})
if err != nil {
return diag.FromErr(err)
}
if err := res.Wait(); err != nil {
return diag.FromErr(err)
}
}
}

index := apiClient.searchClient.InitIndex(indexName)
res, err := index.SetSettings(mapToIndexSettings(d))
if err != nil {
Expand Down Expand Up @@ -620,18 +646,43 @@ func resourceIndexUpdate(ctx context.Context, d *schema.ResourceData, m interfac
}

func resourceIndexDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
apiClient := m.(*apiClient)

if d.Get("deletion_protection").(bool) {
return diag.Errorf("cannot destroy index without setting deletion_protection=false and running `terraform apply`")
}

index := apiClient.searchClient.InitIndex(d.Id())
res, err := index.Delete(ctx)
apiClient := m.(*apiClient)
indexName := d.Id()

if primaryIndexName, ok := d.GetOk("primary_index_name"); ok {
primaryIndex := apiClient.searchClient.InitIndex(primaryIndexName.(string))
primaryIndexSettings, err := primaryIndex.GetSettings(ctx)
if err != nil {
return diag.FromErr(err)
}
var newReplicas []string
for _, replica := range primaryIndexSettings.Replicas.Get() {
if replica == indexName {
continue
}
newReplicas = append(newReplicas, replica)
}
updateReplicasRes, err := primaryIndex.SetSettings(search.Settings{
Replicas: opt.Replicas(newReplicas...),
})
if err != nil {
return diag.FromErr(err)
}
if err := updateReplicasRes.Wait(); err != nil {
return diag.FromErr(err)
}
}

index := apiClient.searchClient.InitIndex(indexName)
deleteIndexRes, err := index.Delete(ctx)
if err != nil {
return diag.FromErr(err)
}
if err := res.Wait(ctx); err != nil {
if err := deleteIndexRes.Wait(ctx); err != nil {
return diag.FromErr(err)
}

Expand Down Expand Up @@ -670,10 +721,11 @@ func mapToIndexResourceValues(d *schema.ResourceData, settings search.Settings)
isVirtualIndex := d.Get("virtual").(bool)

return map[string]interface{}{
"name": d.Id(),
"virtual": isVirtualIndex,
"attributes_config": marshalAttributesConfig(settings, isVirtualIndex),
"ranking_config": marshalRankingConfig(settings, isVirtualIndex),
"name": d.Id(),
"primary_index_name": settings.Primary.Get(),
"virtual": isVirtualIndex,
"attributes_config": marshalAttributesConfig(settings, isVirtualIndex),
"ranking_config": marshalRankingConfig(settings, isVirtualIndex),
"faceting_config": []interface{}{map[string]interface{}{
"max_values_per_facet": settings.MaxValuesPerFacet.Get(),
"sort_facet_values_by": settings.SortFacetValuesBy.Get(),
Expand Down Expand Up @@ -720,7 +772,6 @@ func marshalRankingConfig(settings search.Settings, isVirtualIndex bool) []inter
}
if !isVirtualIndex {
rankingConfig["ranking"] = settings.Ranking.Get()
rankingConfig["replicas"] = settings.Replicas.Get()
}

return []interface{}{rankingConfig}
Expand Down Expand Up @@ -905,7 +956,6 @@ func unmarshalRankingConfig(configured interface{}, settings *search.Settings, i
settings.RelevancyStrictness = opt.RelevancyStrictness(config["relevancy_strictness"].(int))
if !isVirtualIndex {
settings.Ranking = opt.Ranking(castStringList(config["ranking"])...)
settings.Replicas = opt.Replicas(castStringSet(config["replicas"])...)
}
}

Expand Down
50 changes: 48 additions & 2 deletions internal/provider/resource_index_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ func TestAccResourceIndex(t *testing.T) {
resource.TestCheckNoResourceAttr(resourceName, "attributes_config.0.unretrievable_attributes.0"),
resource.TestCheckResourceAttr(resourceName, "attributes_config.0.attributes_to_retrieve.0", "*"),
testCheckResourceListAttr(resourceName, "ranking_config.0.ranking", []string{"typo", "geo", "words", "filters", "proximity", "attribute", "exact", "custom"}),
resource.TestCheckNoResourceAttr(resourceName, "ranking_config.0.replicas.0"),
testCheckResourceListAttr(resourceName, "highlight_and_snippet_config.0.attributes_to_highlight", []string{}),
testCheckResourceListAttr(resourceName, "highlight_and_snippet_config.0.attributes_to_snippet", []string{}),
resource.TestCheckResourceAttr(resourceName, "highlight_and_snippet_config.0.highlight_pre_tag", "<em>"),
Expand All @@ -54,7 +53,6 @@ func TestAccResourceIndex(t *testing.T) {
testCheckResourceListAttr(resourceName, "attributes_config.0.unretrievable_attributes", []string{"author_email"}),
testCheckResourceListAttr(resourceName, "attributes_config.0.attributes_to_retrieve", []string{"body", "category", "description", "tag", "title"}),
testCheckResourceListAttr(resourceName, "ranking_config.0.ranking", []string{"words", "proximity"}),
resource.TestCheckNoResourceAttr(resourceName, "ranking_config.0.replicas.0"),
resource.TestCheckResourceAttr(resourceName, "faceting_config.0.max_values_per_facet", "50"),
resource.TestCheckResourceAttr(resourceName, "faceting_config.0.sort_facet_values_by", "alpha"),
testCheckResourceListAttr(resourceName, "highlight_and_snippet_config.0.attributes_to_highlight", []string{"title"}),
Expand Down Expand Up @@ -86,6 +84,36 @@ func TestAccResourceIndex(t *testing.T) {
})
}

func TestAccResourceIndexWithReplica(t *testing.T) {
// NOTE: Deleting replica fails due to the same reason as the below issue.
// https://github.com/algolia/algoliasearch-client-javascript/issues/1377
// TODO: Remove t.Skip() once the issue is resolved.
t.Skip()

primaryIndexName := randStringStartWithAlpha(80)
replicaIndexName := fmt.Sprintf("%s_replica", primaryIndexName)
primaryIndexResourceName := fmt.Sprintf("algolia_index.%s", primaryIndexName)
replicaIndexResourceName := fmt.Sprintf("algolia_index.%s", replicaIndexName)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: testAccResourceIndexWithReplica(primaryIndexName, replicaIndexName),
Check: resource.ComposeTestCheckFunc(
// primary index
resource.TestCheckResourceAttr(primaryIndexResourceName, "name", primaryIndexName),
// replica index
resource.TestCheckResourceAttr(replicaIndexResourceName, "name", replicaIndexName),
resource.TestCheckResourceAttr(replicaIndexResourceName, "primary_index_name", primaryIndexName),
),
},
},
CheckDestroy: testAccCheckIndexDestroy,
})
}

func testAccResourceIndex(name string) string {
return fmt.Sprintf(`
resource "algolia_index" "%s" {
Expand Down Expand Up @@ -164,6 +192,24 @@ resource "algolia_index" "` + name + `" {
`
}

// nolint:unused
func testAccResourceIndexWithReplica(name string, replicaName string) string {
return `
resource "algolia_index" "` + name + `" {
name = "` + name + `"
deletion_protection = false
}
resource "algolia_index" "` + replicaName + `" {
name = "` + replicaName + `"
primary_index_name = algolia_index.` + name + `.name
deletion_protection = false
}
`
}

func testAccCheckIndexDestroy(s *terraform.State) error {
apiClient := newTestAPIClient()
for _, rs := range s.RootModule().Resources {
Expand Down
Loading

0 comments on commit 68274d1

Please sign in to comment.