Skip to content

Commit

Permalink
Add documentation and sample
Browse files Browse the repository at this point in the history
Signed-off-by: Russ Cam <russcam@canva.com>
  • Loading branch information
russcam committed Oct 24, 2023
1 parent 45d59a6 commit dd87d7d
Show file tree
Hide file tree
Showing 2 changed files with 182 additions and 0 deletions.
79 changes: 79 additions & 0 deletions guides/index_templates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
- [Index templates](#index-templates)
- [Setup](#setup)


# Index templates

Index templates let you initialize new indexes with predefined mappings and settings.
For example, if you continuously index log data, you can define an index template so that all of these indexes have
the same number of shards and replicas.

## Setup

To get started, first create a client, create an index template. In this example, an index template is created,
composed of two component templates:

- `index-settings` which specifies index settings such as shard configuration and slowlog settings
- `index-mappings` which specifies the field mappings

```java
import org.apache.hc.core5.http.HttpHost;

final HttpHost[] hosts = new HttpHost[] {
new HttpHost("http", "localhost", 9200)
};

final OpenSearchTransport transport = ApacheHttpClient5TransportBuilder
.builder(hosts)
.setMapper(new JacksonJsonpMapper())
.build();
OpenSearchClient client = new OpenSearchClient(transport);

final var indexSettingsComponentTemplate = "index-settings";
PutComponentTemplateRequest putComponentTemplateRequest = PutComponentTemplateRequest.of(
c -> c.name(indexSettingsComponentTemplate)
.settings(
s -> s.numberOfShards("2")
.numberOfReplicas("1")
.indexing(
i -> i.slowlog(
sl -> sl.level("info")
.reformat(true)
.threshold(th -> th.index(ith -> ith.warn(Time.of(t -> t.time("2s")))))
)
)
.search(
se -> se.slowlog(sl -> sl.level("info").threshold(th -> th.query(q -> q.warn(Time.of(t -> t.time("2s"))))))
)
)
);
client.cluster().putComponentTemplate(putComponentTemplateRequest);

final var indexMappingsComponentTemplate = "index-mappings";
putComponentTemplateRequest = PutComponentTemplateRequest.of(
c -> c.name(indexMappingsComponentTemplate).mappings(m -> m.properties("age", p -> p.integer(i -> i)))
);
client.cluster().putComponentTemplate(putComponentTemplateRequest);

final var indexTemplateName = "my-index-template";
PutIndexTemplateRequest putIndexTemplateRequest = PutIndexTemplateRequest.of(
it -> it.name(indexTemplateName)
.indexPatterns("my-index-*")
.composedOf(List.of(indexSettingsComponentTemplate, indexMappingsComponentTemplate))
);

client.indices().putIndexTemplate(putIndexTemplateRequest);
```

## Usage

Create an index with a name that matches the index template's `indexPatterns`

```java
String indexName = "my-index-1";
client.indices().create(CreateIndexRequest.of(c -> c.index(indexName)));
```

The index will be created with the index settings and mappings defined by the `my-index-template` index template.

You can find a working sample of the above code in [IndexTemplates.java](../samples/src/main/java/org/opensearch/client/samples/IndexTemplates.java).
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

package org.opensearch.client.samples;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opensearch.client.opensearch._types.Time;
import org.opensearch.client.opensearch.cluster.PutComponentTemplateRequest;
import org.opensearch.client.opensearch.indices.*;

import java.util.List;

/**
* Run with: <c>./gradlew :samples:run -Dsamples.mainClass=IndexTemplates</c>
*/
public class IndexTemplates {
private static final Logger LOGGER = LogManager.getLogger(IndexTemplates.class);

public static void main(String[] args) {
try {
var client = SampleClient.create();

var version = client.info().version();
LOGGER.info("Server: {}@{}", version.distribution(), version.number());

final var indexTemplateName = "my-index-template";

if (!client.indices().existsIndexTemplate(t -> t.name(indexTemplateName)).value()) {
DeleteIndexTemplateRequest deleteIndexTemplateRequest = DeleteIndexTemplateRequest.of(i -> i.name(indexTemplateName));

LOGGER.info("Deleting index template {}", indexTemplateName);
client.indices().deleteIndexTemplate(deleteIndexTemplateRequest);
}

// Create an index template composed of two component templates, one for index settings, and one for mappings
String indexSettingsComponentTemplate = "index-settings";
PutComponentTemplateRequest putComponentTemplateRequest = PutComponentTemplateRequest.of(
c -> c.name(indexSettingsComponentTemplate)
.settings(
s -> s.numberOfShards("2")
.numberOfReplicas("1")
.indexing(
i -> i.slowlog(
sl -> sl.level("info")
.reformat(true)
.threshold(th -> th.index(ith -> ith.warn(Time.of(t -> t.time("2s")))))
)
)
.search(
se -> se.slowlog(sl -> sl.level("info").threshold(th -> th.query(q -> q.warn(Time.of(t -> t.time("2s"))))))
)
)
);
LOGGER.info("Creating component template {}", indexSettingsComponentTemplate);
client.cluster().putComponentTemplate(putComponentTemplateRequest);

String indexMappingsComponentTemplate = "index-mappings";
putComponentTemplateRequest = PutComponentTemplateRequest.of(
c -> c.name(indexMappingsComponentTemplate).mappings(m -> m.properties("age", p -> p.integer(i -> i)))
);
LOGGER.info("Creating component template {}", indexMappingsComponentTemplate);
client.cluster().putComponentTemplate(putComponentTemplateRequest);

PutIndexTemplateRequest putIndexTemplateRequest = PutIndexTemplateRequest.of(
it -> it.name(indexTemplateName)
.indexPatterns("my-index-*")
.composedOf(List.of(indexSettingsComponentTemplate, indexMappingsComponentTemplate))
);

LOGGER.info("Creating index template {}", indexTemplateName);
client.indices().putIndexTemplate(putIndexTemplateRequest);

String indexName = "my-index-1";
if (client.indices().exists(r -> r.index(indexName)).value()) {
LOGGER.info("Deleting index {}", indexName);
client.indices().delete(DeleteIndexRequest.of(d -> d.index(indexName)));
}

LOGGER.info("Creating index {}", indexName);
client.indices().create(CreateIndexRequest.of(c -> c.index(indexName)));

GetMappingResponse getMappingResponse = client.indices().getMapping(GetMappingRequest.of(m -> m.index(indexName)));
// mappings for the index should contain those defined in component template
LOGGER.info("Mappings {} found for index {}", getMappingResponse.result().get(indexName).mappings(), indexName);

GetIndicesSettingsResponse getSettingsResponse = client.indices()
.getSettings(GetIndicesSettingsRequest.of(m -> m.index(indexName)));
// settings for the index should contain those defined in component template
LOGGER.info("Settings {} found for index {}", getSettingsResponse.result().get(indexName).settings(), indexName);

LOGGER.info("Deleting index {}", indexName);
client.indices().delete(DeleteIndexRequest.of(d -> d.index(indexName)));
} catch (Exception e) {
LOGGER.error("Unexpected exception", e);
}
}
}

0 comments on commit dd87d7d

Please sign in to comment.