ElasticSearch Windows集群下的Java API实现简单的CURD操作

ElasticSearch Windows集群下的Java API实现简单的CURD操作

一、环境说明


  1. Windows上部署三节点的集群,参考:ElasticSearch Windows集群安装部署
  2. elasticsearch版本:7.8.0
  3. 测试框架:JUnit

二、实现步骤


  1. 创建maven项目

  2. 添加es相关依赖,依赖如下:

    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch 的客户端 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch 依赖 2.x 的 log4j -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>
        <!-- junit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    
  3. 创建ESClientTest测试类,具体代码如下

    package com.suben.es;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.suben.es.entity.Student;
    import org.apache.http.HttpHost;
    import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
    import org.elasticsearch.action.bulk.BulkRequest;
    import org.elasticsearch.action.bulk.BulkResponse;
    import org.elasticsearch.action.delete.DeleteRequest;
    import org.elasticsearch.action.index.IndexRequest;
    import org.elasticsearch.action.index.IndexResponse;
    import org.elasticsearch.action.search.SearchRequest;
    import org.elasticsearch.action.search.SearchResponse;
    import org.elasticsearch.action.support.master.AcknowledgedResponse;
    import org.elasticsearch.client.*;
    import org.elasticsearch.client.indices.CreateIndexRequest;
    import org.elasticsearch.client.indices.CreateIndexResponse;
    import org.elasticsearch.client.indices.GetIndexRequest;
    import org.elasticsearch.client.indices.GetIndexResponse;
    import org.elasticsearch.common.xcontent.XContentType;
    import org.elasticsearch.index.query.QueryBuilders;
    import org.elasticsearch.search.SearchHit;
    import org.elasticsearch.search.SearchHits;
    import org.elasticsearch.search.builder.SearchSourceBuilder;
    import org.junit.Test;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class ESClientTest {
    
        private static final String INDEX_NAME = "students";
    
        /**
         * 连接es集群中多个节点的写法:可以同时写明集群中所有的节点相关信息
         * @throws Exception
         */
        @Test
        public void testCreateIndex() throws Exception{
            RestHighLevelClient client =
                    new RestHighLevelClient(
                            RestClient.builder(
                                    new HttpHost("localhost", 1004, "http"),
                                    new HttpHost("localhost", 1005, "http"),
                                    new HttpHost("localhost", 1006, "http"))
                    );
            // 构造索引对象
            CreateIndexRequest index001 = new CreateIndexRequest(INDEX_NAME);
            // client创建索引
            CreateIndexResponse response = client.indices().create(index001, RequestOptions.DEFAULT);
            // 查看下释放创建成功
            boolean acknowledged = response.isAcknowledged();
            // 输出执行结果
            System.out.println("创建索引:" + acknowledged);
    
            // 释放资源
            client.close();
        }
    
        @Test
        public void testGetIndex() throws Exception{
            RestHighLevelClient client =
                    new RestHighLevelClient(
                            RestClient.builder(
                                    new HttpHost("localhost", 1004, "http"),
                                    new HttpHost("localhost", 1005, "http"),
                                    new HttpHost("localhost", 1006, "http"))
                    );
            // 构造索引对象
            GetIndexRequest index001 = new GetIndexRequest(INDEX_NAME);
            // client创建索引
            GetIndexResponse response = client.indices().get(index001, RequestOptions.DEFAULT);
            // 输出执行结果
            System.out.println("创建索引:" + response.getAliases());
            System.out.println("创建索引:" + response.getSettings());
            System.out.println("创建索引:" + response.getMappings());
    
            // 释放资源
            client.close();
        }
    
        /**
         * 连接es集群另外一种方式:可以只写其中某一台节点相关信息
         * @throws Exception
         */
        @Test
        public void testDeleteIndex() throws Exception{
            RestHighLevelClient client =
                    new RestHighLevelClient(
                            RestClient.builder(
                                    new HttpHost("localhost", 1004, "http"))
                    );
            // 构造索引对象
            DeleteIndexRequest index001 = new DeleteIndexRequest(INDEX_NAME);
            // client创建索引
            AcknowledgedResponse response = client.indices().delete(index001,RequestOptions.DEFAULT);
            // 输出执行结果
            System.out.println("删除索引:" + response.isAcknowledged());
            // 释放资源
            client.close();
        }
    
        @Test
        public void testAddDocument() throws Exception{
            RestHighLevelClient client =
                    new RestHighLevelClient(
                            RestClient.builder(
                                    new HttpHost("localhost", 1004, "http"))
                    );
    
            // 新增文档请求对象
            IndexRequest indexRequest = new IndexRequest();
            // 设置索引及其唯一标识
            indexRequest.index(INDEX_NAME).id("1002");
    
            // 构造文档对象
            Student student = new Student("李云龙",34,"男");
            Student student2 = new Student("张三",34,"男");
            Student student3 = new Student("赵丽颖",34,"女");
    
            List<Student> list = new ArrayList<>();
            list.add(student);
            list.add(student2);
            list.add(student3);
    
            // 将User对象转成Json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String stuJson = objectMapper.writeValueAsString(student);
    
            // 设置文档数据为Student,格式为json
            indexRequest.source(stuJson,objectMapper.writeValueAsString(student2),objectMapper.writeValueAsString(student3),
                    XContentType.JSON);
    
            // 提交新增文档请求(同步模式)
            IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
    
            // 输出执行结果
            System.out.println("新增文档:" + response);
            // 释放资源
            client.close();
        }
    
        @Test
        public void testBatchAddDocument() throws Exception{
            RestHighLevelClient client =
                    new RestHighLevelClient(
                            RestClient.builder(
                                    new HttpHost("localhost", 1004, "http"))
                    );
            // 创建批量请求对象
            BulkRequest bulkRequest = new BulkRequest();
    
            // 新增文档对象
            for (int i = 0; i < 10; i++) {
                int uniqueId = 3000 + (i + 1);
                if (i % 2 == 0){
                    bulkRequest.add(new IndexRequest().index(INDEX_NAME).id(String.valueOf(uniqueId)).source(new ObjectMapper().writeValueAsString(new Student("帅哥"+i + "号",28+i,"男")),XContentType.JSON));
                }else{
                    bulkRequest.add(new IndexRequest().index(INDEX_NAME).id(String.valueOf(uniqueId)).source(new ObjectMapper().writeValueAsString(new Student("美女"+i + "号",18+i,"女")),XContentType.JSON));
                }
            }
    
            // 提交新增文档请求(同步模式)
            BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    
            // 输出执行结果
            System.out.println("批量新增文档时间:" + response.getTook());
            System.out.println("批量新增文档结果:" + response.getItems());
            // 释放资源
            client.close();
        }
    
        @Test
        public void testBatchDeleteDocument() throws Exception{
            RestHighLevelClient client =
                    new RestHighLevelClient(
                            RestClient.builder(
                                    new HttpHost("localhost", 1004, "http"))
                    );
            // 创建批量请求对象
            BulkRequest bulkRequest = new BulkRequest();
    
            // 新增文档对象
            for (int i = 0; i < 10; i++) {
                int uniqueId = 2000 + (i + 1);
                bulkRequest.add(new DeleteRequest().id(String.valueOf(uniqueId)).index(INDEX_NAME));
            }
    
            // 提交新增文档请求(同步模式)
            BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    
            // 输出执行结果
            System.out.println("批量删除文档时间:" + response.getTook());
            System.out.println("批量删除文档结果:" + response.getItems());
            // 释放资源
            client.close();
        }
    
        @Test
        public void testQueryIndexDatas() throws Exception{
            RestHighLevelClient client =
                    new RestHighLevelClient(
                            RestClient.builder(
                                    new HttpHost("localhost", 1004, "http"))
                    );
            // 创建查询请求对象
            SearchRequest searchRequest = new SearchRequest();
            // 指定查询的索引
            searchRequest.indices(INDEX_NAME);
    
            // 构造查询索引的请求对象
            SearchSourceBuilder requestBuilder = new SearchSourceBuilder();
            // 设置查询条件:查询所有,match_all
            requestBuilder.query(QueryBuilders.matchAllQuery());
            // 设置显示的总条数,默认只显示10条
            requestBuilder.size(1000);
    
            // 设置查询请求对象条件,即requestBuilder
            searchRequest.source(requestBuilder);
    
            // 提交
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
    
            // 输出执行结果
            SearchHits hits = response.getHits();
            System.out.println("took:" + response.getTook());
            System.out.println("timeout:" + response.isTimedOut());
            System.out.println("total:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("hits========>>");
            for (SearchHit hit : hits) {
                //输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
            System.out.println("<<========");
    
            // 释放资源
            client.close();
        }
    }
    

    注意事项:由于es默认只显示命中的10条记录,故在代码中需要设置你想显示的总条数,如果不设置,在我的测试数据中总15条,代码执行后,只显示了十条,如下所示:
    在这里插入图片描述

    故需要代码中修改下,上述代码中通过requestBuilder对象设置了1000条,,修改完成后,正常显示,如下:
    在这里插入图片描述

  4. 为了查看日志,可以在resources目录下添加log4j2.xml,内容如下

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="WARN">
        <Appenders>
            <Console name="Console" target="SYSTEM_OUT">
                <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
            </Console>
    
            <RollingFile name="RollingFile" filename="log/test.log"
                         filepattern="${logPath}/%d{YYYYMMddHHmmss}-fargo.log">
                <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
                <Policies>
                    <SizeBasedTriggeringPolicy size="10 MB" />
                </Policies>
                <DefaultRolloverStrategy max="20" />
            </RollingFile>
    
        </Appenders>
        <Loggers>
            <Root level="info">
                <AppenderRef ref="Console" />
                <AppenderRef ref="RollingFile" />
            </Root>
        </Loggers>
    </Configuration>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若兰幽竹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值