Java Code Examples for org.elasticsearch.client.transport.TransportClient#close()
The following examples show how to use
org.elasticsearch.client.transport.TransportClient#close() .
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: ElasticsearchGis.java From Elasticsearch-Tutorial-zh-CN with GNU General Public License v3.0 | 7 votes |
@SuppressWarnings({"unchecked", "resource"}) public static void main(String[] args) throws Exception { // 先构建client,两个参数分别是:cluster.name 固定参数代表后面参数的含义,集群名称 // client.transport.sniff 表示设置自动探查集群的集群节点 Settings settings = Settings.builder() .put("cluster.name", "youmeek-cluster") .put("client.transport.sniff", true) .build(); //单个节点的写法 TransportClient transportClient = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.1.127"), 9300)); //batchCreate(transportClient); query(transportClient); transportClient.close(); }
Example 2
Source File: ClientFactory.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
private Client tryCreateClient(RetryContext retryContext) throws InterruptedException { if (Thread.interrupted()) { throw new InterruptedException(); } TransportClient result = preBuiltTransportClientFactory .build(clusterName, null) .addTransportAddresses(createInetTransportAddresses()); if (result.connectedNodes().isEmpty()) { result.close(); LOG.error( "Failed to connect to Elasticsearch cluster '{}' on {}. Retry count = {}", clusterName, inetAddresses, retryContext.getRetryCount()); throw new MolgenisDataException( String.format( "Failed to connect to Elasticsearch cluster '%s' on %s. Is Elasticsearch running?", clusterName, inetAddresses)); } return result; }
Example 3
Source File: EsUpdateSettingsTest.java From io with Apache License 2.0 | 6 votes |
/** * Indexの設定が更新できること. */ @Test public void Indexの設定が更新できること() { Map<String, String> settings = new HashMap<String, String>(); settings.put("index.number_of_replicas", "1"); TransportClient client = null; try { client = createTransportClient(); assertEquals("0", getNumberOfReplicas(client, "index.number_of_replicas")); index.updateSettings(index.getName(), settings); assertEquals("1", getNumberOfReplicas(client, "index.number_of_replicas")); } finally { client.close(); } }
Example 4
Source File: EsUpdateSettingsTest.java From io with Apache License 2.0 | 6 votes |
/** * Indexの設定が更新できること. */ @Test public void Indexの設定が更新できること() { Map<String, String> settings = new HashMap<String, String>(); settings.put("index.number_of_replicas", "1"); TransportClient client = null; try { client = createTransportClient(); assertEquals("0", getNumberOfReplicas(client, "index.number_of_replicas")); index.updateSettings(index.getName(), settings); assertEquals("1", getNumberOfReplicas(client, "index.number_of_replicas")); } finally { client.close(); } }
Example 5
Source File: ElasticsearchWrapper.java From glowroot with Apache License 2.0 | 5 votes |
private static void waitForElasticsearch() throws Exception { TransportClient client = Util.client(new InetSocketAddress("127.0.0.1", 9300)); while (client.connectedNodes().isEmpty()) { SECONDS.sleep(1); } client.close(); }
Example 6
Source File: EsUpdateSettingsTest.java From io with Apache License 2.0 | 5 votes |
/** * 無効な値を指定した場合にEsClientExceptionがスローされること. */ @Test(expected = EsClientException.class) public void 無効な値を指定した場合にEsClientExceptionがスローされること() { Map<String, String> settings = new HashMap<String, String>(); settings.put("index.number_of_replicas", "invalid_value"); TransportClient client = null; try { client = createTransportClient(); index.updateSettings(index.getName(), settings); } finally { client.close(); } }
Example 7
Source File: EsUpdateSettingsTest.java From io with Apache License 2.0 | 5 votes |
/** * 存在しないkeyを指定した場合EsClientExceptionがスローされること. */ @Test(expected = EsClientException.class) public void 存在しないkeyを指定した場合EsClientExceptionがスローされること() { Map<String, String> settings = new HashMap<String, String>(); settings.put("invalid_key", "0"); TransportClient client = null; try { client = createTransportClient(); index.updateSettings(index.getName(), settings); } finally { client.close(); } }
Example 8
Source File: BaseDemo.java From Elasticsearch-Tutorial-zh-CN with GNU General Public License v3.0 | 5 votes |
@SuppressWarnings({"unchecked", "resource"}) public static void main(String[] args) throws IOException { // 先构建client,两个参数分别是:cluster.name 固定参数代表后面参数的含义,集群名称 // client.transport.sniff 表示设置自动探查集群的集群节点 Settings settings = Settings.builder() .put("cluster.name", "youmeek-cluster") .put("client.transport.sniff", true) .build(); //单个节点的写法 TransportClient transportClient = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.1.127"), 9300)); //====================================================== create(transportClient); batchCreate(transportClient); batchUpdate(transportClient); batchDelete(transportClient); update(transportClient); query(transportClient); queryByMatchOneParam(transportClient); queryByMatchMoreParam(transportClient); queryByTerm(transportClient); queryByPrefix(transportClient); queryByBool(transportClient); queryMore(transportClient); queryByMultiGet(transportClient); queryByScroll(transportClient); queryByTemplate(transportClient); delete(transportClient); aggregate(transportClient); //====================================================== transportClient.close(); }
Example 9
Source File: EsUpdateSettingsTest.java From io with Apache License 2.0 | 5 votes |
/** * 無効な値を指定した場合にEsClientExceptionがスローされること. */ @Test(expected = EsClientException.class) public void 無効な値を指定した場合にEsClientExceptionがスローされること() { Map<String, String> settings = new HashMap<String, String>(); settings.put("index.number_of_replicas", "invalid_value"); TransportClient client = null; try { client = createTransportClient(); index.updateSettings(index.getName(), settings); } finally { client.close(); } }
Example 10
Source File: EsUpdateSettingsTest.java From io with Apache License 2.0 | 5 votes |
/** * 存在しないkeyを指定した場合EsClientExceptionがスローされること. */ @Test(expected = EsClientException.class) public void 存在しないkeyを指定した場合EsClientExceptionがスローされること() { Map<String, String> settings = new HashMap<String, String>(); settings.put("invalid_key", "0"); TransportClient client = null; try { client = createTransportClient(); index.updateSettings(index.getName(), settings); } finally { client.close(); } }
Example 11
Source File: DoTestTransportHookProxy.java From uavstack with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { ConsoleLogger cl = new ConsoleLogger("test"); cl.setDebugable(true); UAVServer.instance().setLog(cl); UAVServer.instance().putServerInfo(CaptureConstants.INFO_APPSERVER_VENDOR, ServerVendor.TOMCAT); MOFAgent.mofContext.put("org.uavstack.mof.ext.clsloader", Thread.currentThread().getContextClassLoader()); TransportHookProxy p = new TransportHookProxy("test", Collections.emptyMap()); p.doProxyInstall(null, "testApp"); String[] esAddrs = {"127.0.0.1:9300"}; String clusterName = ""; String index = "esindex"; String type = "String"; String alias = "alias"; Boolean result; Settings settings = Settings.EMPTY; if (!StringHelper.isEmpty(clusterName)) { settings = Settings.builder().put("cluster.name", clusterName).build(); } TransportClient client = new PreBuiltTransportClient(settings); for (String esAddr : esAddrs) { String[] ipport = esAddr.split(":"); client.addTransportAddress(new InetSocketTransportAddress( new InetSocketAddress(ipport[0], DataConvertHelper.toInt(ipport[1], 9300)))); } result = client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet().isExists(); if(result) { result = client.admin().indices().delete(new DeleteIndexRequest(index)).actionGet().isAcknowledged(); } client.admin().indices().create(new CreateIndexRequest(index)).actionGet().isAcknowledged(); client.admin().indices().typesExists(new TypesExistsRequest(new String[] { index }, type)).actionGet().isExists(); client.admin().indices().prepareAliases().addAlias(index, alias).get().isAcknowledged(); client.admin().indices().prepareAliases().removeAlias(index, alias).get().isAcknowledged(); client.prepareSearch(index).setSearchType(SearchType.DFS_QUERY_THEN_FETCH).get(TimeValue.timeValueMillis(15000)); Map<String, Object> m = new HashMap<String, Object>(); m.put("user", "kimchy"); m.put("postDate", new Date()); m.put("message", "trying out Elasticsearch"); BulkRequestBuilder bulkRequest = client.prepareBulk(); bulkRequest.add(client.prepareIndex("twitter", "tweet", "1").setSource(m)); BulkResponse bulkResponse = bulkRequest.get(); if (bulkResponse.hasFailures()) { System.out.println("Failed"); } client.close(); }
Example 12
Source File: ItemESMessageListener.java From BigDataPlatform with GNU General Public License v3.0 | 4 votes |
@Override public void onMessage(Message message) { try { //从消息中取商品id TextMessage textMessage = (TextMessage) message; log.info("得到消息:"+textMessage.getText()); String[] text = textMessage.getText().split(","); Long itemId = new Long(text[1]); //等待事务提交 Thread.sleep(1000); //更新索引 Settings settings = Settings.builder() .put("cluster.name", ES_CLUSTER_NAME).build(); TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new TransportAddress(InetAddress.getByName(ES_CONNECT_IP), 9300)); if("add".equals(text[0])){ //根据商品id查询商品信息 SearchItem searchItem = itemMapper.getItemById(itemId); String image=searchItem.getProductImageBig(); if (image != null && !"".equals(image)) { String[] strings = image.split(","); image=strings[0]; }else{ image=""; } searchItem.setProductImageBig(image); IndexResponse indexResponse = client.prepareIndex(ITEM_INDEX, ITEM_TYPE, String.valueOf(searchItem.getProductId())) .setSource(jsonBuilder() .startObject() .field("productId", searchItem.getProductId()) .field("salePrice", searchItem.getSalePrice()) .field("productName", searchItem.getProductName()) .field("subTitle", searchItem.getSubTitle()) .field("productImageBig", searchItem.getProductImageBig()) .field("categoryName", searchItem.getCategoryName()) .field("cid", searchItem.getCid()) .endObject() ).get(); }else if("delete".equals(text[0])){ DeleteResponse deleteResponse = client.prepareDelete(ITEM_INDEX, ITEM_TYPE, String.valueOf(itemId)).get(); } log.info("处理消息成功"); client.close(); } catch (Exception e) { e.printStackTrace(); } }
Example 13
Source File: DoTestESClient.java From uavstack with Apache License 2.0 | 4 votes |
public static void main(String[] args) { TransportClient client = new PreBuiltTransportClient(Settings.EMPTY); client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("127.0.0.1", 9300))); IndexRequestBuilder irb = client.prepareIndex("uav_test_db", "uav_test_table"); Map<String, Object> item = new HashMap<String, Object>(); item.put("name", "zz"); item.put("age", 1); irb.setSource(item); IndexResponse ir = irb.get(); System.out.println(ir.status()); client.close(); }
Example 14
Source File: DkesService.java From dk-fitting with Apache License 2.0 | 4 votes |
public JSONObject getIndexAndTypeName(String es_url, String esCluster_name) { JSONObject result = new JSONObject(); ArrayList<JSONObject> indices = new ArrayList<>(); if (es_url.contains(":") && StringUtils.split(es_url, ":").length == 2) { String[] esU = StringUtils.split(es_url, ":"); String esIp = esU[0]; int esPort = Integer.valueOf(esU[1]); Settings settings = Settings.builder().put("cluster.name", esCluster_name) .put("client.transport.sniff", true) // 开启嗅探,自动搜寻新加入集群IP .build(); TransportClient transportClient = null; try { transportClient = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esIp), esPort)); ActionFuture<GetMappingsResponse> mappings = transportClient.admin().indices().getMappings(new GetMappingsRequest()); Iterator<ObjectObjectCursor<String, ImmutableOpenMap<String, MappingMetaData>>> iterator = mappings.actionGet().getMappings().iterator(); while (iterator.hasNext()) { ObjectObjectCursor<String, ImmutableOpenMap<String, MappingMetaData>> next = iterator.next(); String key = next.key; ImmutableOpenMap<String, MappingMetaData> value = next.value; Iterator<String> stringIterator = value.keysIt(); while (stringIterator.hasNext()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("index_name", key); jsonObject.put("index_type", stringIterator.next()); indices.add(jsonObject); } } result.put("succeed", true); result.put("indices", indices); } catch (UnknownHostException e) { e.printStackTrace(); } finally { if (transportClient != null) { transportClient.close(); } } }else { result.put("succeed", false); result.put("msg", "连接es的地址输入格式有误!"); return result; } /*if (es_url.contains(":") && StringUtils.split(es_url, ":").length == 2) { String[] esU = StringUtils.split(es_url, ":"); String esIp = esU[0]; ArrayList<JSONObject> indices = new ArrayList<>(); JSONObject body = restTemplate.getForEntity("http://" + esIp + ":" + esHttpPort + "/_mappings", JSONObject.class).getBody(); if (!body.isEmpty()) { for (String indexName : body.keySet()) { JSONObject o = body.getJSONObject(indexName); JSONObject mappings = o.getJSONObject("mappings"); for (String esType : mappings.keySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("index_name", indexName); jsonObject.put("index_type", esType); indices.add(jsonObject); } } result.put("succeed", true); result.put("indices", indices); } else { result.put("succeed", false); result.put("errmsg", "未发现集群中的index!"); } } else { result.put("succeed", false); result.put("msg", "连接es的地址输入格式有误!"); return result; }*/ return result; }
Example 15
Source File: EsClientPoolFactory.java From dk-fitting with Apache License 2.0 | 4 votes |
@Override //销毁对象 public void destroyObject(PooledObject<TransportClient> pooledObject) throws Exception { TransportClient client = pooledObject.getObject(); client.close(); }
Example 16
Source File: EsClientPoolFactory.java From dk-fitting with Apache License 2.0 | 4 votes |
public void destroyObject(PooledObject<TransportClient> pooledObject) throws Exception { TransportClient client = pooledObject.getObject(); client.close(); }
Example 17
Source File: SearchItemServiceImpl.java From BigDataPlatform with GNU General Public License v3.0 | 4 votes |
@Override public int importAllItems() { try{ Settings settings = Settings.builder() .put("cluster.name", ES_CLUSTER_NAME).build(); TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new TransportAddress(InetAddress.getByName(ES_CONNECT_IP), 9300)); //批量添加 BulkRequestBuilder bulkRequest = client.prepareBulk(); //查询商品列表 List<SearchItem> itemList = itemMapper.getItemList(); //遍历商品列表 for (SearchItem searchItem : itemList) { String image=searchItem.getProductImageBig(); if (image != null && !"".equals(image)) { String[] strings = image.split(","); image=strings[0]; }else{ image=""; } searchItem.setProductImageBig(image); bulkRequest.add(client.prepareIndex(ITEM_INDEX, ITEM_TYPE, String.valueOf(searchItem.getProductId())) .setSource(jsonBuilder() .startObject() .field("productId", searchItem.getProductId()) .field("salePrice", searchItem.getSalePrice()) .field("productName", searchItem.getProductName()) .field("subTitle", searchItem.getSubTitle()) .field("productImageBig", searchItem.getProductImageBig()) .field("categoryName", searchItem.getCategoryName()) .field("cid", searchItem.getCid()) .endObject() ) ); } BulkResponse bulkResponse = bulkRequest.get(); log.info("更新索引成功"); client.close(); }catch (Exception e){ e.printStackTrace(); throw new XmallException("导入ES索引库出错,请再次尝试"); } return 1; }