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

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

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

文章目录

  • 3.5 Java API 操作
    • 3.5.1 搭建环境
    • 3.5.2 创建客户端对象
    • 3.5.3 索引操作
    • 3.5.4 文档操作
    • 3.5.5 高级查询

3.5 Java API 操作

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

3.5.1 搭建环境

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

  2. 修改 Pom.xml

    <dependencies>
        <dependency>
            <groupId>org.elasticsearchgroupId>
            <artifactId>elasticsearchartifactId>
            <version>7.8.0version>
        dependency>
        
        <dependency>
            <groupId>org.elasticsearch.clientgroupId>
            <artifactId>elasticsearch-rest-high-level-clientartifactId>
            <version>7.8.0version>
        dependency>
        
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-apiartifactId>
            <version>2.8.2version>
        dependency>
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-coreartifactId>
            <version>2.8.2version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.9.9version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        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();
        }
    }
    
  • 启动测试
    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第1张图片
  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());
    
    

    允许测试
    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第2张图片

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

    运行测试
    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第3张图片

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

    运行测试
    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第4张图片

  3. 查询文档

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

    运行测试
    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第5张图片

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

    运行测试
    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第6张图片

  • 批量删除

    // 批量删除数据
        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());
    

    运行测试
    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第7张图片

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

    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第8张图片

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

    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第9张图片

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

    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第10张图片

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

    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第11张图片

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

    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第12张图片

  6. 组合查询

    	SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //boolQueryBuilder.must(QueryBuilders.matchQuery("age", 30));
        //boolQueryBuilder.must(QueryBuilders.matchQuery("sex", "男"));
        //boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex", "男"));
        boolQueryBuilder.should(QueryBuilders.matchQuery("age", 30));
        boolQueryBuilder.should(QueryBuilders.matchQuery("age", 40));
        builder.query(boolQueryBuilder);
        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());
        }
    

    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第13张图片

  7. 范围查询

    	SearchRequest request = new SearchRequest();
        request.indices("user");
    
        SearchSourceBuilder builder = new SearchSourceBuilder();
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
    
        rangeQuery.gte(30);
        rangeQuery.lt(50);
    
        builder.query(rangeQuery);
    
        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());
        }
    

    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第14张图片

  8. 模糊查询

    	SearchRequest request = new SearchRequest();
        request.indices("user");
    
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.fuzzyQuery("name", "wangwu").fuzziness(Fuzziness.TWO));
    
        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());
        }
    

    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第15张图片

  9. 高亮查询

    	SearchRequest request = new SearchRequest();
        request.indices("user");
    
        SearchSourceBuilder builder = new SearchSourceBuilder();
        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "zhangsan");
    
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        highlightBuilder.field("name");
    
        builder.highlighter(highlightBuilder);
        builder.query(termsQueryBuilder);
    
        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());
            System.out.println(hit.getHighlightFields());
        }
    

    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第16张图片

  10. 聚合查询

    	SearchRequest request = new SearchRequest();
        request.indices("user");
    
        SearchSourceBuilder builder = new SearchSourceBuilder();
    
        AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
        builder.aggregation(aggregationBuilder);
    
        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());
        }
    

    Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记_第17张图片

  11. 分组查询

    	SearchRequest request = new SearchRequest();
        request.indices("user");
    
        SearchSourceBuilder builder = new SearchSourceBuilder();
    
        AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
        builder.aggregation(aggregationBuilder);
    
        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());
        }
    

你可能感兴趣的:(Elasticsearch,elasticsearch)