zoukankan      html  css  js  c++  java
  • Java API connects Elasticsearch cluster

    写在前面

    org.elasticsearch.client
    transport&elasticsearch-rest-high-level-client

    官网地址:

    https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/transport-client.html

    方式一:TransportClient

    pom.xml

            <!--添加Es的dependency-->
            <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>transport</artifactId>
                <version>6.2.4</version>
            </dependency>
    

    代码:

    package com.sunshine.punch.es;
    
    import org.elasticsearch.action.get.GetResponse;
    import org.elasticsearch.action.get.MultiGetItemResponse;
    import org.elasticsearch.action.get.MultiGetResponse;
    import org.elasticsearch.action.index.IndexResponse;
    import org.elasticsearch.client.Response;
    import org.elasticsearch.client.transport.TransportClient;
    import org.elasticsearch.common.settings.Settings;
    import org.elasticsearch.common.transport.TransportAddress;
    import org.elasticsearch.common.xcontent.XContentBuilder;
    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.io.IOException;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.util.HashMap;
    import java.util.Map;
    
    import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
    
    /**
     * Description:
     *
     * Settings
     * Client/PreBuiltTransportClient
     * client.admin().indices().prepareCreate(INDEX).get();
     * client.admin().indices().prepareDelete(INDEX).get();
     * prepareIndex
     * prepareGet
     * prepareMultiGet
     * get()
     * Hadoop : HDFS + YARN 【生产上主要使用Hadoop的点】
     *         YARN:能够提交Spark等作业上去就行了 Spark on YARN
     *         HDFS:单纯的用来存储数据就好
     *
     * @Author: 留歌36
     * @Date: 2019/5/23 9:55
     */
    public class TransportAddressApp {
        TransportClient client;
        @Before
        public void setUp(){
            // 设置集群名称
            Settings settings = Settings.builder().put("cluster.name", "tongnan-application").build();
            // 创建client
            try {
                client = new PreBuiltTransportClient(settings)
                        .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.1.109"),9300));
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        @After
        public void  tearDown(){
            client.close();
        }
    
        private static final String INDEX = "street";
        private static final String TYPE ="doc";
    
        /**
         * 创建一个索引
         * 默认是:5个分片
         */
        @Test
        public void createIndex(){
            client.admin().indices().prepareCreate(INDEX).get();
        }
    
        /**
         * 删除一个索引
         */
        @Test
        public void deleteIndex(){
            client.admin().indices().prepareDelete(INDEX).get();
        }
    
        /**
         * 删除Doc
         */
        @Test
        public  void  deleteDoc(){
    
            client.prepareDelete(INDEX, TYPE, "1001").get();
    
        }
    
    
        /**
         * 使用Json数据创建一个文档
         * 不推荐
         */
        @Test
        public void createDocWithJson(){
            String json = "{"name":"留歌2"}";
            IndexResponse response =client.prepareIndex(INDEX, TYPE, "1001")
                    .setSource(json, XContentType.JSON)
                    .get();
    
            printInfo(response);
        }
    
        /**
         * 把打印的方法抽取出来
         * @param response
         */
        private void printInfo(IndexResponse response){
            System.out.println("index: "+response.getIndex());
            System.out.println("type: "+response.getType());
            System.out.println("id: "+response.getId());
            System.out.println("version: "+response.getVersion());
            System.out.println("result: "+response.getResult());
        }
    
        /**
         * 使用Map进行构建DOC
         * 推荐
         */
        @Test
        public void createDocWithMap(){
            Map<String,Object> map = new HashMap<>();
            map.put("street","留歌街道");
            IndexResponse response = client.prepareIndex(INDEX, TYPE, "1003")
                    .setSource(map)
                    .get();
    
            printInfo(response);
        }
        /**
         * 使用XContentBuilder进行构建DOC
         * ES提供的
         * 推荐
         */
        @Test
        public void createDocWithXContentBuilder() throws IOException {
            XContentBuilder builder = jsonBuilder()
                    .startObject()
                    .field("name","留歌的网站")
                    .field("content","主要是一些日常Vlog")
                    .field("url","www.csyh.cn")
                    .endObject();
            IndexResponse response = client.prepareIndex(INDEX, TYPE, "1003")
                    .setSource(builder)
                    .get();
    
            printInfo(response);
    
        }
    
        /**
         * 查询Doc数据【单个】
         */
        @Test
        public void getDocById(){
           GetResponse response = client.prepareGet(INDEX, TYPE, "1003").get();
    
            System.out.println(response.getSourceAsString());
        }
        /**
         * 查询Docs数据【多个】
         */
        @Test
        public void getDocsByIds(){
            MultiGetResponse responses = client.prepareMultiGet()
                    .add(INDEX, TYPE, "1003")
                    .add(INDEX, TYPE, "1001","1002","1002222") // 这里的可变参数 是可以多个ID的
                    .get();
    
            for (MultiGetItemResponse response : responses){
                GetResponse res = response.getResponse();
                if (res.isExists()){
                    System.out.println(res.getSourceAsString());
                }
            }
        }
    }
    
    

    方式二:TransportClient

    pom.xml

          <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>6.5.4</version>
            </dependency>
    

    代码:

    package com.sunshine.punch.es;
    
    import org.apache.http.HttpHost;
    import org.elasticsearch.action.bulk.BulkItemResponse;
    import org.elasticsearch.action.bulk.BulkRequest;
    import org.elasticsearch.action.bulk.BulkResponse;
    import org.elasticsearch.action.get.GetRequest;
    import org.elasticsearch.action.index.IndexRequest;
    import org.elasticsearch.client.RequestOptions;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.elasticsearch.common.xcontent.XContentType;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.io.IOException;
    
    /**
     * Description: TODO
     *
     * @Author: 留歌36
     * @Date: 2019/5/24 8:50
     */
    public class HighLevelRestClientApp {
        RestHighLevelClient client;
        @Before
        public void setUp(){
            client = new RestHighLevelClient(RestClient.builder(
                    new HttpHost("192.168.1.109",9200,"http")
            ));
    
        }
        @After
        public void tearDown(){
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Test
        public void getClient(){
            System.out.println(client);
        }
        private final String INDEX = "street";
        private final String TYPE = "doc";
    
    
        /**
         * 判断文档是否存在
         */
        @Test
        public void existDoc() throws IOException{
            GetRequest request = new GetRequest(INDEX, TYPE, "1001");
            boolean exists = client.exists(request, RequestOptions.DEFAULT);
            System.out.println("是否存在:" + exists);
        }
    
        /**
         * 创建Doc
         *
         */
        @Test
        public void createDoc(){
    
        }
        /**
         * get Doc
         *
         */
        @Test
        public void getDoc(){
    
        }
        /**
         * 批量Doc
         *
         */
        @Test
        public void bulkDoc() throws IOException{
            BulkRequest request = new BulkRequest();
            request.add(new IndexRequest(INDEX,TYPE).id("1004")
                    .source(XContentType.JSON,"street", "测试镇1"));
            request.add(new IndexRequest(INDEX,TYPE).id("1004")
                    .source(XContentType.JSON,"street", "测试镇2"));
    
    
    
            // 同步执行
            BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                for (BulkItemResponse bulkItemResponse : bulkResponse) {
                    if (bulkItemResponse.isFailed()) {
                        BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
                        System.out.println(failure.getMessage());
                    }
                }
            }
    
    
    
        }
        /**
         * Kibana
         * 1.全链路监控
         * 2.ak分词
         * 3.es-sql 插件
         */
    
    }
    
    
  • 相关阅读:
    实现用户信息的增删改-mongoose数据库操作
    gulp使用流程及常用插件
    Js面向对象动态添加标签页,Tab栏切换
    类似淘宝侧边栏jq代码编写
    jQuery选择器
    jQuery-突出显示案例
    隔行变色加高亮显示
    ajax请求到后台
    LOOK OUT THE HOLE!
    应用keyup监测输入框兼容IE处理
  • 原文地址:https://www.cnblogs.com/liuge36/p/12614738.html
Copyright © 2011-2022 走看看