阅读背景:

ElasticsearchJavaAPI-客户端连接

来源:互联网 
package com.java1234;

import com.google.gson.JsonObject;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;

/**
 * @author XXL
 * @create 2019-08-04 13:05
 */
public class ESConn {

    protected TransportClient client;

    @Before
    public void setUp() throws Exception {

        Settings esSettings = Settings.builder()
                .put("cluster.name", "my-application") //设置ES实例的名称
                // 这个不能乱加, 加了报错啊
//                .put("client.transport.sniff", true) //主动嗅探全部集群的状况,把集群中其他ES节点的ip添加到本地的客户端列表中
                .build();

        /**
         * 这里的衔接方法指的是没有安装x-pack插件,如果安装了x-pack则参考{@link ElasticsearchXPackClient}
         * 1. java客户真个方法是以tcp协定在9300端口上进行通讯
         * 2. http客户真个方法是以http协定在9200端口上进行通讯
         */
        client = new PreBuiltTransportClient(esSettings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("公网ip"), 9300));

        System.out.println("ElasticsearchClient 衔接胜利");
    }

    @Test
    public void testClientConnection() throws Exception {
        System.out.println(client);
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("name", "java 编程思想");
        jsonObject.addProperty("publishDate", "2018-11-11");
        jsonObject.addProperty("price", 100);

        IndexResponse response=client.prepareIndex("book", "java", "1")
                .setSource(jsonObject.toString(), XContentType.JSON).get();
        System.out.println("索引名称:"+response.getIndex());
        System.out.println("类型:"+response.getType());
        System.out.println("文档ID:"+response.getId());
        System.out.println("当前实例状况:"+response.status());
        System.out.println("--------------------------");
    }

    @After
    public void tearDown() throws Exception {
        if (client != null) {
            client.close();
        }

    }

}
package com.java1234;

import com.google.gson.J



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: