ElasticSearch增删改查(Java代码版-高版本-API)

ElasticSearch增删改查(Java代码版-高版本-API),第1张

介绍:本次使用的是ES的高版本进行整合Java

描述: 使用的是 7.17.3版本,进行配置ES集群,以及常用的crud方法进行整合为工具类,方便调用

①导入JAR
	<!--elasticsearch配置包-->
		<dependency>
			<groupId>co.elastic.clients</groupId>
			<artifactId>elasticsearch-java</artifactId>
			<version>7.17.3</version>
		</dependency>
		<dependency>
			<groupId>jakarta.json</groupId>
			<artifactId>jakarta.json-api</artifactId>
			<version>2.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.13</version>
		</dependency>
		<!--elasticsearch配置完成-->
②配置yml
#elasticsearch地址配置,多个地址用逗号隔开
elasticsearch:
  hosts:  10.1.5.132:9200,10.1.5.133:9200,10.1.5.100:9200
③编写config


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @author ***
 * @date 2022/5/5 13:44
 */
@ConfigurationProperties(prefix = "elasticsearch")//配置配置信息的前缀
@Configuration
public class ElasticSearchClientConfig {
    /**
     * 多个IP逗号隔开
     */
    private String hosts;
    /**
    *需要密码的话在配置文件编写
    */
	private String username;

    private String password;

    @Bean
    public ElasticsearchClient restClient() {
        HttpHost[] httpHosts = toHttpHost();
	    //不需要密码的方式
        RestClient restClient = RestClient.builder(httpHosts).build();
        //需要密码的方式
         credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        RestClient restClient = RestClient.builder(httpHosts).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                        return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                })
                .build();
                
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }


    /**
     * 解析hosts
     *
     * @return
     */
    private HttpHost[] toHttpHost() {
        if (!StringUtils.hasLength(hosts)) {
            throw new RuntimeException("elasticsearch.hosts不能为空!");
        }
        String[] hostArray = hosts.split(",");
        HttpHost[] httpHosts = new HttpHost[hostArray.length];
        HttpHost httpHost;
        for (int i = 0; i < hostArray.length; i++) {
            String[] strings = hostArray[i].split(":");
            httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "http");
            httpHosts[i] = httpHost;
        }

        return httpHosts;
    }


    public String getHosts() {
        return hosts;
    }

    public void setHosts(String hosts) {
        this.hosts = hosts;
    }
}

④写一个工具类

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.micro.core.enums.CoreConstant;
import com.micro.core.exceptions.ValidateException;
import com.micro.serv.product.model.vo.req.SalKnowledgeAnswerReqVO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ***
 * @date 2022/5/5 16:37
 * ES查询工具
 */
@Component
public class ElasticSearchUtil {
    @Resource
    ElasticsearchClient elasticsearchClient;

    /**
     * 增加索引
     *
     * @param indexName
     * @throws IOException
     */
    public void create(String indexName) throws Exception {
        //写法比RestHighLevelClient更加简洁
        CreateIndexResponse indexResponse = elasticsearchClient.indices().create(c -> c.index(indexName));
        if (!indexResponse.acknowledged()) {
            throw new ValidateException(CoreConstant.TRANS_STATUS__FAILED, "ES增加索引" + indexName + "失败");
        }
    }

    /**
     * 查询索引
     */
    public void query(String indexName) throws IOException {
        GetIndexResponse getIndexResponse = elasticsearchClient.indices().get(i -> i.index(indexName));
        System.out.println(getIndexResponse.toString());
    }

    /**
     * 判断索引是否存在
     */
    public void exists(String indexName) throws Exception {
        BooleanResponse booleanResponse = elasticsearchClient.indices().exists(e -> e.index(indexName));
        if (!booleanResponse.value()) {
            throw new ValidateException(CoreConstant.TRANS_STATUS__FAILED, indexName + "索引不存在");
        }
    }

    /**
     * 删除索引
     */
    public void delete(String indexName) throws Exception {
        DeleteIndexResponse deleteIndexResponse = elasticsearchClient.indices().delete(d -> d.index(indexName));
        if (!deleteIndexResponse.acknowledged()) {
            throw new ValidateException(CoreConstant.TRANS_STATUS__FAILED, "删除索引" + indexName + "失败");
        }
    }

    /**
     * 判断索引是否存在,不存在则创建
     */
    public void exitsOrSave(String indexName) throws Exception {
        BooleanResponse booleanResponse = elasticsearchClient.indices().exists(e -> e.index(indexName));
        if (!booleanResponse.value()) {
            create(indexName);
        }
    }

    /**
     * 判断索引是否存在,存在则删除
     */
    public void exitsOrDelete(String indexName) throws Exception {
        BooleanResponse booleanResponse = elasticsearchClient.indices().exists(e -> e.index(indexName));
        if (booleanResponse.value()) {
            delete(indexName);
        }
    }

    /**
     * 插入文档
     */
    public void addDocument(SalKnowledgeAnswerReqVO reqVo) throws Exception {
        //判断索引是否存在
        String indexName = reqVo.getIndexName();
        exitsOrSave(indexName);
        IndexResponse indexResponse = elasticsearchClient.index(i -> i
                .index(indexName)
                //设置id
                .id(reqVo.getKnowledgeId().toString())
                //传入user对象
                .document(reqVo));
    }

    /**
     * 更新文档
     */
    public void updateDocument(SalKnowledgeAnswerReqVO reqVo) throws Exception {
        UpdateResponse<SalKnowledgeAnswerReqVO> updateResponse = elasticsearchClient.update(u -> u
                        .index(reqVo.getIndexName())
                        .id(reqVo.getKnowledgeId().toString())
                        .doc(reqVo)
                , SalKnowledgeAnswerReqVO.class);
    }
    /**
     * 根据问题id查询文档
     */
    public SalKnowledgeAnswerReqVO getDocument(SalKnowledgeAnswerReqVO reqVo) throws IOException {
        GetResponse<SalKnowledgeAnswerReqVO> getResponse = elasticsearchClient.get(g -> g
                        .index(reqVo.getIndexName())
                        .id(reqVo.getKnowledgeId().toString())
                , SalKnowledgeAnswerReqVO.class
        );
        return getResponse.source();
    }

    /**
     * 根据问题id删除文档
     */
    public void deleteDocument(String indexName,String id) throws IOException {
        DeleteResponse deleteResponse = elasticsearchClient.delete(d -> d
                .index(indexName)
                .id(id)
        );
        System.out.println(deleteResponse.id());
    }

    /**
     * 分页查询
     */
    public SalKnowledgeAnswerReqVO search(SalKnowledgeAnswerReqVO reqVo) throws IOException {
        SearchResponse<SalKnowledgeAnswerReqVO> search = elasticsearchClient.search(s -> s
                .index(reqVo.getIndexName())
                //查询name字段包含hello的document(不使用分词器精确查找)
                .query(q -> q
                        .term(t -> t
                                .field("name")
                                .value(v -> v.stringValue("hello"))
                        ))
                //分页查询,从第0页开始查询3个document
                .from(0)
                .size(3)
                //按age降序排序
                .sort(f->f.field(o->o.field("age").order(SortOrder.Desc))),SalKnowledgeAnswerReqVO.class
        );
        for (Hit<SalKnowledgeAnswerReqVO> hit : search.hits().hits()) {
            System.out.println(hit.source());
        }
        return null;
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/883670.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存