创建Java连接Elasticsearch客户端连接

    从这节开始,讲解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 等后面讲到集群再详解;下一讲开始讲解如何创建索引.........如何操作文档(增删改查).....这些

    

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值