zoukankan      html  css  js  c++  java
  • es使用java的api操作

    基本环境的创建

    pom依赖

     <?xml version="1.0" encoding="UTF-8"?>
     <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.player3.es</groupId>
        <artifactId>estest</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>estest</name>
        <description>Demo project for Spring Boot</description>
     
        <properties>
            <java.version>1.8</java.version>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
        </properties>
     
        <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>
     
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
     
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
     
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-dependencies</artifactId>
                    <version>${spring-boot.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
     
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <version>2.3.7.RELEASE</version>
                    <configuration>
                        <mainClass>com.player3.es.estest.EstestApplication</mainClass>
                    </configuration>
                    <executions>
                        <execution>
                            <id>repackage</id>
                            <goals>
                                <goal>repackage</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
     
     </project>
     

    创建索引 EsTest_Client

     public static void main(String[] args) throws IOException {
           //创建es客户端对象
             RestHighLevelClient esclient = new RestHighLevelClient(
                     RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
             ///关闭连接
             esclient.close();
        }

    通过:localhost:9200/_cat/indices?v 查看,确实新增一条索引

    查询索引 EsTest_index_search

      public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
     
            GetIndexRequest player3 = new GetIndexRequest("player3");
            GetIndexResponse response = esclient.indices().get(player3, RequestOptions.DEFAULT);
     
              System.out.println(response.getAliases());
              System.out.println(response.getDataStreams());
              System.out.println(response.getDefaultSettings());
              System.out.println(response.getIndices());
              System.out.println(response.getMappings());
              System.out.println(response.getSettings());
            ///关闭连接
            esclient.close();
        }

    删除索引: EsTest_index_delete

       public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            DeleteIndexRequest shoppingg = new DeleteIndexRequest("shoppingg");
     
            AcknowledgedResponse delete = esclient.indices().delete(shoppingg, RequestOptions.DEFAULT);//create(request, RequestOptions.DEFAULT);
     ///关闭连接
            System.out.println(delete.isAcknowledged());
            esclient.close();
        }

     

    在索引下新增数据 EsTest_Client_Doc_Insert

     class User
     
     private String name;
      private String sex;
      private Integer age;

     

      public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            //插入数据
            IndexRequest indexRequest = new IndexRequest();
            //需要插入的数据 index|索引 id|唯一标识
            indexRequest.index("user").id("1020");
            User user = new User();
            user.setName("李为");
            user.setSex("男");
            user.setAge(27);
            // 向es插入数据,必须将数据转换为json jackson
            ObjectMapper mapper=new ObjectMapper();
            String userjson = mapper.writeValueAsString(user);//对象转str
            indexRequest.source(userjson, XContentType.JSON);//index为user,id1020的数据
            IndexResponse index = esclient.index(indexRequest, RequestOptions.DEFAULT);
            System.out.println(index);
            ///关闭连接
            esclient.close();
        }

     

    索引下的修改数据 EsTest_Client_Doc_Update

     
        //TODO 如果直接把全部的值替换 就是全量更新
     //   public static void main(String[] args) throws IOException {
     //       //创建es客户端对象
     //       RestHighLevelClient esclient = new RestHighLevelClient(
     //               RestClient.builder(new HttpHost("localhost",9200,"http"))
     //       );
     //       //插入数据
     //       IndexRequest indexRequest = new IndexRequest();
     //       //需要插入的数据 index|索引 id|唯一标识
     //       indexRequest.index("user").id("1020");
     //
     //       User user = new User();
     //       user.setName("李为");
     //       user.setSex("男");
     //       user.setAge(26);
     //       // 向es插入数据,必须将数据转换为json jackson
     //       ObjectMapper mapper=new ObjectMapper();
     //       String userjson = mapper.writeValueAsString(user);//对象转str
     //       indexRequest.source(userjson, XContentType.JSON);//index为user,id1020的数据
     //       IndexResponse index = esclient.index(indexRequest, RequestOptions.DEFAULT);
     //       System.out.println(index);
     //       ///关闭连接
     //       esclient.close();
     //   }
     
        public static void main(String[] args) throws IOException {
                    //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
     
     
            UpdateRequest update = new UpdateRequest();
            update.index("user").id("1020");
          update.doc(XContentType.JSON,"sex","女","age",18);
     
            esclient.update(update, RequestOptions.DEFAULT);
            esclient.close();
        }

    索引下的删除数据 EsTest_Client_Doc_delete

       public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            DeleteRequest deleteRequest = new DeleteRequest();
            deleteRequest.index("user").id("1020");
            esclient.delete(deleteRequest, RequestOptions.DEFAULT);
     
     
            ///关闭连接
            esclient.close();
        }

    索引下的批量插入 EsTest_Client_Doc_insert_bash

     public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            BulkRequest request = new BulkRequest();
            request.add(new IndexRequest().index("user").id("1010").source(XContentType.JSON,
                    "name","李伟","age",27,"sex","男"));
            request.add(new IndexRequest().index("user").id("1011").source(XContentType.JSON,
                    "name","lisi","age",22,"sex","女"));
            request.add(new IndexRequest().index("user").id("1012").source(XContentType.JSON,
                    "name","wangwu","age",26,"sex","女"));
            request.add(new IndexRequest().index("user").id("1013").source(XContentType.JSON,
                    "name","zhaoliu","age",27,"sex","女"));
            esclient.bulk(request, RequestOptions.DEFAULT);
            ///关闭连接
            esclient.close();
        }

    索引下的批量删除数据 EsTest_Client_Doc_delete_bash

     public static void main(String[] args) throws IOException {
            //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            BulkRequest request = new BulkRequest();
            request.add(new DeleteRequest().index("user").id("1010"));
            request.add(new DeleteRequest().index("user").id("1011"));
            request.add(new DeleteRequest().index("user").id("1012"));
            request.add(new DeleteRequest().index("user").id("1013"));
            esclient.bulk(request, RequestOptions.DEFAULT);
            ///关闭连接
            esclient.close();
        }

     

    条件查询之全部查询 EsTest_Client_Query

    public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices("user");
            //查询所有的数据
            searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
            SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
           // System.out.println(search);
            SearchHits hits = search.getHits();
            System.out.println(hits.getTotalHits());
            System.out.println(search.getTook());
          for(SearchHit hit:hits){
              System.out.println(hit.getSourceAsString());
          }
            ///关闭连接
            esclient.close();
        }

    条件查询之匹配查询 EsTest_Client_termQuery

     public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest req = new SearchRequest();
            req.indices("user");
            req.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",27)));
    
            SearchResponse search = esclient.search(req, RequestOptions.DEFAULT);
    
            ///关闭连接
            esclient.close();
            SearchHits hits = search.getHits();
            for(SearchHit hit:hits){
                System.out.println(hit.getSourceAsString());
            }
        }

    条件查询之分页查询 EsTest_Client_From_Size

     public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest searchRequest = new SearchRequest();
            SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
            query.from(0);//当前页
            query.size(3);//每页条数
            searchRequest.indices("user");
            searchRequest.source(query);
           // searchRequest.
            SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = search.getHits();
            for(SearchHit hit:hits){
                System.out.println(hit.getSourceAsString());
            }
            ///关闭连接
            esclient.close();
        }

    条件查询之排序 EsTest_Client_From_Size_Sort

      public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest searchRequest = new SearchRequest();
            SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
            query.from(0);//当前页
            query.size(3);//每页条数
            query.sort("age", SortOrder.DESC);
            searchRequest.indices("user");
            searchRequest.source(query);
           // searchRequest.
            SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = search.getHits();
            for(SearchHit hit:hits){
                System.out.println(hit.getSourceAsString());
            }
            ///关闭连接
            esclient.close();
        }

    条件查询之排除某列 EsTest_Client_Fetch

    public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest searchRequest = new SearchRequest();
            SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
           String[] includes={};//包含
           String[] excludes={"age"};//排除
    
            query.fetchSource(includes,excludes);
            searchRequest.indices("user");
            searchRequest.source(query);
           // searchRequest.
            SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = search.getHits();
            for(SearchHit hit:hits){
                System.out.println(hit.getSourceAsString());
            }
            ///关闭连接
            esclient.close();
        }

    组合查询 EsTest_Client_Should

    查询男人 年龄30的

     public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices("user");
            SearchSourceBuilder builder = new SearchSourceBuilder();
            BoolQueryBuilder bool = new BoolQueryBuilder();
            bool.must(QueryBuilders.matchQuery("sex","男"));
            bool.must(QueryBuilders.matchQuery("age",27));
           //组合查询
            builder.query(bool);
            searchRequest.source(builder);
    
    
            SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
            ///关闭连接
            SearchHits hits = search.getHits();
            esclient.close();
            for(SearchHit hit:hits){
                System.out.println(hit.getSourceAsString());
            }
    
        }

    查询不是男人的

    public static void main(String[] args) throws IOException {
      //创建es客户端对象
        RestHighLevelClient esclient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder bool = new BoolQueryBuilder();
        bool.must(QueryBuilders.matchQuery("age",27));
        bool.mustNot(QueryBuilders.matchQuery("sex","男"));
       //组合查询
        builder.query(bool);
        searchRequest.source(builder);
    
    
        SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
        ///关闭连接
        SearchHits hits = search.getHits();
        esclient.close();
        for(SearchHit hit:hits){
            System.out.println(hit.getSourceAsString());
        }
    
    }

    年龄为26或27

    public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices("user");
            SearchSourceBuilder builder = new SearchSourceBuilder();
            BoolQueryBuilder bool = new BoolQueryBuilder();
            // age=27 and sex =男
    //        bool.must(QueryBuilders.matchQuery("age",27));
    //        bool.mustNot(QueryBuilders.matchQuery("sex","男"));
            
            //age=26 or age=27
            bool.should(QueryBuilders.matchQuery("age",27));
            bool.should(QueryBuilders.matchQuery("age",26));
    
           //组合查询
            builder.query(bool);
            searchRequest.source(builder);
    
    
            SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
            ///关闭连接
            SearchHits hits = search.getHits();
            esclient.close();
            for(SearchHit hit:hits){
                System.out.println(hit.getSourceAsString());
            }
    
        }

    年龄大于等于27小于40

     public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices("user");
            SearchSourceBuilder builder = new SearchSourceBuilder();
    //年龄大于等于27小于40
            RangeQueryBuilder age = QueryBuilders.rangeQuery("age");
            age.gte(27);
            age.lt(40);
            //组合查询
            builder.query(age);
            searchRequest.source(builder);
    
    
            SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
            ///关闭连接
            SearchHits hits = search.getHits();
            esclient.close();
            for(SearchHit hit:hits){
                System.out.println(hit.getSourceAsString());
            }
    
        }

    高亮查询 EsTest_Client_GaoLiang

     public static void main(String[] args) throws IOException {
          //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest request = new SearchRequest();
            request.indices("user");
            SearchSourceBuilder builder = new SearchSourceBuilder();
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhaoliu");
    
    //SearchSourceBuilder 带有高亮标签
            //记住这里是创建的不是 builder.highlighter 空参弄出来的,不然会报错的
            HighlightBuilder highlighter = new HighlightBuilder();
            highlighter.preTags("<font color='red'>");//前缀
            highlighter.postTags("</font>");//后缀
            highlighter.field("name");//name属性高亮显示
            builder.highlighter(highlighter);
            builder.query(termQueryBuilder);
    
            request.source(builder);
            SearchResponse search = esclient.search(request, RequestOptions.DEFAULT);
    
            SearchHits hits = search.getHits();
            ///关闭连接
            esclient.close();
            for(SearchHit hit:hits){
                System.out.println(hit.getSourceAsString());
            }
    
        }

    聚合查询

    求最大值

        public static void main(String[] args) throws IOException {
            //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest request = new SearchRequest();
            request.indices("user");
            SearchSourceBuilder builder = new SearchSourceBuilder();
            MaxAggregationBuilder field = AggregationBuilders.max("maxAge").field("age");
            builder.aggregation(field);
            request.source(builder);
            SearchResponse search = esclient.search(request, RequestOptions.DEFAULT);
    
            SearchHits hits = search.getHits();
            ///关闭连接
            esclient.close();
            for(SearchHit hit:hits){
                System.out.println(hit.getSourceAsString());
            }
    
        }

    分组

     public static void main(String[] args) throws IOException {
            //创建es客户端对象
            RestHighLevelClient esclient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http"))
            );
            SearchRequest request = new SearchRequest();
            request.indices("user");
            SearchSourceBuilder builder = new SearchSourceBuilder();
            TermsAggregationBuilder ageGroup = AggregationBuilders.terms("ageGroup").field("age");
            builder.aggregation(ageGroup);
            request.source(builder);
            SearchResponse search = esclient.search(request, RequestOptions.DEFAULT);
    
            SearchHits hits = search.getHits();
            ///关闭连接
            esclient.close();
            for(SearchHit hit:hits){
                System.out.println(hit.getSourceAsString());
            }
    
        }
  • 相关阅读:
    设计模式之单例模式(Singleton)
    ASP.Net WebForm温故知新学习笔记:二、ViewState与UpdatePanel探秘
    ASP.Net WebForm温故知新学习笔记:一、aspx与服务器控件探秘
    [学习笔记] $Maximum$ $Minimum$ $identity$
    BZOJ 2159: Crash 的文明世界(组合数学+第二类斯特林数+树形dp)
    BZOJ 3083: 遥远的国度 (树剖+线段树)
    LUOGU P4560 [IOI2014]Wall 砖墙 (线段树)
    牛客网 NOIP赛前集训营-普及组(第四场)C--部分和 (高维前缀和)
    LUOGU P1501 [国家集训队]Tree II (lct)
    LUOGU P3690 【模板】Link Cut Tree (lct)
  • 原文地址:https://www.cnblogs.com/q1359720840/p/14703023.html
Copyright © 2011-2022 走看看