从这节开始,讲解java是如何连接ES呢?
怀揣好奇的心情......满满的期待.......查阅资料,ElasticSearch提供了主流开发语言的连接开发包 ..........长话短说,进入实操阶段
从企业级开发角度去讲,现在maven工程还是比较多的.....所以这一讲也是用maven进行讲解.
新建的maven项目 添加如下依赖即可:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
连接es的java代码:
package com.lxz.test;
import java.net.InetAddress;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
/**
* @author: xxx
* @email: xxx
* @version: 1.0.0
* @time: 2018年9月26日 下午4:04:02
*/
public class TestEsCli_1 {
private static String host="192.168.19.128"; //服务器地址
private static int port =9200; //端口
private TransportClient client =null; //es客户端
public static void main(String[] args) throws Exception{
TestEsCli_1 test = new TestEsCli_1();
test.getEsClient();
}
/**
* 实例化es客户端
*/
@SuppressWarnings({ "resource", "unchecked" })
public void getEsClient(){
try {
client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
System.out.println("client: "+ client);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(client!=null){
client.close();
}
}
}
}
因为我这边是在本地的vm中安装的Elasticsearch,执行速度有点慢哈.....建议在操作的同时,tail -f ../logs/elasticsearch.log,实时查看日志文件.对解决错误有很大的帮助......
执行的结果如下:
这里有个Setting 等后面讲到集群再详解;下一讲开始讲解如何创建索引.........如何操作文档(增删改查).....这些