Java操作ElasticSearch(完整)

1、maven项目 ,添加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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>esJava</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- 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.11.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>

2、连接es工具类,获取client

package com.hdit.es;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;

/**
 * @基本功能: 获取client对象
 * @ClassName: EsDemo
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/11 9:02
 * @Version 1.0
 */
public class EsDemo {
    
     
//  第一种连接es方式(简洁些)
    public static void main(String[] args) throws IOException {
    
    
//        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
//                new HttpHost("192.168.184.128",9200,"http"),
//                new HttpHost("192.168.184.128",9201,"http"),
//                new HttpHost("192.168.184.128",9202,"http")
//        ));
//        RestHighLevelClient client = EsDemo.getClient();
//        return  client;
    }
    
    
//  第二种连接es方式(分开写)
    public static RestHighLevelClient getClient(){
    
    
        HttpHost httpHost1 = new HttpHost("192.168.184.128",9200);
        HttpHost httpHost2 = new HttpHost("192.168.184.128",9201);
        HttpHost httpHost3 = new HttpHost("192.168.184.128",9202);
        RestClientBuilder clientBuilder = RestClient.builder(httpHost1,httpHost2,httpHost3);
        RestHighLevelClient client = new RestHighLevelClient(clientBuilder);
        return  client;
    }
}

3、测试工具类,测试Java是否可以连接到es集群

package com.hdit.es;

import org.elasticsearch.client.RestHighLevelClient;
import org.junit.Test;

/**
 * @基本功能: 测试Java连接es
 * @ClassName: TestDemo
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/11 20:34
 * @Version 1.0
 */
public class TestDemo {
    
    
    @Test
    public void testConnect(){
    
    
        try {
    
    
            RestHighLevelClient client = EsDemo.getClient();
            System.out.println("ok!");
        } catch (Exception e) {
    
    
            System.out.println(e);
        }
    }
}

4、创建索引、删除索引、查询索引

package com.hdit.es;

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.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
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;

/**
 * @基本功能: java操作es----索引
 * @ClassName: createIndex
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/11 20:36
 * @Version 1.0
 */
public class TestIndex {
    
    
    String index="person";
    String type="man";
    
    //4.1 创建索引
    @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 = EsDemo.getClient();
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("resp:" + createIndexResponse.toString());
}
    //4.2 Java删除索引
    @Test
    public  void delete() throws IOException {
    
    
        //1.准备request对象
        DeleteIndexRequest request=new DeleteIndexRequest();
        request.indices(index);
        //2.通过Cilent操作
        RestHighLevelClient client = EsDemo.getClient();
        AcknowledgedResponse delete=client.indices().delete(request,RequestOptions.DEFAULT);
        /* 3.输出 */
        System.out.println(delete);
    }
    
   //4.3 Java查询索引
    @Test
    public   void exists() throws IOException {
    
    
        //1.准备request对象
        GetIndexRequest request=new GetIndexRequest();
        // 查询es中有没有person索引
        request.indices(index);
        //2.通过Cilent操作
        RestHighLevelClient client = EsDemo.getClient();
        boolean exists= client.indices().exists(request,RequestOptions.DEFAULT);
        //3.输出
        System.out.println(exists);
    }
}

5、创建文档(类似数据库表中添加一行数据)、查询文档、修改文档、删除文档、批量添加文档、批量删除文档

package com.hdit.es;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
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;
import java.util.HashMap;
import java.util.Map;

/**
 * @基本功能: es文档操作
 * @ClassName: TestOperation
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/11 20:57
 * @Version 1.0
 */
public class TestOperation {
    
    
    String index = "person";
    String type = "man";
    RestHighLevelClient client = EsDemo.getClient();
    ObjectMapper mapper = new ObjectMapper();
    
    //5.1 创建文档
    @Test
    public void createDoc() throws IOException {
    
    
        //1.准备一个json数据
        Person p =new Person(1,"张三",18,new Date());
        String json = mapper.writeValueAsString(p);
        //2.准备一个request对象(手动指定id)
        IndexRequest request = new IndexRequest(index,type,p.getId().toString());
        request.source(json, XContentType.JSON);
        //3.通过client对象执行添加
        IndexResponse resp = client.index(request, RequestOptions.DEFAULT);
        //4.输出返回结果
        System.out.println(resp.getResult().toString());
    }

    //5.2 获取文档内容
    @Test
    public void testGetDocument() throws IOException {
    
    
        GetRequest request = new GetRequest(index, "1");
        GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
        // 打印文档内容
        System.out.println(getResponse.getSourceAsString());
        // 打印结果集合
        System.out.println(getResponse.getSource().entrySet());
        // 打印结果对象
        System.out.println(getResponse);
    }

    //5.3 根据id修改文档指定内容
    @Test
    public void update() throws IOException {
    
    
        //创建Map修改指定内容
        Map<String,Object> doc= new HashMap<String, Object>();
        doc.put("name","张大三");
        String docID="1";
        // 修改id为1的文档信息
        UpdateRequest request=new UpdateRequest(index,type,docID);
        request.doc(doc);
        UpdateResponse update=client.update(request,RequestOptions.DEFAULT);
        System.out.println(update.getResult().toString());
    }
    
    //5.4 删除文档
    @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());
    }
    
    //5.5 批量添加文档
    @Test
    public void BulkDoc() throws IOException {
    
    
        // 创建3个需要添加的对象
        Person p1= new Person(1,"张三",30,new Date());
        Person p2= new Person(2,"李四",40,new Date());
        Person p3= new Person(3,"马五",50,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(json2,XContentType.JSON));
        request.add(new IndexRequest(index,type,p3.getId().toString()).source(json3,XContentType.JSON));
        BulkResponse resp=client.bulk(request,RequestOptions.DEFAULT);
        System.out.println(resp.toString());
    }
    
    //5.6 批量删除文档
    @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);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43605266/article/details/114680663