Java集成Elasticsearch基本操作:实现增删改查

依赖

        
        
            org.elasticsearch
            elasticsearch
            7.10.2
        
        
            org.elasticsearch.client
            transport
            7.10.2
        
        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            7.10.2
        
        
            org.apache.logging.log4j
            log4j-api
        
        
            org.apache.logging.log4j
            log4j-core
        

增加连接ex工具类,获取Client

package com.dcx.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

public class ESConfig {
    public static RestHighLevelClient getClient(){
        HttpHost httpHost1 = new HttpHost("192.168.100.24",9201);
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHost1));
        return  client;
    }
}







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

public class EsDemo {  
    //连接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;
    }
}

测试Java是否可以连接到es集群

package com.dcx.util;

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

/**
 * @基本功能: 测试Java连接es
 */
public class TestDemo {
    @Test
    public void testConnect(){
        try {
            RestHighLevelClient client = EsDemo.getClient();
            System.out.println("ok!");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

创建索引、删除索引、查询索引、创建文档、查询文档、修改文档、删除文档

package com.dcx.util;


import com.dcx.config.ESConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
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.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.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class EsTest {

    //数据库
    String index = "good";
    //表
    String type = "default";

    //创建索引
    @Test
    public void createIndex() throws IOException {
        //索引的settings(可不写)
        Settings.Builder settings = Settings.builder()
                .put("number_of_shards", 3)
                .put("number_of_replicas", 1);


        XContentBuilder mappings = JsonXContent.contentBuilder();
        mappings.startObject()
                .startObject("properties")
                .startObject("formId")
                .field("type", "long")
                .endObject()
                .startObject("formName")
                .field("type", "text")
                .endObject()
                .endObject()
                .endObject();

        //将settings和Mappings 封装到一个Request对象
        CreateIndexRequest request = new CreateIndexRequest(index).settings(settings).mapping(type, mappings);
        //通过Client对象连接ES并执行创建索引
        RestHighLevelClient client = ESConfig.getClient();
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("resp:" + createIndexResponse.toString());
    }


    //删除索引
    @Test
    public void delete() throws IOException {
        //1.准备request对象
        DeleteIndexRequest request = new DeleteIndexRequest();
        request.indices(index);
        //2.通过Cilent操作
        RestHighLevelClient client = ESConfig.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();
        // 查询es中有没有person索引
        request.indices(index);
        //2.通过Cilent操作
        RestHighLevelClient client = ESConfig.getClient();
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        //3.输出
        System.out.println(exists);
    }

    //创建文档
    @Test
    public void createDocument() throws IOException {
        
        // 唯一编号
        String id = "1";

        IndexRequest request = new IndexRequest(index, type, id);
        Map jsonMap = new HashMap<>();
        jsonMap.put("formId", 657);
        jsonMap.put("formName", "覆盖到极致");
        request.source(jsonMap);

        //3.通过client对象执行添加
        RestHighLevelClient client = ESConfig.getClient();
        IndexResponse resp = client.index(request, RequestOptions.DEFAULT);
        //4.输出返回结果
        System.out.println(resp.getResult().toString());
    }

    //获取文档内容
    @Test
    public void getDocument() throws IOException {
        RestHighLevelClient client = ESConfig.getClient();
        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);
    }

    //修改
    @Test
    public void updateDocument() throws IOException {
        
        // 唯一编号
        String id = "1";
        UpdateRequest upateRequest = new UpdateRequest(index, type, id);

        // 依旧可以使用Map这种集合作为更新条件
        Map jsonMap = new HashMap<>();
        jsonMap.put("formName", "安师傅");
        upateRequest.doc(jsonMap);

        RestHighLevelClient client = ESConfig.getClient();
        UpdateResponse update = client.update(upateRequest, RequestOptions.DEFAULT);
        System.out.println(update.getResult().toString());

    }

    //删除文档
    @Test
    public void deleteDocument() throws IOException {
        RestHighLevelClient client = ESConfig.getClient();
        String id = "1";
        DeleteRequest request = new DeleteRequest("good2", type, id);
        DeleteResponse resp = client.delete(request, RequestOptions.DEFAULT);
        log.info("good2",type,id,resp.getResult().toString());
    }


}




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