JAVA操作ES

  1. 新建一个maven工程

  2. 导入依赖

    • elasticsearch (版本要和本地使用的版本一致)
    • elasticsearch的高级API
    • junit
    • lombok
    <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
     
        <groupId>org.example</groupId>
        <artifactId>com.qf</artifactId>
        <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- 1.elastic的jar包
     2.es高级api
     3.junit
     4.lombok-->
        <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.2.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.2.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.22</version>
        </dependency>
    </dependencies>
     
     
     
    </project>
    
  3. 创建测试类连接ES

    1. 获取连接

      package com.qf.utils;
       
      import org.apache.http.HttpHost;
      import org.elasticsearch.client.RestClient;
      import org.elasticsearch.client.RestClientBuilder;
      import org.elasticsearch.client.RestHighLevelClient;
       
      public class ESClient {
       
          public static RestHighLevelClient getClient(){
       
              HttpHost httpHost=new HttpHost("192.128.64.128",9200);
              RestClientBuilder clientBuilder= RestClient.builder(httpHost);
              RestHighLevelClient client=new RestHighLevelClient(clientBuilder);
              return client;
       
          }
       
       
      }
      
    2. 测试连接

      package com.qf.test;
       
      import com.qf.utils.ESClient;
       
      import org.elasticsearch.client.RestHighLevelClient;
       
      import org.junit.Test;
       
       
       
      public class Demo1 {
          @Test
          public void testConnect() {
              try {
                  RestHighLevelClient client = ESClient.getClient();
                  System.out.println("ok!");
              } catch (Exception e) {
                  System.out.println(e);
       
       
              }
          }
      }
      
  4. java创建索引

    package com.qf.test;
     
    import com.qf.utils.ESClient;
     
    import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
    import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
    import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
     
    import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
    import org.elasticsearch.action.support.master.AcknowledgedResponse;
    import org.elasticsearch.client.Client;
    import org.elasticsearch.client.RequestOptions;
     
     
    import org.elasticsearch.client.RestHighLevelClient;
     
     
    //import org.elasticsearch.client.indices.CreateIndexRequest;
    //import org.elasticsearch.client.indices.CreateIndexResponse;
    import org.elasticsearch.common.settings.Settings;
    import org.elasticsearch.common.xcontent.XContentBuilder;
    import org.elasticsearch.common.xcontent.json.JsonXContent;
    import org.junit.Test;
     
    import java.io.IOException;
     
    public class Demo2 {
        String index="person";
        String type="man";
     
    @Test
        public void createIndex() throws IOException {
     
     
            //1.索引的settings
            Settings.Builder settings = Settings.builder()
                    .put("number_of_shards", 3)
                    .put("number_of_replicas", 1);
     
            //2.索引的mappings
            XContentBuilder mappings = JsonXContent.contentBuilder();
                   mappings .startObject()
                    .startObject("properties")
                    .startObject("name")
                        .field("type", "text")
                    .endObject()
                    .startObject("age")
                        .field("type", "integer")
                    .endObject()
                    .startObject("birthday")
                        .field("type", "date")
                        .field("format", "yyyy-MM-dd")
                    .endObject()
            .endObject()
        .endObject();
     
            //将settings和Mappings 封装到一个Request对象
            CreateIndexRequest request = new CreateIndexRequest(index)
                    .settings(settings)
                    .mapping(type, mappings);
            //通过Client对象连接ES并执行创建索引
     
            RestHighLevelClient client = ESClient.getClient();
     
            CreateIndexResponse createIndexResponse =client.indices().create(request,RequestOptions.DEFAULT);
     
            System.out.println("resp:" + createIndexResponse.toString());
     
     
     
        }
    }
    
  5. 查询和删除索引

    @Test
                public  void delete() throws IOException {
            //1.准备request对象
            DeleteIndexRequest request=new DeleteIndexRequest();
            request.indices(index);
            //2.通过Cilent操作
            RestHighLevelClient client = ESClient.getClient();
            AcknowledgedResponse  delete=client.indices().delete(request,RequestOptions.DEFAULT);
            /* 3.输出 */
            System.out.println(delete);
        }
     
     
     
        @Test
        public   void exists() throws IOException {
            //1.准备request对象
            GetIndexRequest request=new GetIndexRequest();
            request.indices(index);
            //2.通过Cilent操作
            RestHighLevelClient client = ESClient.getClient();
           boolean exists= client.indices().exists(request,RequestOptions.DEFAULT);
            //3.输出
            System.out.println(exists);
        }
    
  6. java操作文档

    1. 添加文档

      创建person类

      package com.qf.entity;
      import com.fasterxml.jackson.annotation.JsonFormat;
      import com.fasterxml.jackson.annotation.JsonIgnore;
      import lombok.AllArgsConstructor;
      import lombok.Data;
      import lombok.NoArgsConstructor;
       
      import  java.util.Date;
       
      public class Person {
       
       
          @JsonIgnore
          private  Integer id;
          private String name;
          private  Integer age;
       
          @JsonFormat(pattern = "yyyy-MM-dd")
          private  Date  birthday;
       
          public Person(Integer id, String name, Integer age, Date birthday) {
              this.id = id;
              this.name = name;
              this.age = age;
              this.birthday = birthday;
          }
       
          public Integer getId() {
              return id;
          }
      }
      

      创建测试类

      注:添加json依赖包

      com.fasterxml.jackson.core jackson-databind 2.10.2
      package com.qf.test;
      import com.fasterxml.jackson.core.JsonProcessingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
      import com.qf.entity.Person;
      import com.qf.utils.ESClient;
      import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
      import org.elasticsearch.action.index.IndexRequest;
      import org.elasticsearch.action.index.IndexResponse;
      import org.elasticsearch.client.RequestOptions;
      import org.elasticsearch.client.RestHighLevelClient;
      import org.elasticsearch.common.xcontent.XContentType;
      import org.junit.Test;
      
      import java.io.IOException;
      import java.util.Date;
      
      public class Demo3 {
          String index="person";
          String type="man";
          RestHighLevelClient client = ESClient.getClient();
          ObjectMapper mapper=new ObjectMapper();
      
      @Test
          public void createDoc() throws IOException {
          //1.准备一个json数据
          Person person=new Person(1,"张三",20,new Date());
         String json= mapper.writeValueAsString(person);
          //2.准备一个request对象(手动指定id)
          IndexRequest request=new IndexRequest(index,type,person.getId().toString());
          request.source(json, XContentType.JSON);
          //3.通过client对象执行添加
          IndexResponse resp =client.index(request, RequestOptions.DEFAULT);
      
          //4.输出返回结果
          System.out.println(resp.getResult().toString());
      }
      
      }
      
    2. 修改文档

      @Test
          public void update() throws IOException {
          //创建Map修改指定内容
          Map<String,Object>doc= new HashMap<String, Object>();
          doc.put("name","张大三");
          String docID="1";
       
          UpdateRequest request=new UpdateRequest(index,type,docID);
          request.doc(doc);
          UpdateResponse update=client.update(request,RequestOptions.DEFAULT);
          System.out.println(update.getResult().toString());
      }
      
    3. 删除文档

      @Test
          public void delete() throws IOException {
          DeleteRequest request=new DeleteRequest(index,type,"1");
          DeleteResponse resp=client.delete(request,RequestOptions.DEFAULT);
          System.out.println(resp.getResult().toString());
      }
      
    4. 批量添加文档

      @Test
          public void BulkDoc() throws IOException {
          Person p1= new Person(1,"HJH",20,new Date());
          Person p2= new Person(2,"YQG",30,new Date());
          Person p3= new Person(3,"LWD",22,new Date());
       
         String json1= mapper.writeValueAsString(p1);
         String json2= mapper.writeValueAsString(p2);
         String json3= mapper.writeValueAsString(p3);
       
         //创建Request,将准备好的数据封装进去
          BulkRequest  request=new BulkRequest();
          request.add(new IndexRequest(index,type,p1.getId().toString()).source(json1,XContentType.JSON));
          request.add(new IndexRequest(index,type,p2.getId().toString()).source(json1,XContentType.JSON));
          request.add(new IndexRequest(index,type,p3.getId().toString()).source(json1,XContentType.JSON));
       
          BulkResponse resp=client.bulk(request,RequestOptions.DEFAULT);
       
          System.out.println(resp.toString());
      
       
      }
      
    5. 批量删除文档

      @Test
          public void bulkDeleteDoc() throws IOException {
          BulkRequest  request=new BulkRequest();
          request.add(new DeleteRequest(index,type,"1"));
          request.add(new DeleteRequest(index,type,"2"));
          request.add(new DeleteRequest(index,type,"3"));
          BulkResponse resp=client.bulk(request,RequestOptions.DEFAULT);
      
          System.out.println(resp);
      
      
      }
      
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐