.. include:: ../services/es.rst .. _docker-es-java: Java =========== Java 应用可以使用基于 Restful 的客户端进行访问,但是要保证客户端支持 Basic Authentication 和 Https 功能,推荐使用 `Jest `__ 客户端,线上使用的 Elasticsearch 版本是 2.1,所以 Jest 版本使用 2.0 以上即可。 如果使用 maven 构建项目需要在 pom.xml 中引入如下配置: .. code-block:: xml io.searchbox jest 2.0.0 io.searchbox jest-common 2.0.0 接下来我们就可以操作自己的 Elasticsearch。 首先,我们要初始化 *JestClient* ,初始化方式如下: .. code-block:: java SSLContext sslContext = null; try { sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier); JestClientFactory factory = new JestClientFactory(); factory.setHttpClientConfig(new HttpClientConfig.Builder("https://es.sinacloud.com/") .defaultSchemeForDiscoveredNodes("https") // required, otherwise uses http .sslSocketFactory(sslSocketFactory) // this only affects sync calls .httpsIOSessionStrategy(httpsIOSessionStrategy) .defaultCredentials("your_Elasticsearch_account", "your_Elasticsearch_password")// this only affects async calls .build() ); JestClient client = factory.getObject(); 初始化好之后,就可以通过 *JestClient* 进行操作了。 .. code-block:: java // 插入操作 Map source = new LinkedHashMap(); source.put("key", "value"); Index index = new Index.Builder(source).index("索引名").type("类型名").id("id").build(); try { JestResult result = client.execute(get); System.out.println(result.getJsonString()); } catch (IOException e) { e.printStackTrace(); } // Get 操作 Get get = new Get.Builder("索引名", "").type(null).build(); try { JestResult result = client.execute(get); System.out.println(result.getJsonString()); } catch (IOException e) { e.printStackTrace(); } 更多关于 Jest 的操作参考这里 `Jest `__ 。