Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记

Posted yuan_404

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记相关的知识,希望对你有一定的参考价值。

上一篇:(3. Elasticsearch 基本操作_上)学习笔记

下一篇:(5. Elasticsearch 环境)学习笔记

3.5 Java API 操作

  • Elasticsearch 软件是由 Java 语言开发的,所以也可以通过 Java API 的方式对 Elasticsearch
    服务进行访问

3.5.1 搭建环境

  1. 在 IDEA 中创建一个 Maven 依赖

  2. 修改 Pom.xml

    <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.5.2 创建客户端对象

  • 新建一个类,并编写代码

    public class ESTest_Client {
        public static void main(String[] args) throws Exception {
            // 创建ES客户端
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost", 9200, "http"))
            );
            // 关闭ES客户端
            esClient.close();
        }
    }
    

    注意:9200 端口为 Elasticsearch 的 Web 通信端口,localhost 为启动 ES 服务的主机名

  • 启动测试

    控制台没有报错就表示连接成功

3.5.3 索引操作

  • ES 服务器正常启动后,可以通过 Java API 客户端对象对 ES 索引进行操作
  1. 创建索引
  • 创建新的类,并编写
    public class ESTest_Index_Create {
        public static void main(String[] args) throws Exception {
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost", 9200, "http"))
            );
            // 创建索引
            CreateIndexRequest request = new CreateIndexRequest("user");
            CreateIndexResponse createIndexResponse =
                    esClient.indices().create(request, RequestOptions.DEFAULT);
            // 响应状态
            boolean acknowledged = createIndexResponse.isAcknowledged();
            System.out.println("索引操作 :" + acknowledged);
            esClient.close();
        }
    }
    
  • 启动测试
    在这里插入图片描述
  1. 查看索引

    // 查询索引
        GetIndexRequest request = new GetIndexRequest("user");
    
        GetIndexResponse getIndexResponse =
                esClient.indices().get(request, RequestOptions.DEFAULT);
        // 响应状态
        System.out.println(getIndexResponse.getAliases());
        System.out.println(getIndexResponse.getMappings());
        System.out.println(getIndexResponse.getSettings());
    

    允许测试
    在这里插入图片描述

  2. 删除索引

     // 查询索引
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        AcknowledgedResponse response = esClient.indices().delete(request, RequestOptions.DEFAULT);
        // 响应状态
        System.out.println(response.isAcknowledged());
    
    

    允许测试
    在这里插入图片描述

3.5.4 文档操作

  • 创建数据模型

    public class User {
        private String name;
        private String sex;
        private Integer age;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
    }
    
  1. 新增文档

     // 插入数据
        IndexRequest request = new IndexRequest();
        request.index("user").id("1001");
    
        User user = new User();
        user.setName("zhangsan");
        user.setAge(30);
        user.setSex("男");
    
        // 向ES插入数据,必须将数据转换位JSON格式
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);
        request.source(userJson, XContentType.JSON);
    
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
    
        System.out.println(response.getResult());
    

    运行测试
    在这里插入图片描述

  2. 修改文档

    // 修改数据
        UpdateRequest request = new UpdateRequest();
        request.index("user").id("1001");
        request.doc(XContentType.JSON, "sex", "女");
    
        UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
    
        System.out.println(response.getResult());
    

    运行测试
    在这里插入图片描述

  3. 查询文档

    // 查询数据
        GetRequest request = new GetRequest();
        request.index("user").id("1001");
        GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
    
        System.out.println(response.getSourceAsString());
    

    运行测试
    在这里插入图片描述

  4. 删除文档

    	DeleteRequest request = new DeleteRequest();
        request.index("user").id("1001");
    
        DeleteResponse response = esClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    

    运行测试
    在这里插入图片描述

  5. 批量操作

  • 批量新增

    // 批量插入数据
        BulkRequest request = new BulkRequest();
    
        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan", "age",30,"sex","男"));
        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi", "age",30,"sex","女"));
        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu", "age",40,"sex","男"));
    
        BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.getTook());
        System.out.println(response.getItems());
    

    运行测试
    在这里插入图片描述

  • 批量删除

    // 批量删除数据
        BulkRequest request = new BulkRequest();
    
        request.add(new DeleteRequest().index("user").id("1001"));
        request.add(new DeleteRequest().index("user").id("1002"));
        request.add(new DeleteRequest().index("user").id("1003"));
    
        BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.getTook());
        System.out.println(response.getItems());
    

    运行测试
    在这里插入图片描述

3.5.5 高级查询

  1. 查询所有索引数据

    // 1. 查询索引中全部的数据
        SearchRequest request = new SearchRequest();
        request.indices("user");
        request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());
        for ( SearchHit hit : hits ) {
            System.out.println(hit.getSourceAsString());
        }
    

    在这里插入图片描述

  2. term 查询,查询条件为关键字

    	SearchRequest request = new SearchRequest();
        request.indices("user");
        request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age", 30)));
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());
        for ( SearchHit hit : hits ) {
            System.out.println(hit.getSourceAsString());
        }
    

    在这里插入图片描述

  3. 分页查询

    	SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        // (当前页码-1)*每页显示数据条数
        builder.from(2);
        builder.size(2);
        request.source(builder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());
        for ( SearchHit hit : hits ) {
            System.out.println(hit.getSourceAsString());
        }
    

    在这里插入图片描述

  4. 查询排序

    	SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        builder.sort("age", SortOrder.DESC);
        request.source(builder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());
        for ( SearchHit hit : hits ) {
            System.out.println(hit.getSourceAsString());
        }
    

    在这里插入图片描述

  5. 过滤字段

    	SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        String[] excludes = {"age"};
        String[] includes = {};
        builder.fetchSource(includes, excludes);
        request.source(builder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());
        for ( SearchHit hit : hits ) {
            System.out.println(hit.getSourceAsString());
        }
    

    在这里插入图片描述

  6. 组合查询

    	SearchRequest request = new SearchRequest();
        

    以上是关于Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

    Elasticsearch-尚硅谷(8. 优化)学习笔记

    Elasticsearch-尚硅谷(8. 优化)学习笔记

    Elasticsearch - 尚硅谷(3. Elasticsearch 基本操作_上)学习笔记

    Elasticsearch - 尚硅谷(2. Elasticsearch 安装)学习笔记

    Elasticsearch - 尚硅谷(5. Elasticsearch 环境)学习笔记

    Elasticsearch-尚硅谷(9. 面试题)学习笔记