• Elasticsearch Java API


    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();
            }
    
        }
    
    }
    

      

    运行结果:

    温故而知新
  • 相关阅读:
    Socket网络编程
    android开发常用颜色
    eclipse使用技巧以及开发安卓程序过程中遇到的问题
    XML文件中的常用属性
    将博客园的文本编辑栏属性变成可以粘贴
    显示单位px、dip、pt以及sp
    WIN32 API IP地址转换
    常用win32api函数
    win32—GrafMenu的CreateBitmapIndirect创建失败的问题
    #pragam 使用方法
  • 原文地址:https://www.cnblogs.com/Uzai/p/11333592.html
Copyright © 2020-2023  润新知