Java代码用于操作ElasticSearch的RestAPI
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
public class ElasticSearchClient {
private static final int ELASTIC_SEARCH_PORT = 9200;
private static final String ELASTIC_SEARCH_SCHEME = "http";
private static final String ELASTIC_SEARCH_HOST = "localhost";
public static RestHighLevelClient createClient() {
final RestClientBuilder builder = RestClient.builder(new HttpHost(ELASTIC_SEARCH_HOST, ELASTIC_SEARCH_PORT, ELASTIC_SEARCH_SCHEME));
return new RestHighLevelClient(builder);
}
public static void closeClient(RestHighLevelClient client) {
if (client != null) {
try {
client.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
// 创建Elasticsearch客户端
RestHighLevelClient client = createClient();
// 执行操作,例如索引创建、搜索、更新等
// ...
// 关闭客户端
closeClient(client);
}
}
这段代码展示了如何在Java中创建和关闭一个Elasticsearch的RestHighLevelClient实例,用于与Elasticsearch集群进行交互。在main
方法中,可以添加具体的Elasticsearch操作逻辑。
评论已关闭