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

依赖

        <!-- ES -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.10.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>7.10.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.10.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
        </dependency>

增加连接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<String, Object> 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<String, Object> 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());
    }


}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是Spring集成Elasticsearch实现增删改查的示例代码: 1. 添加依赖 在`pom.xml`中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置Elasticsearch连接信息 在`application.yml`中添加以下配置信息: ```yaml spring: data: elasticsearch: cluster-nodes: localhost:9300 ``` 3. 定义实体类 定义一个实体类,如下所示: ```java @Document(indexName = "my_index", type = "my_type") public class MyEntity { @Id private String id; private String name; private Integer age; // 省略getter/setter方法 } ``` 4. 定义Repository 定义一个Repository接口,继承`ElasticsearchRepository`,如下所示: ```java public interface MyEntityRepository extends ElasticsearchRepository<MyEntity, String> { } ``` 5. 实现增删改查操作 在Service层中注入`MyEntityRepository`,并实现相应的增删改查操作,如下所示: ```java @Service public class MyEntityService { @Autowired private MyEntityRepository repository; public void save(MyEntity entity) { repository.save(entity); } public void delete(String id) { repository.deleteById(id); } public void update(MyEntity entity) { repository.save(entity); } public List<MyEntity> search(String name) { NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); builder.withQuery(QueryBuilders.matchQuery("name", name)); Iterable<MyEntity> searchResult = repository.search(builder.build()); List<MyEntity> result = new ArrayList<>(); searchResult.forEach(result::add); return result; } } ``` 这里实现了四个方法: - `save`:新增或更新数据 - `delete`:删除数据 - `update`:更新数据 - `search`:根据名称查询数据 以上就是Spring集成Elasticsearch实现增删改查的示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值