elasticsearch获取client工具类

  Elasticsearch 的Java API 提供了非常便捷的方法来索引和查询数据等。 通过添加jar包,不需要编写HTTP层的代码就可以开始着手进行连接到Elasticsearch的工作。它提供了两种方法连接到Elasticsearch:创建一个本地节点并加入集群(cluster),或者利用传输(transport)。这两种方法都是利用一个Client(org.elasticsearch.client.Client)实例来实现的。


1、先上maven依赖(注意不同版本的jar包方法不一样)

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.1.1</version>
        </dependency>
2、上代码

public class EsClient {

    static Map<String, String> m = new HashMap<String, String>();
//    // 设置client.transport.sniff为true来使客户端去嗅探整个集群的状态,把集群中其它机器的ip地址加到客户端中,
    static Settings settings =Settings.builder().put("cluster.name", "elasticsearch") //设置ES实例的名称
                                                .put("client.transport.sniff", true) //自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
                                                 .build();
 
    // 取得实例
    @SuppressWarnings("resource")
    public static synchronized TransportClient getTransportClient() {
        InetAddress addr;
        try {
                addr = InetAddress.getByName("127.0.0.1");
                InetSocketAddress ip=new InetSocketAddress(addr, 9300);
                TransportAddress transportAddress = new InetSocketTransportAddress(ip);
                TransportClient client=new PreBuiltTransportClient(settings).addTransportAddress(transportAddress);
                return client;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
     
    }   
}

3、测试

         public static void main(String[] args) {
                 try {
                     HashMap<String, Object> hashMap = new HashMap<String, Object>();  
                      hashMap.put("id", "3");  
                      hashMap.put("title","双宿双飞从");
                      hashMap.put("describe", "测试123");  
                      hashMap.put("author", "测试doc");  
                     TransportClient client=EsClientPool.getInstance().getClient();
                    IndexResponse response = client.prepareIndex("tbname", "type",hashMap.get("id").toString())
                            .setSource(hashMap).execute().actionGet();  
                    System.out.println("主键id"+response.getId());;  
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

猜你喜欢

转载自blog.csdn.net/qw463800202/article/details/54616178