JAVA实例:初始化
ElasticSearch提供了很多API供开发者调用,在过去的版本中,应用的比较广泛的是通过Transport端口调用相应的功能,但是新版本的ElasticSearch已经不推荐使用Transport端口,而是推荐使用REST的方式调用功能。本实例以Java REST Client为作为参考。
添加pom引用
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.1.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.1.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client-sniffer</artifactId>
<version>7.1.1</version>
</dependency>
Java High Level REST Client需要Java 1.8,并且依赖于Elasticsearch core项目。
初始化
RestHighLevelClient实例需要按如下方式构建:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
关闭客户端
RestHighLevelClient将根据提供的构建器在内部创建用于执行请求的客户端。该客户端维护一个连接池并启动一些线程,因此当您处理好请求时,您应该将其关闭以释放这些资源,改操作通过调用close()方法来完成:
client.close();