类org.elasticsearch.action.admin.indices.create.CreateIndexRequest源码实例Demo

下面列出了怎么用org.elasticsearch.action.admin.indices.create.CreateIndexRequest的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: usergrid   文件: SetupDao.java
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());
        }

    }
 
源代码5 项目: microservices-platform   文件: IndexServiceImpl.java
@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;
}
 
源代码10 项目: Elasticsearch   文件: UpsertByIdTask.java
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);
            }

        }
    });
}
 
源代码11 项目: Elasticsearch   文件: TransportDeleteAction.java
@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);
    }
}
 
源代码12 项目: conductor   文件: ElasticSearchDAOV5.java
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
        }
    }
}
 
源代码13 项目: conductor   文件: ElasticSearchDAOV6.java
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);
        }
    }
}
 
源代码14 项目: c2mon   文件: ElasticsearchClientRest.java
@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;
}
 
源代码15 项目: datashare   文件: ElasticsearchConfiguration.java
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;
}
 
源代码16 项目: pulsar   文件: ElasticSearchSink.java
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.");
        }
    }
}
 
源代码17 项目: streams   文件: ElasticsearchPersistWriter.java
/**
 * 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);
    }
  }
}
 
源代码18 项目: streams   文件: TwitterUserstreamElasticsearchIT.java
@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());

}
 
源代码19 项目: foxtrot   文件: TestUtils.java
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();
}
 
源代码23 项目: crate   文件: ResizeRequest.java
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);
}
 
源代码26 项目: anomaly-detection   文件: RolloverTests.java
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"));
}
 
源代码27 项目: anomaly-detection   文件: RolloverTests.java
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());
}
 
源代码28 项目: anomaly-detection   文件: RolloverTests.java
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());
}
 
源代码29 项目: staccato   文件: ElasticsearchIndexInitializer.java
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();
}
 
 类所在包
 类方法
 同包方法