@Override public boolean createIndex(String indexName, Object settings) { CreateIndexRequest request = new CreateIndexRequest(indexName); if (settings instanceof String) { request.settings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE); } else if (settings instanceof Map) { request.settings((Map) settings); } else if (settings instanceof XContentBuilder) { request.settings((XContentBuilder) settings); } try { return client.indices().create(request).isAcknowledged(); } catch (IOException e) { throw new ElasticsearchException("Error for creating index: " + request.toString(), e); } }
public void createIndexIfNotExists(String indexName, final int shards, final int replicas) { // create an index if not existent if (!this.elasticsearchClient.admin().indices().prepareExists(indexName).execute().actionGet().isExists()) { Settings.Builder settings = Settings.builder() .put("number_of_shards", shards) .put("number_of_replicas", replicas); this.elasticsearchClient.admin().indices().prepareCreate(indexName) .setSettings(settings) .setUpdateAllTypes(true) .execute().actionGet(); } else { //LOGGER.debug("Index with name {} already exists", indexName); } }
private void addIndex(String indexName) { try { elasticSearchClient.admin() .indices() .prepareGetIndex() .addIndices(indexName) .execute() .actionGet(); } catch (IndexNotFoundException infe) { try { elasticSearchClient.admin() .indices() .prepareCreate(indexName) .execute() .actionGet(); } catch (ResourceAlreadyExistsException done) { // no-op } } }
/** * If ES already contains this instance's target index, then do nothing. * Otherwise, create the index, then wait {@link #CREATE_SLEEP}. * <p> * The {@code client} field must point to a live, connected client. * The {@code indexName} field must be non-null and point to the name * of the index to check for existence or create. * * @param config the config for this ElasticSearchIndex * @throws java.lang.IllegalArgumentException if the index could not be created */ private void checkForOrCreateIndex(Configuration config) { Preconditions.checkState(null != client); //Create index if it does not already exist IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet(); if (!response.isExists()) { ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder(); ElasticSearchSetup.applySettingsFromTitanConf(settings, config, ES_CREATE_EXTRAS_NS); CreateIndexResponse create = client.admin().indices().prepareCreate(indexName) .setSettings(settings.build()).execute().actionGet(); try { final long sleep = config.get(CREATE_SLEEP); log.debug("Sleeping {} ms after {} index creation returned from actionGet()", sleep, indexName); Thread.sleep(sleep); } catch (InterruptedException e) { throw new TitanException("Interrupted while waiting for index to settle in", e); } if (!create.isAcknowledged()) throw new IllegalArgumentException("Could not create index: " + indexName); } }
.setSettings(settings) .get(); if (!indexResponse.isAcknowledged()) { throw new IllegalStateException("Failed to create index " + index.getName());
@Override public void recreateIndex(String indexName) throws IOException { DeleteIndexRequestBuilder dirBuilder = transportClient.admin().indices().prepareDelete(indexName); try { DeleteIndexResponse diResponse = dirBuilder.execute().actionGet(); } catch (IndexNotFoundException ie) { System.out.println("Index not found... that's ok"); } CreateIndexRequestBuilder cirBuilder = transportClient.admin().indices().prepareCreate(indexName); CreateIndexResponse ciResponse = cirBuilder.execute().actionGet(); Assert.assertTrue(ciResponse.isAcknowledged(), "Create index succeeeded"); }
@Test public void testAdvancedMapping() throws Exception { setup(Settings.EMPTY, new DynamicSgConfig(), Settings.EMPTY, true, ClusterConfiguration.DEFAULT); try (TransportClient tc = getInternalTransportClient(this.clusterInfo, Settings.EMPTY)) { tc.admin().indices().create(new CreateIndexRequest("myindex1") .mapping("mytype1", FileHelper.loadFile("mapping1.json"), XContentType.JSON)).actionGet(); tc.admin().indices().create(new CreateIndexRequest("myindex2") .mapping("mytype2", FileHelper.loadFile("mapping2.json"), XContentType.JSON)).actionGet(); tc.admin().indices().create(new CreateIndexRequest("myindex3") .mapping("mytype3", FileHelper.loadFile("mapping3.json"), XContentType.JSON)).actionGet(); tc.admin().indices().create(new CreateIndexRequest("myindex4") .mapping("mytype4", FileHelper.loadFile("mapping4.json"), XContentType.JSON)).actionGet(); } RestHelper rh = nonSslRestHelper(); System.out.println("############ write into mapping 1"); String data1 = FileHelper.loadFile("data1.json"); System.out.println(rh.executePutRequest("myindex1/mytype1/1?refresh", data1, encodeBasicHeader("nagilum", "nagilum"))); System.out.println(rh.executePutRequest("myindex1/mytype1/1?refresh", data1, encodeBasicHeader("nagilum", "nagilum"))); System.out.println("############ write into mapping 2"); System.out.println(rh.executePutRequest("myindex2/mytype2/2?refresh", data1, encodeBasicHeader("nagilum", "nagilum"))); System.out.println(rh.executePutRequest("myindex2/mytype2/2?refresh", data1, encodeBasicHeader("nagilum", "nagilum"))); System.out.println("############ write into mapping 3"); String parent = FileHelper.loadFile("data2.json"); String child = FileHelper.loadFile("data3.json"); System.out.println(rh.executePutRequest("myindex3/mytype3/1?refresh", parent, encodeBasicHeader("nagilum", "nagilum"))); System.out.println(rh.executePutRequest("myindex3/mytype3/2?routing=1&refresh", child, encodeBasicHeader("nagilum", "nagilum"))); System.out.println("############ write into mapping 4"); System.out.println(rh.executePutRequest("myindex4/mytype4/1?refresh", parent, encodeBasicHeader("nagilum", "nagilum"))); System.out.println(rh.executePutRequest("myindex4/mytype4/2?routing=1&refresh", child, encodeBasicHeader("nagilum", "nagilum"))); }
@Override public boolean createIndex(String indexName) { Assert.notNull(indexName, "No index defined for Query"); try { return client.indices().create(Requests.createIndexRequest(indexName)).isAcknowledged(); } catch (Exception e) { throw new ElasticsearchException("Failed to create index " + indexName, e); } }
tc.admin().indices().create(new CreateIndexRequest("twutter")).actionGet();
@Test public void get_with_string_timeout_is_not_yet_implemented() { try { es.client().prepareCreate(generateNewIndexName()).get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); } }
.setSettings(settings) .execute() .actionGet(); timeNewIndexCreation.stop(); logger.info("Created new Index Name [{}] ACK=[{}]", indexName, cir.isAcknowledged()); } catch (IndexAlreadyExistsException e) { logger.info("Index Name [{}] already exists", indexName);
CreateIndexResponse indexResponse = SHARED_NODE.client().admin().indices() .prepareCreate(index.getName()) .setSettings(settings) .get(); if (!indexResponse.isAcknowledged()) { throw new IllegalStateException("Failed to create index " + index.getName());
@Override public CreateIndexResponse get() { Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { if (profiler.isTraceEnabled()) { profiler.stopTrace(toString()); } } }
@Test public void test557() throws Exception { final Settings settings = Settings.builder() .put(ConfigConstants.SEARCHGUARD_ROLES_MAPPING_RESOLUTION, "BOTH") .build(); setup(Settings.EMPTY, new DynamicSgConfig(), settings); try (TransportClient tc = getInternalTransportClient(this.clusterInfo, Settings.EMPTY)) { tc.admin().indices().create(new CreateIndexRequest("copysf")).actionGet(); tc.index(new IndexRequest("vulcangov").type("kolinahr").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("starfleet").type("ships").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("starfleet_academy").type("students").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); } final RestHelper rh = nonSslRestHelper(); HttpResponse res = rh.executePostRequest("/*/_search", "{\"size\":0,\"aggs\":{\"indices\":{\"terms\":{\"field\":\"_index\",\"size\":10}}}}", encodeBasicHeader("nagilum", "nagilum")); System.out.println(res.getBody()); Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); Assert.assertTrue(res.getBody().contains("starfleet_academy")); res = rh.executePostRequest("/*/_search", "{\"size\":0,\"aggs\":{\"indices\":{\"terms\":{\"field\":\"_index\",\"size\":10}}}}", encodeBasicHeader("557", "nagilum")); System.out.println(res.getBody()); Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); Assert.assertTrue(res.getBody().contains("starfleet_academy")); }
@Test public void create_index() { CreateIndexRequestBuilder requestBuilder = es.client().prepareCreate(generateNewIndexName()); requestBuilder.get(); }
private void updateLogIndexName() { this.logIndexName = this.logIndexPrefix + "_" + SIMPLE_DATE_FORMAT.format(new Date()); try { elasticSearchClient.admin() .indices() .prepareGetIndex() .addIndices(logIndexName) .execute() .actionGet(); } catch (IndexNotFoundException infe) { try { elasticSearchClient.admin() .indices() .prepareCreate(logIndexName) .execute() .actionGet(); } catch (ResourceAlreadyExistsException ilee) { // no-op } catch (Exception e) { logger.error("Failed to update log index name: {}", logIndexName, e); } } }
@Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { es.client().prepareCreate(generateNewIndexName()).get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); } }
@Test public void execute_should_throw_an_unsupported_operation_exception() { try { es.client().prepareCreate(generateNewIndexName()).execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); } }
@Test public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); CreateIndexRequestBuilder requestBuilder = es.client().prepareCreate(generateNewIndexName()); requestBuilder.get(); assertThat(logTester.logs()).hasSize(1); }