下面列出了怎么用org.elasticsearch.action.admin.indices.create.CreateIndexRequest的API类实例代码及写法,或者点击链接到github查看源代码。
public void setup() throws IOException, NoSuchFieldException, IllegalAccessException {
String key;
CreateIndexResponse ciResp;
Reflections reflections = new Reflections("org.apache.usergrid.chop.webapp.dao");
Set<Class<? extends Dao>> daoClasses = reflections.getSubTypesOf(Dao.class);
IndicesAdminClient client = elasticSearchClient.getClient().admin().indices();
for (Class<? extends Dao> daoClass : daoClasses) {
key = daoClass.getDeclaredField("DAO_INDEX_KEY").get(null).toString();
if (!client.exists(new IndicesExistsRequest(key)).actionGet().isExists()) {
ciResp = client.create(new CreateIndexRequest(key)).actionGet();
if (ciResp.isAcknowledged()) {
LOG.debug("Index for key {} didn't exist, now created", key);
} else {
LOG.debug("Could not create index for key: {}", key);
}
} else {
LOG.debug("Key {} already exists", key);
}
}
}
@Override
protected void populateData(TransportClient tc) {
try {
tc.admin().indices().create(new CreateIndexRequest("logs").mapping("_doc", FileHelper.loadFile("dlsfls/masked_field_mapping.json"), XContentType.JSON)).actionGet();
byte[] data = FileHelper.loadFile("dlsfls/logs_bulk_data.json").getBytes(StandardCharsets.UTF_8);
BulkRequest br = new BulkRequest().add(data, 0, data.length, XContentType.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE);
if(tc.bulk(br).actionGet().hasFailures()) {
Assert.fail("bulk import failed");
}
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.toString());
}
}
protected void populateData(TransportClient tc) {
tc.admin().indices().create(new CreateIndexRequest("deals")
.mapping("deals", "timestamp","type=date","@timestamp","type=date")).actionGet();
try {
String doc = FileHelper.loadFile("dlsfls/doc1.json");
for (int i = 0; i < 10; i++) {
final String moddoc = doc.replace("<name>", "cust" + i).replace("<employees>", "" + i).replace("<date>", "1970-01-02");
tc.index(new IndexRequest("deals").type("deals").id("0" + i).setRefreshPolicy(RefreshPolicy.IMMEDIATE).source(moddoc, XContentType.JSON)).actionGet();
}
} catch (IOException e) {
Assert.fail(e.toString());
}
}
protected void populateData(TransportClient tc) {
tc.admin().indices().create(new CreateIndexRequest("deals")
.mapping("deals", "timestamp","type=date","@timestamp","type=date")).actionGet();
try {
String doc = FileHelper.loadFile("dlsfls/doc1.json");
for (int i = 0; i < 10; i++) {
final String moddoc = doc.replace("<name>", "cust" + i).replace("<employees>", "" + i).replace("<date>", "1970-01-02");
tc.index(new IndexRequest("deals").type("deals").id("0" + i).setRefreshPolicy(RefreshPolicy.IMMEDIATE).source(moddoc, XContentType.JSON)).actionGet();
}
} catch (IOException e) {
Assert.fail(e.toString());
}
}
@Override
public boolean create(IndexDto indexDto) throws IOException {
CreateIndexRequest request = new CreateIndexRequest(indexDto.getIndexName());
request.settings(Settings.builder()
.put("index.number_of_shards", indexDto.getNumberOfShards())
.put("index.number_of_replicas", indexDto.getNumberOfReplicas())
);
if (StrUtil.isNotEmpty(indexDto.getType()) && StrUtil.isNotEmpty(indexDto.getMappingsSource())) {
//mappings
request.mapping(indexDto.getType(), indexDto.getMappingsSource(), XContentType.JSON);
}
CreateIndexResponse response = elasticsearchRestTemplate.getClient()
.indices()
.create(request, RequestOptions.DEFAULT);
return response.isAcknowledged();
}
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
container.start();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASSWORD));
RestClientBuilder builder = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
client = new RestHighLevelClient(builder);
client.indices().create(new CreateIndexRequest(INDEX), RequestOptions.DEFAULT);
reporter.reset();
}
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
// Start the container
container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
container.start();
// Create the client
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASSWORD));
RestClientBuilder builder = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
client = new RestHighLevelClient(builder);
client.indices().create(new CreateIndexRequest(INDEX), RequestOptions.DEFAULT);
reporter.reset();
}
private CreateIndexRequest createIndexRequest() {
val docObject = new JsonObject();
docObject.addProperty("dynamic", "false");
docObject.add("properties", buildMappingsJson());
val mapObject = new JsonObject();
mapObject.add(properties.getDocType(), docObject);
val request = new CreateIndexRequest(properties.getIndexName());
request.settings(Settings.builder()
.put("index.number_of_shards", 5)
.put("index.number_of_replicas", 3)
);
request.mapping(properties.getDocType(), mapObject.toString(), XContentType.JSON);
return request;
}
private CreateIndexRequest createIndexRequest() {
val docObject = new JsonObject();
docObject.addProperty("dynamic", "false");
docObject.add("properties", buildMappingsJson());
val mapObject = new JsonObject();
mapObject.add(properties.getDetectorDocType(), docObject);
val request = new CreateIndexRequest(properties.getDetectorIndexName());
request.settings(Settings.builder()
.put("index.number_of_shards", 5)
.put("index.number_of_replicas", 3)
);
request.mapping(properties.getDetectorDocType(), mapObject.toString(), XContentType.JSON);
return request;
}
private void createIndexAndExecuteUpsertRequest(final UpsertByIdNode.Item item,
final SettableFuture<TaskResult> futureResult) {
transportCreateIndexAction.execute(
new CreateIndexRequest(item.index()).cause("upsert single item"),
new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse createIndexResponse) {
executeUpsertRequest(item, futureResult);
}
@Override
public void onFailure(Throwable e) {
e = ExceptionsHelper.unwrapCause(e);
if (e instanceof IndexAlreadyExistsException) {
executeUpsertRequest(item, futureResult);
} else {
futureResult.setException(e);
}
}
});
}
@Override
protected void doExecute(final Task task, final DeleteRequest request, final ActionListener<DeleteResponse> listener) {
ClusterState state = clusterService.state();
if (autoCreateIndex.shouldAutoCreate(request.index(), state)) {
createIndexAction.execute(task, new CreateIndexRequest(request).index(request.index()).cause("auto(delete api)")
.masterNodeTimeout(request.timeout()), new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse result) {
innerExecute(task, request, listener);
}
@Override
public void onFailure(Throwable e) {
if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
// we have the index, do it
innerExecute(task, request, listener);
} else {
listener.onFailure(e);
}
}
});
} else {
innerExecute(task, request, listener);
}
}
private void addIndex(String indexName) {
try {
elasticSearchClient.admin()
.indices()
.prepareGetIndex()
.addIndices(indexName)
.execute()
.actionGet();
} catch (IndexNotFoundException infe) {
try {
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
createIndexRequest.settings(Settings.builder()
.put("index.number_of_shards", config.getElasticSearchIndexShardCount())
.put("index.number_of_replicas", config.getElasticSearchIndexReplicationCount())
);
elasticSearchClient.admin()
.indices()
.create(createIndexRequest)
.actionGet();
} catch (ResourceAlreadyExistsException done) {
// no-op
}
}
}
private void createIndex(String indexName) {
try {
elasticSearchClient.admin().indices().prepareGetIndex().addIndices(indexName).execute().actionGet();
} catch (IndexNotFoundException infe) {
try {
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
createIndexRequest.settings(Settings.builder()
.put("index.number_of_shards", config.getElasticSearchIndexShardCount())
.put("index.number_of_replicas", config.getElasticSearchIndexReplicationCount())
);
elasticSearchClient.admin()
.indices()
.create(createIndexRequest)
.actionGet();
} catch (ResourceAlreadyExistsException done) {
LOGGER.error("Failed to update log index name: {}", indexName, done);
}
}
}
@Override
public boolean createIndex(IndexMetadata indexMetadata, String mapping) {
CreateIndexRequest request = new CreateIndexRequest(indexMetadata.getName());
request.settings(Settings.builder()
.put("index.number_of_shards", properties.getShardsPerIndex())
.put("index.number_of_replicas", properties.getReplicasPerShard())
);
if (properties.isAutoTemplateMapping()) {
request.mapping(TYPE, mapping, XContentType.JSON);
}
try {
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
return createIndexResponse.isAcknowledged();
} catch (IOException e) {
log.error("Error creating '{}' index on Elasticsearch.", indexMetadata.getName(), e);
}
return false;
}
public static boolean createIndex(RestHighLevelClient client, String indexName, String indexType) {
GetIndexRequest request = new GetIndexRequest();
request.indices(indexName);
try {
if (!client.indices().exists(request)) {
LOGGER.info("index {} does not exist, creating one", indexName);
CreateIndexRequest createReq = new CreateIndexRequest(indexName);
createReq.settings(getResourceContent(SETTINGS_RESOURCE_NAME), JSON);
createReq.mapping(indexType, getResourceContent(MAPPING_RESOURCE_NAME), JSON);
client.indices().create(createReq);
return true;
}
} catch (IOException e) {
throw new ConfigurationException(e);
}
return false;
}
private void createIndexIfNeeded() throws IOException {
GetIndexRequest request = new GetIndexRequest();
request.indices(elasticSearchConfig.getIndexName());
boolean exists = getClient().indices().exists(request);
if (!exists) {
CreateIndexRequest cireq = new CreateIndexRequest(elasticSearchConfig.getIndexName());
cireq.settings(Settings.builder()
.put("index.number_of_shards", elasticSearchConfig.getIndexNumberOfShards())
.put("index.number_of_replicas", elasticSearchConfig.getIndexNumberOfReplicas()));
CreateIndexResponse ciresp = getClient().indices().create(cireq);
if (!ciresp.isAcknowledged() || !ciresp.isShardsAcknowledged()) {
throw new RuntimeException("Unable to create index.");
}
}
}
/**
* createIndexIfMissing
* @param indexName indexName
*/
public void createIndexIfMissing(String indexName) {
// Synchronize this on a static class level
if (!this.manager.client()
.admin()
.indices()
.exists(new IndicesExistsRequest(indexName))
.actionGet()
.isExists()) {
// It does not exist... So we are going to need to create the index.
// we are going to assume that the 'templates' that we have loaded into
// elasticsearch are sufficient to ensure the index is being created properly.
CreateIndexResponse response = this.manager.client().admin().indices().create(new CreateIndexRequest(indexName)).actionGet();
if (response.isAcknowledged()) {
LOGGER.info("Index Created: {}", indexName);
} else {
LOGGER.error("Index {} did not exist. While attempting to create the index from stored ElasticSearch Templates we were unable to get an acknowledgement.", indexName);
LOGGER.error("Error Message: {}", response.toString());
throw new RuntimeException("Unable to create index " + indexName);
}
}
}
@BeforeClass
public void prepareTest() throws Exception {
testConfiguration = new StreamsConfigurator<>(TwitterUserstreamElasticsearchConfiguration.class).detectCustomConfiguration();
testClient = ElasticsearchClientManager.getInstance(testConfiguration.getElasticsearch()).client();
ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);
IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getElasticsearch().getIndex());
IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
if(indicesExistsResponse.isExists()) {
DeleteIndexRequest deleteIndexRequest = Requests.deleteIndexRequest(testConfiguration.getElasticsearch().getIndex());
DeleteIndexResponse deleteIndexResponse = testClient.admin().indices().delete(deleteIndexRequest).actionGet();
assertTrue(deleteIndexResponse.isAcknowledged());
};
CreateIndexRequest createIndexRequest = Requests.createIndexRequest(testConfiguration.getElasticsearch().getIndex());
CreateIndexResponse createIndexResponse = testClient.admin().indices().create(createIndexRequest).actionGet();
assertTrue(createIndexResponse.isAcknowledged());
}
public static void ensureIndex(ElasticsearchConnection connection, final String table) {
IndicesExistsRequest indicesExistsRequest = new IndicesExistsRequest().indices(table);
IndicesExistsResponse indicesExistsResponse = connection.getClient()
.admin()
.indices()
.exists(indicesExistsRequest)
.actionGet();
if(!indicesExistsResponse.isExists()) {
Settings indexSettings = Settings.builder()
.put("number_of_replicas", 0)
.build();
CreateIndexRequest createRequest = new CreateIndexRequest(table).settings(indexSettings);
connection.getClient()
.admin()
.indices()
.create(createRequest)
.actionGet();
}
}
@Test
public void testKibanaAlias() throws Exception {
final Settings settings = Settings.builder()
.build();
setup(settings);
try (TransportClient tc = getInternalTransportClient()) {
String body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
Map indexSettings = new HashMap();
indexSettings.put("number_of_shards", 1);
indexSettings.put("number_of_replicas", 0);
tc.admin().indices().create(new CreateIndexRequest(".kibana-6")
.alias(new Alias(".kibana"))
.settings(indexSettings))
.actionGet();
tc.index(new IndexRequest(".kibana-6").type("doc").id("6.2.2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source(body, XContentType.JSON)).actionGet();
}
final RestHelper rh = nonSslRestHelper();
HttpResponse res;
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest(".kibana-6/doc/6.2.2?pretty", encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode());
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest(".kibana/doc/6.2.2?pretty", encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode());
System.out.println(res.getBody());
}
@Test
public void testKibanaAlias65() throws Exception {
final Settings settings = Settings.builder()
.build();
setup(settings);
try (TransportClient tc = getInternalTransportClient()) {
String body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
Map indexSettings = new HashMap();
indexSettings.put("number_of_shards", 1);
indexSettings.put("number_of_replicas", 0);
tc.admin().indices().create(new CreateIndexRequest(".kibana_1")
.alias(new Alias(".kibana"))
.settings(indexSettings))
.actionGet();
tc.index(new IndexRequest(".kibana_1").type("doc").id("6.2.2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source(body, XContentType.JSON)).actionGet();
tc.index(new IndexRequest(".kibana_-900636979_kibanaro").type("doc").id("6.2.2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source(body, XContentType.JSON)).actionGet();
}
final RestHelper rh = nonSslRestHelper();
HttpResponse res;
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest(".kibana/doc/6.2.2?pretty", new BasicHeader("securitytenant", "__user__"), encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode());
System.out.println(res.getBody());
Assert.assertTrue(res.getBody().contains(".kibana_-900636979_kibanaro"));
}
@Override
protected void populateData(TransportClient tc) {
String mapping = "{" +
" \"mytype\" : {" +
" \"properties\" : {" +
" \"amount\" : {\"type\": \"integer\"}," +
" \"owner\" : {\"type\": \"text\"}," +
" \"my_nested_object\" : {\"type\" : \"nested\"}" +
" }" +
" }" +
" }" +
"";
tc.admin().indices().create(new CreateIndexRequest("deals")
.settings(Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build())
.mapping("mytype", mapping, XContentType.JSON)).actionGet();
//tc.index(new IndexRequest("deals").type("mytype").id("3").setRefreshPolicy(RefreshPolicy.IMMEDIATE)
// .source("{\"amount\": 7,\"owner\": \"a\", \"my_nested_object\" : {\"name\": \"spock\"}}", XContentType.JSON)).actionGet();
//tc.index(new IndexRequest("deals").type("mytype").id("4").setRefreshPolicy(RefreshPolicy.IMMEDIATE)
// .source("{\"amount\": 8, \"my_nested_object\" : {\"name\": \"spock\"}}", XContentType.JSON)).actionGet();
//tc.index(new IndexRequest("deals").type("mytype").id("5").setRefreshPolicy(RefreshPolicy.IMMEDIATE)
// .source("{\"amount\": 1400,\"owner\": \"a\", \"my_nested_object\" : {\"name\": \"spock\"}}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("deals").type("mytype").id("1").setRefreshPolicy(RefreshPolicy.IMMEDIATE)
.source("{\"amount\": 1500,\"owner\": \"b\", \"my_nested_object\" : {\"name\": \"spock\"}}", XContentType.JSON)).actionGet();
}
public ResizeRequest(StreamInput in) throws IOException {
super(in);
targetIndexRequest = new CreateIndexRequest(in);
sourceIndex = in.readString();
type = in.readEnum(ResizeType.class);
copySettings = in.readOptionalBoolean();
}
/**
* Create anomaly detector index without checking exist or not.
*
* @param actionListener action called after create index
* @throws IOException IOException from {@link AnomalyDetectionIndices#getAnomalyDetectorMappings}
*/
public void initAnomalyResultIndexDirectly(ActionListener<CreateIndexResponse> actionListener) throws IOException {
String mapping = getAnomalyResultMappings();
CreateIndexRequest request = new CreateIndexRequest(AD_RESULT_HISTORY_INDEX_PATTERN)
.mapping(MAPPING_TYPE, mapping, XContentType.JSON)
.alias(new Alias(AD_RESULT_HISTORY_WRITE_INDEX_ALIAS));
adminClient.indices().create(request, actionListener);
}
/**
* Create anomaly detector job index.
*
* @param actionListener action called after create index
* @throws IOException IOException from {@link AnomalyDetectionIndices#getAnomalyDetectorJobMappings}
*/
public void initAnomalyDetectorJobIndex(ActionListener<CreateIndexResponse> actionListener) throws IOException {
// TODO: specify replica setting
CreateIndexRequest request = new CreateIndexRequest(AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX)
.mapping(AnomalyDetector.TYPE, getAnomalyDetectorJobMappings(), XContentType.JSON);
adminClient.indices().create(request, actionListener);
}
private void assertRolloverRequest(RolloverRequest request) {
assertEquals(AnomalyResult.ANOMALY_RESULT_INDEX, request.indices()[0]);
Map<String, Condition<?>> conditions = request.getConditions();
assertEquals(1, conditions.size());
assertEquals(new MaxDocsCondition(9000000L), conditions.get(MaxDocsCondition.NAME));
CreateIndexRequest createIndexRequest = request.getCreateIndexRequest();
assertEquals(AnomalyDetectionIndices.AD_RESULT_HISTORY_INDEX_PATTERN, createIndexRequest.index());
assertTrue(createIndexRequest.mappings().get(AnomalyDetectionIndices.MAPPING_TYPE).contains("data_start_time"));
}
public void testRolledOverButNotDeleted() {
doAnswer(invocation -> {
RolloverRequest request = invocation.getArgument(0);
@SuppressWarnings("unchecked")
ActionListener<RolloverResponse> listener = (ActionListener<RolloverResponse>) invocation.getArgument(1);
assertEquals(AnomalyResult.ANOMALY_RESULT_INDEX, request.indices()[0]);
Map<String, Condition<?>> conditions = request.getConditions();
assertEquals(1, conditions.size());
assertEquals(new MaxDocsCondition(9000000L), conditions.get(MaxDocsCondition.NAME));
CreateIndexRequest createIndexRequest = request.getCreateIndexRequest();
assertEquals(AnomalyDetectionIndices.AD_RESULT_HISTORY_INDEX_PATTERN, createIndexRequest.index());
assertTrue(createIndexRequest.mappings().get(AnomalyDetectionIndices.MAPPING_TYPE).contains("data_start_time"));
listener.onResponse(new RolloverResponse(null, null, Collections.emptyMap(), request.isDryRun(), true, true, true));
return null;
}).when(indicesClient).rolloverIndex(any(), any());
Metadata.Builder metaBuilder = Metadata
.builder()
.put(indexMeta(".opendistro-anomaly-results-history-2020.06.24-000003", 1L, AnomalyResult.ANOMALY_RESULT_INDEX), true)
.put(
indexMeta(
".opendistro-anomaly-results-history-2020.06.24-000004",
Instant.now().toEpochMilli(),
AnomalyResult.ANOMALY_RESULT_INDEX
),
true
);
clusterState = ClusterState.builder(clusterName).metadata(metaBuilder.build()).build();
when(clusterService.state()).thenReturn(clusterState);
adIndices.rolloverAndDeleteHistoryIndex();
verify(clusterAdminClient, times(1)).state(any(), any());
verify(indicesClient, times(1)).rolloverIndex(any(), any());
verify(indicesClient, never()).delete(any(), any());
}
public void testRolledOverDeleted() {
doAnswer(invocation -> {
RolloverRequest request = invocation.getArgument(0);
@SuppressWarnings("unchecked")
ActionListener<RolloverResponse> listener = (ActionListener<RolloverResponse>) invocation.getArgument(1);
assertEquals(AnomalyResult.ANOMALY_RESULT_INDEX, request.indices()[0]);
Map<String, Condition<?>> conditions = request.getConditions();
assertEquals(1, conditions.size());
assertEquals(new MaxDocsCondition(9000000L), conditions.get(MaxDocsCondition.NAME));
CreateIndexRequest createIndexRequest = request.getCreateIndexRequest();
assertEquals(AnomalyDetectionIndices.AD_RESULT_HISTORY_INDEX_PATTERN, createIndexRequest.index());
assertTrue(createIndexRequest.mappings().get(AnomalyDetectionIndices.MAPPING_TYPE).contains("data_start_time"));
listener.onResponse(new RolloverResponse(null, null, Collections.emptyMap(), request.isDryRun(), true, true, true));
return null;
}).when(indicesClient).rolloverIndex(any(), any());
Metadata.Builder metaBuilder = Metadata
.builder()
.put(indexMeta(".opendistro-anomaly-results-history-2020.06.24-000002", 1L, AnomalyResult.ANOMALY_RESULT_INDEX), true)
.put(indexMeta(".opendistro-anomaly-results-history-2020.06.24-000003", 2L, AnomalyResult.ANOMALY_RESULT_INDEX), true)
.put(
indexMeta(
".opendistro-anomaly-results-history-2020.06.24-000004",
Instant.now().toEpochMilli(),
AnomalyResult.ANOMALY_RESULT_INDEX
),
true
);
clusterState = ClusterState.builder(clusterName).metadata(metaBuilder.build()).build();
when(clusterService.state()).thenReturn(clusterState);
adIndices.rolloverAndDeleteHistoryIndex();
verify(clusterAdminClient, times(1)).state(any(), any());
verify(indicesClient, times(1)).rolloverIndex(any(), any());
verify(indicesClient, times(1)).delete(any(), any());
}
private boolean createInitialIndex(CollectionMetadata collection) throws Exception {
String initialIndexName = collection.getId() + "-000001";
String writeAlias = collection.getId();
CreateIndexRequest request = new CreateIndexRequest(initialIndexName);
request.alias(new Alias(writeAlias))
.settings(Settings.builder()
.put("index.number_of_shards", configProps.getNumberOfShards())
.put("index.number_of_replicas", configProps.getNumberOfReplicas()));
client.indices().create(request, RequestOptions.DEFAULT);
log.info("Index '" + initialIndexName + "' for collection '" + collection.getId() + "' initialized");
return true;
}
@Test
public void testCreateAndDeleteIndex() throws IOException, ExecutionException, InterruptedException {
// Create an Index
doCreateIndex(new CreateIndexRequest(SECOND_INDEX));
validateSpanContentAfterIndexCreateRequest();
// Delete the index
reporter.reset();
doDeleteIndex(new DeleteIndexRequest(SECOND_INDEX));
validateSpanContentAfterIndexDeleteRequest();
}