org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest Java Examples

The following examples show how to use org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RestIndicesExistsAction.java    From Elasticsearch with Apache License 2.0 13 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    IndicesExistsRequest indicesExistsRequest = new IndicesExistsRequest(Strings.splitStringByCommaToArray(request.param("index")));
    indicesExistsRequest.indicesOptions(IndicesOptions.fromRequest(request, indicesExistsRequest.indicesOptions()));
    indicesExistsRequest.local(request.paramAsBoolean("local", indicesExistsRequest.local()));
    client.admin().indices().exists(indicesExistsRequest, new RestResponseListener<IndicesExistsResponse>(channel) {
        @Override
        public RestResponse buildResponse(IndicesExistsResponse response) {
            if (response.isExists()) {
                return new BytesRestResponse(OK);
            } else {
                return new BytesRestResponse(NOT_FOUND);
            }
        }

    });
}
 
Example #2
Source File: SetupDao.java    From usergrid with Apache License 2.0 7 votes vote down vote up
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);
        }
    }
}
 
Example #3
Source File: MongoElasticsearchSyncIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@Test
public void testSync() throws Exception {

  MongoElasticsearchSync sync = new MongoElasticsearchSync(testConfiguration);

  sync.run();

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getDestination().getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  assertTrue(indicesExistsResponse.isExists());

  // assert lines in file
  SearchRequestBuilder countRequest = testClient
      .prepareSearch(testConfiguration.getDestination().getIndex())
      .setTypes(testConfiguration.getDestination().getType());
  SearchResponse countResponse = countRequest.execute().actionGet();

  assertEquals((int)countResponse.getHits().getTotalHits(), 89);

}
 
Example #4
Source File: PercolateTagProcessor.java    From streams with Apache License 2.0 6 votes vote down vote up
/**
 * createIndexIfMissing.
 * @param indexName indexName
 */
public void createIndexIfMissing(String indexName) {
  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 {} did not exist. The index was automatically created from the stored ElasticSearch Templates.", 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);
    }
  }
}
 
Example #5
Source File: Search.java    From elasticsearch-rest-command with The Unlicense 6 votes vote down vote up
public static String[] parseIndices(AST_Search searchTree, Client client) throws CommandException {
	String[] indices = Strings.EMPTY_ARRAY;

	// 过滤不存在的index,不然查询会失败
	// 如果所有指定的index都不存在,那么将在所有的index查询该条件
	String[] originIndices = ((String) searchTree.getOption(Option.INDEX))
			.split(",");
	ArrayList<String> listIndices = new ArrayList<String>();

	for (String index : originIndices) {
		if (client.admin().indices()
				.exists(new IndicesExistsRequest(index)).actionGet()
				.isExists()) {
			listIndices.add(index);
		}
	}

	if (listIndices.size() > 0)
		indices = listIndices.toArray(new String[listIndices.size()]);
	else
		throw new CommandException(String.format("%s index not exsit", searchTree.getOption(Option.INDEX)));
	
	return indices;

}
 
Example #6
Source File: ElasticsearchPersistWriter.java    From streams with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
  }
}
 
Example #7
Source File: ElasticsearchTestUtils.java    From components with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes an index and block until deletion is complete.
 *
 * @param index The index to delete
 * @param client The client which points to the Elasticsearch instance
 * @throws InterruptedException if blocking thread is interrupted or index existence check failed
 * @throws java.util.concurrent.ExecutionException if index existence check failed
 * @throws IOException if deletion failed
 */
static void deleteIndex(String index, Client client)
        throws InterruptedException, java.util.concurrent.ExecutionException, IOException {
    IndicesAdminClient indices = client.admin().indices();
    IndicesExistsResponse indicesExistsResponse =
            indices.exists(new IndicesExistsRequest(index)).get();
    if (indicesExistsResponse.isExists()) {
        indices.prepareClose(index).get();
        // delete index is an asynchronous request, neither refresh or upgrade
        // delete all docs before starting tests. WaitForYellow() and delete directory are too slow,
        // so block thread until it is done (make it synchronous!!!)
        AtomicBoolean indexDeleted = new AtomicBoolean(false);
        AtomicBoolean waitForIndexDeletion = new AtomicBoolean(true);
        indices.delete(
                Requests.deleteIndexRequest(index),
                new DeleteActionListener(indexDeleted, waitForIndexDeletion));
        while (waitForIndexDeletion.get()) {
            Thread.sleep(100);
        }
        if (!indexDeleted.get()) {
            throw new IOException("Failed to delete index " + index);
        }
    }
}
 
Example #8
Source File: ElasticsearchParentChildUpdaterIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTestParentChildPersistUpdater() throws Exception {

  testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration( "ElasticsearchParentChildUpdaterIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  assertTrue(indicesExistsResponse.isExists());

  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("org.apache.streams.pojo.json"))
      .setScanners(new SubTypesScanner()));
  objectTypes = reflections.getSubTypesOf(ActivityObject.class);

  Path testdataDir = Paths.get("target/dependency/activitystreams-testdata");
  files = Files.list(testdataDir).collect(Collectors.toList());

}
 
Example #9
Source File: ElasticsearchPersistWriterIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTestPersistWriter() throws Exception {

  testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration("ElasticsearchPersistWriterIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  if(indicesExistsResponse.isExists()) {
    DeleteIndexRequest deleteIndexRequest = Requests.deleteIndexRequest(testConfiguration.getIndex());
    DeleteIndexResponse deleteIndexResponse = testClient.admin().indices().delete(deleteIndexRequest).actionGet();
    assertTrue(deleteIndexResponse.isAcknowledged());
  }

}
 
Example #10
Source File: ElasticSearchIndex.java    From titan1withtp3.1 with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #11
Source File: ElasticsearchDataStructure.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void init() {

	boolean indexExistsAlready = clientProvider.getClient()
			.admin()
			.indices()
			.exists(new IndicesExistsRequest(index))
			.actionGet()
			.isExists();

	if (!indexExistsAlready) {
		CreateIndexRequest request = new CreateIndexRequest(index);
		request.mapping(ELASTICSEARCH_TYPE, MAPPING, XContentType.JSON);
		clientProvider.getClient().admin().indices().create(request).actionGet();
	}

	refreshIndex();

}
 
Example #12
Source File: ElasticsearchNamespaceStore.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void init() {
	boolean indexExistsAlready = clientProvider.getClient()
			.admin()
			.indices()
			.exists(new IndicesExistsRequest(index))
			.actionGet()
			.isExists();

	if (!indexExistsAlready) {
		CreateIndexRequest request = new CreateIndexRequest(index);
		request.mapping(ELASTICSEARCH_TYPE, MAPPING, XContentType.JSON);
		clientProvider.getClient().admin().indices().create(request).actionGet();
	}

}
 
Example #13
Source File: TwitterUserstreamElasticsearchIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@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());

}
 
Example #14
Source File: ElasticsearchReindexIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTest() throws Exception {

  testConfiguration = new StreamsConfigurator<>(ElasticsearchReindexConfiguration.class).detectCustomConfiguration("ElasticsearchReindexIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration.getSource()).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertThat(clusterHealthResponse.getStatus(), not(ClusterHealthStatus.RED));

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getSource().getIndexes().get(0));
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  assertThat(indicesExistsResponse.isExists(), is(true));

  SearchRequestBuilder countRequest = testClient
      .prepareSearch(testConfiguration.getSource().getIndexes().get(0))
      .setTypes(testConfiguration.getSource().getTypes().get(0));
  SearchResponse countResponse = countRequest.execute().actionGet();

  count = (int)countResponse.getHits().getTotalHits();

  assertThat(count, not(0));

}
 
Example #15
Source File: ElasticsearchReindexChildIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTest() throws Exception {

  testConfiguration = new StreamsConfigurator<>(ElasticsearchReindexConfiguration.class).detectCustomConfiguration("ElasticsearchReindexChildIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration.getSource()).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getSource().getIndexes().get(0));
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  assertThat(indicesExistsResponse.isExists(), is(true));

  SearchRequestBuilder countRequest = testClient
      .prepareSearch(testConfiguration.getSource().getIndexes().get(0))
      .setTypes(testConfiguration.getSource().getTypes().get(0));
  SearchResponse countResponse = countRequest.execute().actionGet();

  count = (int)countResponse.getHits().getTotalHits();

  assertNotEquals(count, 0);

}
 
Example #16
Source File: HdfsElasticsearchIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTest() throws Exception {

  testConfiguration = new StreamsConfigurator<>(HdfsElasticsearchConfiguration.class).detectCustomConfiguration("HdfsElasticsearchIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration.getDestination()).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getDestination().getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  if(indicesExistsResponse.isExists()) {
    DeleteIndexRequest deleteIndexRequest = Requests.deleteIndexRequest(testConfiguration.getDestination().getIndex());
    DeleteIndexResponse deleteIndexResponse = testClient.admin().indices().delete(deleteIndexRequest).actionGet();
    assertTrue(deleteIndexResponse.isAcknowledged());
  };
}
 
Example #17
Source File: ElasticsearchHdfsIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTest() throws Exception {

  testConfiguration = new StreamsConfigurator<>(ElasticsearchHdfsConfiguration.class).detectCustomConfiguration("ElasticsearchHdfsIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration.getSource()).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getSource().getIndexes().get(0));
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  assertThat(indicesExistsResponse.isExists(), is(true));

  SearchRequestBuilder countRequest = testClient
      .prepareSearch(testConfiguration.getSource().getIndexes().get(0))
      .setTypes(testConfiguration.getSource().getTypes().get(0));
  SearchResponse countResponse = countRequest.execute().actionGet();

  count = (int)countResponse.getHits().getTotalHits();

  assertNotEquals(count, 0);
}
 
Example #18
Source File: TwitterHistoryElasticsearchIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTest() throws Exception {

  testConfiguration = new StreamsConfigurator<>(TwitterHistoryElasticsearchConfiguration.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());
  };
}
 
Example #19
Source File: TestUtils.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #20
Source File: ESUtil.java    From ns4_gear_watchdog with Apache License 2.0 5 votes vote down vote up
/**
 * 不存在就创建索引
 *
 */
public boolean createIndexIfNotExist(String index, String type) {
    IndicesAdminClient adminClient = client.admin().indices();
    IndicesExistsRequest request = new IndicesExistsRequest(index);
    IndicesExistsResponse response = adminClient.exists(request).actionGet();
    if (!response.isExists()) {
        return createIndex(index, type);
    }
    return true;
}
 
Example #21
Source File: MongoElasticsearchSyncIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void prepareTest() throws Exception {

  testConfiguration = new StreamsConfigurator<>(MongoElasticsearchSyncConfiguration.class).detectCustomConfiguration();
  testClient = ElasticsearchClientManager.getInstance(testConfiguration.getDestination()).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getDestination().getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  assertFalse(indicesExistsResponse.isExists());
}
 
Example #22
Source File: ElasticsearchReindexParentIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void prepareTest() throws Exception {

  testConfiguration = new StreamsConfigurator<>(ElasticsearchReindexConfiguration.class).detectCustomConfiguration("ElasticsearchReindexParentIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration.getSource()).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertThat(clusterHealthResponse.getStatus(), not(ClusterHealthStatus.RED));

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getSource().getIndexes().get(0));
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  assertTrue(indicesExistsResponse.isExists());

  SearchRequestBuilder countRequest = testClient
      .prepareSearch(testConfiguration.getSource().getIndexes().get(0))
      .setTypes(testConfiguration.getSource().getTypes().get(0));
  SearchResponse countResponse = countRequest.execute().actionGet();

  count = (int)countResponse.getHits().getTotalHits();

  PutIndexTemplateRequestBuilder putTemplateRequestBuilder = testClient.admin().indices().preparePutTemplate("mappings");
  URL templateURL = ElasticsearchParentChildWriterIT.class.getResource("/ActivityChildObjectParent.json");
  ObjectNode template = MAPPER.readValue(templateURL, ObjectNode.class);
  String templateSource = MAPPER.writeValueAsString(template);
  putTemplateRequestBuilder.setSource(templateSource);

  testClient.admin().indices().putTemplate(putTemplateRequestBuilder.request()).actionGet();

  assertThat(count, not(0));

}
 
Example #23
Source File: ElasticsearchPersistUpdaterIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void prepareTestPersistUpdater() throws Exception {

  testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration("ElasticsearchPersistUpdaterIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  assertTrue(indicesExistsResponse.isExists());

}
 
Example #24
Source File: ElasticsearchParentChildWriterIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void prepareTestParentChildPersistWriter() throws Exception {

  testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration("ElasticsearchParentChildWriterIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  if (indicesExistsResponse.isExists()) {
    DeleteIndexRequest deleteIndexRequest = Requests.deleteIndexRequest(testConfiguration.getIndex());
    DeleteIndexResponse deleteIndexResponse = testClient.admin().indices().delete(deleteIndexRequest).actionGet();
    assertTrue(deleteIndexResponse.isAcknowledged());
  }

  PutIndexTemplateRequestBuilder putTemplateRequestBuilder = testClient.admin().indices().preparePutTemplate("mappings");
  URL templateURL = ElasticsearchParentChildWriterIT.class.getResource("/ActivityChildObjectParent.json");
  ObjectNode template = MAPPER.readValue(templateURL, ObjectNode.class);
  String templateSource = MAPPER.writeValueAsString(template);
  putTemplateRequestBuilder.setSource(templateSource);

  testClient.admin().indices().putTemplate(putTemplateRequestBuilder.request()).actionGet();

  Reflections reflections = new Reflections(new ConfigurationBuilder()
    .setUrls(ClasspathHelper.forPackage("org.apache.streams.pojo.json"))
    .setScanners(new SubTypesScanner()));
  objectTypes = reflections.getSubTypesOf(ActivityObject.class);

  Path testdataDir = Paths.get("target/dependency/activitystreams-testdata");
  files = Files.list(testdataDir).collect(Collectors.toList());

  assert( files.size() > 0);
}
 
Example #25
Source File: BaseElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * creates a new index if one does not exist
 */
protected void assureIndex() {
    IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet();
    if (!response.isExists()) {
        createIndex();
    }
}
 
Example #26
Source File: BaseElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * removes any existing index and creates a new one
 */
protected void recreateIndex() {
    IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet();
    if (response.isExists()) {
        client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet();
    }

    // create index
    createIndex();
}
 
Example #27
Source File: IndicesExistsRequestBuilder.java    From elasticshell with Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder toXContent(IndicesExistsRequest request, IndicesExistsResponse response, XContentBuilder builder) throws IOException {
    builder.startObject();
    builder.field(Fields.OK, response.isExists());
    builder.endObject();
    return builder;
}
 
Example #28
Source File: BaseElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * removes any existing index and creates a new one
 */
protected void recreateIndex() {
    IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet();
    if (response.isExists()) {
        client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet();
    }

    // create index
    createIndex();
}
 
Example #29
Source File: ElasticsearchUtil.java    From SpringBootLearn with Apache License 2.0 5 votes vote down vote up
/**
 * 判断索引是否存在
 * @param index
 * @return
 */
public static boolean isIndexExist(String index) {
    IndicesExistsResponse inExistsResponse = client
            .admin()
            .indices()
            .exists(new IndicesExistsRequest(index))
            .actionGet();
    if (inExistsResponse.isExists()) {
        log.info("Index [" + index + "] is exist!");
    } else {
        log.info("Index [" + index + "] is not exist!");
    }
    return inExistsResponse.isExists();
}
 
Example #30
Source File: IndexController.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
/**
 * 判断索引是否存在
 * @param index 索引名
 * @author jitwxs
 * @since 2018/10/9 15:08
 */
@PostMapping("/index/hasExist")
public ResultBean hasExist(String index) {
    IndicesExistsRequest inExistsRequest = new IndicesExistsRequest(index);
    IndicesExistsResponse inExistsResponse = transportClient.admin().indices().exists(inExistsRequest).actionGet();

    return inExistsResponse.isExists() ? ResultBean.success("索引存在!") : ResultBean.error("索引不存在!");
}