當前位置: 首頁>>代碼示例>>Java>>正文


Java TransportClient類代碼示例

本文整理匯總了Java中org.elasticsearch.client.transport.TransportClient的典型用法代碼示例。如果您正苦於以下問題:Java TransportClient類的具體用法?Java TransportClient怎麽用?Java TransportClient使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


TransportClient類屬於org.elasticsearch.client.transport包,在下文中一共展示了TransportClient類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: indexJSONTableDocuments

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
private void indexJSONTableDocuments(TransportClient client, String indexName, String typeName, String tablePath, String... fields) {

        loginTestUser(TEST_USER_NAME, TEST_USER_GROUP);

        // Create an OJAI connection to MapR cluster
        Connection connection = DriverManager.getConnection(CONNECTION_URL);

        // Get an instance of OJAI DocumentStore
        final DocumentStore store = connection.getStore(tablePath);

        DocumentStream documentStream = store.find(fields);
        for (Document document : documentStream) {

            IndexResponse response = client.prepareIndex(indexName, typeName, document.getId().getString())
                    .setSource(document.asJsonString(), XContentType.JSON)
                    .get();

            log.info("Elasticsearch Index Response: '{}'", response);
        }

        // Close this instance of OJAI DocumentStore
        store.close();

        // Close the OJAI connection and release any resources held by the connection
        connection.close();
    }
 
開發者ID:mapr-demos,項目名稱:mapr-music,代碼行數:27,代碼來源:MaprMusicElasticSearchService.java

示例2: getElasticClient

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
private TransportClient getElasticClient() {
        try {
            // un-command this, if you have multiple node
//            TransportClient client1 = new PreBuiltTransportClient(Settings.EMPTY)
//                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300))
//                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300));

            Settings setting = Settings.builder()
                    .put("cluster.name", elasticPro.getProperty("cluster"))
                    .put("client.transport.sniff", Boolean.valueOf(elasticPro.getProperty("transport.sniff"))).build();

            client = new PreBuiltTransportClient(setting)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(elasticPro.getProperty("host")), Integer.valueOf(elasticPro.getProperty("port"))));
        } catch (UnknownHostException ex) {
            log.error("Exception occurred while getting Client : " + ex, ex);
        }
        return client;
    }
 
開發者ID:sundarcse1216,項目名稱:es-crud,代碼行數:19,代碼來源:ElasticSearchClient.java

示例3: createClient

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
private TransportClient createClient() {
    Config cfg = getTypeCfg();
    Settings settings = Settings.builder().put("cluster.name", cfg.getString("elastic.cluster-name")).build();
    TransportClient client = new PreBuiltTransportClient(settings);

    List<String> servers = cfg.getStringList("elastic.servers");
    logger.debug(marker, "Elastic Servers: {}", servers);
    for (String addr : servers) {
        try {
            String[] a = addr.split(":");
            String host = a[0];
            int port = Integer.parseInt(a[1]);
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
        } catch (Exception e) {
            logger.error(marker, "Transport client creation failed for '{}'", addr, e);
        }
    }

    return client;
}
 
開發者ID:Lambda-3,項目名稱:Stargraph,代碼行數:21,代碼來源:ElasticClient.java

示例4: getClient

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
public static TransportClient getClient() {
    try {
        if (tclient == null) {
            String EsHosts = "192.168.1.41:9300,192.168.1.42:9300,192.168.1.43:9300";
            Settings settings = Settings.settingsBuilder()
                    .put("cluster.name", "dkes")//設置集群名稱
                    .put("tclient.transport.sniff", true).build();//自動嗅探整個集群的狀態,把集群中其它機器的ip地址加到客戶端中

            tclient = TransportClient.builder().settings(settings).build();
            String[] nodes = EsHosts.split(",");
            for (String node : nodes) {
                if (node.length() > 0) {//跳過為空的node(當開頭、結尾有逗號或多個連續逗號時會出現空node)
                    String[] hostPort = node.split(":");
                    tclient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostPort[0]), Integer.parseInt(hostPort[1])));

                }
            }
        }//if
    } catch (Exception e) {
        e.printStackTrace();
    }
    return tclient;
}
 
開發者ID:hs-web,項目名稱:hsweb-learning,代碼行數:24,代碼來源:EsClient.java

示例5: batchDelete

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
/**
 * 批量刪除
 *
 * @param transportClient
 */
private static void batchDelete(TransportClient transportClient) throws IOException {
	BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();

	DeleteRequestBuilder deleteRequestBuilder1 = transportClient.prepareDelete("product_index", "product", "1");
	DeleteRequestBuilder deleteRequestBuilder2 = transportClient.prepareDelete("product_index", "product", "2");
	DeleteRequestBuilder deleteRequestBuilder3 = transportClient.prepareDelete("product_index", "product", "3");

	bulkRequestBuilder.add(deleteRequestBuilder1);
	bulkRequestBuilder.add(deleteRequestBuilder2);
	bulkRequestBuilder.add(deleteRequestBuilder3);

	BulkResponse bulkResponse = bulkRequestBuilder.get();
	for (BulkItemResponse bulkItemResponse : bulkResponse.getItems()) {
		logger.info("--------------------------------version= " + bulkItemResponse.getVersion());
	}

}
 
開發者ID:judasn,項目名稱:Elasticsearch-Tutorial-zh-CN,代碼行數:23,代碼來源:BaseDemo.java

示例6: setUpClass

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
@BeforeClass
public static void setUpClass() throws Exception {
  faker = new Faker();
  String ip = esContainer.getContainerIpAddress();
  Integer transportPort = esContainer.getMappedPort(9300);
  MapConfiguration memoryParams = new MapConfiguration(new HashMap<>());
  memoryParams.setProperty(CONFIG_ES_CLUSTER_HOST, ip);
  memoryParams.setProperty(CONFIG_ES_CLUSTER_PORT, transportPort);
  memoryParams.setProperty(CONFIG_ES_CLUSTER_NAME, "elasticsearch");
  injector = Guice.createInjector(
      Modules.override(new ElasticSearchModule())
          .with(binder -> {
            binder.bind(Configuration.class).toProvider(() -> memoryParams);
          })
  );
  productDao = injector.getInstance(ProductDao.class);
  esClient = injector.getInstance(TransportClient.class);
}
 
開發者ID:email2liyang,項目名稱:grpc-mate,代碼行數:19,代碼來源:ProductDaoTest.java

示例7: wildcardQuery

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
/**
 * wildcard查詢/or條件/and條件
 */
public static void wildcardQuery() {
    try {
        Settings settings = Settings.settingsBuilder().put("cluster.name", "elasticsearch1").build();
        TransportClient transportClient = TransportClient.builder().
                settings(settings).build().addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("172.16.2.94"), 9300));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch("sqd.es_start");

        // {"query": {"bool": {"must": [{"or": [{"wildcard": {"content": "*oracle*"}},{"wildcard": {"content": "*mysql*"}}]}],"must_not": [],"should": []}},"from": 0, "size": 10, "sort": [],"aggs": {}}
        SearchResponse searchResponse = searchRequestBuilder.
                setQuery(QueryBuilders.boolQuery()
                .must(QueryBuilders.orQuery(QueryBuilders.wildcardQuery("content","*mysql*"),
                        QueryBuilders.wildcardQuery("content","*oracle*")))
                .must(QueryBuilders.termQuery("tbool","false")))
                .setFrom(0).setSize(100).setExplain(true).execute().actionGet();
        SearchHits searchHits = searchResponse.getHits();
        System.out.println();
        System.out.println("Total Hits is " + searchHits.totalHits());
        System.out.println();
        for (int i = 0; i < searchHits.getHits().length; ++i) {
            System.out.println("content is "
                    + searchHits.getHits()[i].getSource().get("content"));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
開發者ID:Transwarp-DE,項目名稱:Transwarp-Sample-Code,代碼行數:31,代碼來源:SearchES.java

示例8: multisearch

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
/**
 * 多字段查詢
 */
public static void multisearch() {
    try {
        Settings settings = Settings.settingsBuilder().put("cluster.name", "elasticsearch1").build();
        TransportClient transportClient = TransportClient.builder().
                settings(settings).build().addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("172.16.2.93"), 9300));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch("service2","clients");
        SearchResponse searchResponse = searchRequestBuilder.
                setQuery(QueryBuilders.boolQuery()
                        .should(QueryBuilders.termQuery("id","5"))
                        .should(QueryBuilders.prefixQuery("content","oracle")))
                .setFrom(0).setSize(100).setExplain(true).execute().actionGet();
        SearchHits searchHits = searchResponse.getHits();
        System.out.println();
        System.out.println("Total Hits is " + searchHits.totalHits());
        System.out.println();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
開發者ID:Transwarp-DE,項目名稱:Transwarp-Sample-Code,代碼行數:24,代碼來源:SearchES.java

示例9: queryByMultiGet

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
/**
 * 獲取多個對象(根據ID)
 *
 * @param transportClient
 * @throws IOException
 */
private static void queryByMultiGet(TransportClient transportClient) throws IOException {

	MultiGetResponse multiGetItemResponses = transportClient.prepareMultiGet()
			.add("product_index", "product", "1")
			.add("product_index", "product", "2")
			.add("product_index", "product", "3")
			.add("product_index", "product", "4")
			.add("product_index", "product", "5")
			.get();

	String resultJSON = null;
	for (MultiGetItemResponse multiGetItemResponse : multiGetItemResponses) {
		GetResponse getResponse = multiGetItemResponse.getResponse();
		if (getResponse.isExists()) {
			resultJSON = getResponse.getSourceAsString();
		}
	}
	logger.info("--------------------------------:" + resultJSON);
}
 
開發者ID:judasn,項目名稱:Elasticsearch-Tutorial-zh-CN,代碼行數:26,代碼來源:BaseDemo.java

示例10: queryByScroll

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
/**
 * Scroll 獲取多個對象
 *
 * @param transportClient
 * @throws IOException
 */
private static void queryByScroll(TransportClient transportClient) throws IOException {

	//setSize 是設置每批查詢多少條數據
	SearchResponse searchResponse = transportClient.prepareSearch("product_index").setTypes("product")
			.setQuery(QueryBuilders.termQuery("product_name", "飛利浦"))
			.setScroll(new TimeValue(60000))
			.setSize(3)
			.get();

	int count = 0;

	do {
		for (SearchHit searchHit : searchResponse.getHits().getHits()) {
			//打印查詢結果,或者做其他處理
			logger.info("count=" + ++count);
			logger.info(searchHit.getSourceAsString());
		}

		searchResponse = transportClient.prepareSearchScroll(searchResponse.getScrollId()).setScroll(new TimeValue(60000))
				.execute()
				.actionGet();
	} while (searchResponse.getHits().getHits().length != 0);
}
 
開發者ID:judasn,項目名稱:Elasticsearch-Tutorial-zh-CN,代碼行數:30,代碼來源:BaseDemo.java

示例11: buildBulkProcessor

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
public BulkProcessor buildBulkProcessor(Context context, TransportClient client) {
    bulkActions = context.getInteger(ES_BULK_ACTIONS,
            DEFAULT_ES_BULK_ACTIONS);
    bulkProcessorName = context.getString(ES_BULK_PROCESSOR_NAME,
            DEFAULT_ES_BULK_PROCESSOR_NAME);
    bulkSize = Util.getByteSizeValue(context.getInteger(ES_BULK_SIZE),
            context.getString(ES_BULK_SIZE_UNIT));
    concurrentRequest = context.getInteger(ES_CONCURRENT_REQUEST,
            DEFAULT_ES_CONCURRENT_REQUEST);
    flushIntervalTime = Util.getTimeValue(context.getString(ES_FLUSH_INTERVAL_TIME),
            DEFAULT_ES_FLUSH_INTERVAL_TIME);
    backoffPolicyTimeInterval = context.getString(ES_BACKOFF_POLICY_TIME_INTERVAL,
            DEFAULT_ES_BACKOFF_POLICY_START_DELAY);
    backoffPolicyRetries = context.getInteger(ES_BACKOFF_POLICY_RETRIES,
            DEFAULT_ES_BACKOFF_POLICY_RETRIES);
    return build(client);
}
 
開發者ID:cognitree,項目名稱:flume-elasticsearch-sink,代碼行數:18,代碼來源:BulkProcessorBuilder.java

示例12: configure

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
@Override
public void configure(Context context) {
    String[] hosts = getHosts(context);
    if(ArrayUtils.isNotEmpty(hosts)) {
        TransportClient client = new ElasticsearchClientBuilder(
                context.getString(PREFIX + ES_CLUSTER_NAME, DEFAULT_ES_CLUSTER_NAME), hosts)
                .setTransportSniff(context.getBoolean(
                        PREFIX + ES_TRANSPORT_SNIFF, false))
                .setIgnoreClusterName(context.getBoolean(
                        PREFIX + ES_IGNORE_CLUSTER_NAME, false))
                .setTransportPingTimeout(Util.getTimeValue(context.getString(
                        PREFIX + ES_TRANSPORT_PING_TIMEOUT), DEFAULT_ES_TIME))
                .setNodeSamplerInterval(Util.getTimeValue(context.getString(
                        PREFIX + ES_TRANSPORT_NODE_SAMPLER_INTERVAL), DEFAULT_ES_TIME))
                .build();
        buildIndexBuilder(context);
        buildSerializer(context);
        bulkProcessor = new BulkProcessorBuilder().buildBulkProcessor(context, client);
    } else {
        logger.error("Could not create transport client, No host exist");
    }
}
 
開發者ID:cognitree,項目名稱:flume-elasticsearch-sink,代碼行數:23,代碼來源:ElasticSearchSink.java

示例13: getClient

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
public TransportClient getClient()   {
    if (esClient == null) {
        synchronized (this) {
            if (esClient == null) {
                try {
                    //判斷配置
                    Preconditions.checkNotNull(clusterName, "es 服務clusterName未配置");
                    Preconditions.checkNotNull(addresses, "es 服務ip未配置");
                    //Preconditions.checkArgument(esPort > 0, "es 服務服務port未配置");
                    //設置集群的名字
                    Settings settings = Settings.settingsBuilder().put("client.node", true).put("cluster.name", clusterName).put("client.transport.sniff", sniff).build();
                    //Settings settings = Settings.settingsBuilder().put("client.transport.sniff", sniff).build();
                    //創建集群client並添加集群節點地址
                    esClient = TransportClient.builder().settings(settings).build();
                    for (String address : addresses) {
                        String[] inetAddress = address.split(":");
                        esClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(inetAddress[0]), new Integer(inetAddress[1])));
                    }
                  }catch (Exception e){
                     LOGGER.error("客戶端連接初始化異常",e);
                }
            }
        }
    }
    return esClient;
}
 
開發者ID:AsuraTeam,項目名稱:asura,代碼行數:27,代碼來源:EshClientFactory.java

示例14: failureHandlerExecutesFailoverForEachBatchItemSeparately

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
@Test
public void failureHandlerExecutesFailoverForEachBatchItemSeparately() {

    // given
    Builder builder = createTestObjectFactoryBuilder();
    ClientObjectFactory<TransportClient, BulkRequest> config = builder.build();

    FailoverPolicy failoverPolicy = spy(new NoopFailoverPolicy());

    String payload1 = "test1";
    String payload2 = "test2";
    BulkRequest bulk = new BulkRequest()
            .add(spy(new IndexRequest().source(payload1, XContentType.CBOR)))
            .add(spy(new IndexRequest().source(payload2, XContentType.CBOR)));

    // when
    config.createFailureHandler(failoverPolicy).apply(bulk);

    // then
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(failoverPolicy, times(2)).deliver((String) captor.capture());

    assertTrue(captor.getAllValues().contains(payload1));
    assertTrue(captor.getAllValues().contains(payload2));
}
 
開發者ID:rfoltyns,項目名稱:log4j2-elasticsearch,代碼行數:26,代碼來源:BulkProcessorObjectFactoryTest.java

示例15: failureHandlerExecutesFailoverForEachBatchItemSeparately

import org.elasticsearch.client.transport.TransportClient; //導入依賴的package包/類
@Test
public void failureHandlerExecutesFailoverForEachBatchItemSeparately() {

    // given
    Builder builder = createTestObjectFactoryBuilder();
    ClientObjectFactory<TransportClient, BulkRequest> config = builder.build();

    FailoverPolicy failoverPolicy = spy(new NoopFailoverPolicy());

    String payload1 = "test1";
    String payload2 = "test2";
    BulkRequest bulk = new BulkRequest()
            .add(spy(new IndexRequest().source(payload1)))
            .add(spy(new IndexRequest().source(payload2)));

    // when
    config.createFailureHandler(failoverPolicy).apply(bulk);

    // then
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(failoverPolicy, times(2)).deliver((String) captor.capture());

    assertTrue(captor.getAllValues().contains(payload1));
    assertTrue(captor.getAllValues().contains(payload2));
}
 
開發者ID:rfoltyns,項目名稱:log4j2-elasticsearch,代碼行數:26,代碼來源:BulkProcessorObjectFactoryTest.java


注:本文中的org.elasticsearch.client.transport.TransportClient類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。