springboot对es的增删改查细节

文章目录

  • 版本约定
  • POM文件
    • 父文件
    • 子文件
  • yaml配置
  • restHighLevelClient配置
  • 分页查询实体类
  • 工具类
    • 新增数据
    • 删除索引
    • 查询(根据ID精确批量查询/模糊查询/分页查询)

版本约定

  • springboot 2.1.6.RELEASE
  • spring-data-elasticsearch 3.2.5.RELEASE
  • elasticsearch-rest-high-level-client 7.6.2

POM文件

父文件

<properties>
    <springboot.version>2.1.6.RELEASEspringboot.version>
    <elasticsearch.version>7.6.2elasticsearch.version>
properties>

<dependencyManagement>
	<dependencies>
		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-dependenciesartifactId>
            <version>${springboot.version}version>
            <type>pomtype>
            <scope>importscope>
        dependency>
        <dependency>
            <groupId>org.elasticsearchgroupId>
            <artifactId>elasticsearchartifactId>
            <version>${elasticsearch.version}version>
        dependency>
        <dependency>
            <groupId>org.elasticsearch.clientgroupId>
            <artifactId>transportartifactId>
            <version>${elasticsearch.version}version>
        dependency>
        <dependency>
            <groupId>org.elasticsearch.plugingroupId>
            <artifactId>transport-netty4-clientartifactId>
            <version>${elasticsearch.version}version>
        dependency>
        <dependency>
            <groupId>org.elasticsearch.clientgroupId>
            <artifactId>elasticsearch-rest-clientartifactId>
            <version>${elasticsearch.version}version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-loggingartifactId>
                    <groupId>commons-logginggroupId>
                exclusion>
            exclusions>
        dependency>
        <dependency>
            <groupId>org.elasticsearch.clientgroupId>
            <artifactId>elasticsearch-rest-high-level-clientartifactId>
            <version>${elasticsearch.version}version>
        dependency>
	dependencies>
dependencyManagement>

子文件

<dependency>
    <groupId>org.springframework.datagroupId>
    <artifactId>spring-data-elasticsearchartifactId>
    <version>3.2.5.RELEASEversion>
dependency>

yaml配置

es:
  host: {your host}
  port: {your port}
  index:
    yourIndex: {yourIndex}

restHighLevelClient配置

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Desc
 **/
@Configuration
public class EsConfig {

    @Value("${es.host}")
    private String esHost;
    @Value("${es.port}")
    private int esPort;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(RestClient.builder(new HttpHost(esHost, esPort, "http")));
    }
}

分页查询实体类

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * @Desc
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class EsOriginVo {

    List<String> list;
    long total;
}

工具类

新增数据

@Service
public class EsServiceForSave {
	@Resource
    private RestHighLevelClient restHighLevelClient;

	/**
     * 存储数据,若索引不存在则创建索引
     *
     * @param key 数据键
     * @param jsonContent json类型的数据
     * @param index 索引
     * @return
     */
	public void saveRepeat(String jsonContent, String key, String index) throws IOException {
        if (!restHighLevelClient.indices().exists(new GetIndexRequest(index), RequestOptions.DEFAULT)) {
            restHighLevelClient.indices().create(new CreateIndexRequest(index), RequestOptions.DEFAULT);
        }
        IndexRequest docAdd = new IndexRequest(index);
        docAdd.id(key);
        docAdd.timeout(TimeValue.timeValueSeconds(5));
        docAdd.source(jsonContent, XContentType.JSON);
        IndexResponse response = restHighLevelClient.index(docAdd, RequestOptions.DEFAULT);
        log.info("向es写入引擎处理后的数据状态:{}", response.status());
    }

}

删除索引

@Service
public class EsServiceForDel {
	@Resource
    private RestHighLevelClient restHighLevelClient;

	@Value("${es.index.yourIndex}")
	private String yourIndex;

	public void delete() {
        DeleteIndexRequest yourIndexDel = new DeleteIndexRequest(yourIndex);
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(yourIndexDel, RequestOptions.DEFAULT);
	}

}

查询(根据ID精确批量查询/模糊查询/分页查询)

@Service
public class EsServiceForSearch {

	@Resource
    private RestHighLevelClient restHighLevelClient;

	@Value("${es.index.yourIndex}")
	private String yourIndex;

	/**
     * 批查询
     *
     * @param key
     * @return
     */
	public List<String> searchByKey(List<String> key) {
		return search(yourIndex, key);
	}

	/**
     * 模糊+分页查询
     *
     * @param word 关键字
     * @param start 开始位置
	 * @param size 查询规模
     * @return
     */
	public EsOriginVo searchByWord(String word, int start, int size) {
		return search(yourIndex, word, start, size);
	}
	
	private EsOriginVo search(String type, String keyWord, int start, int size) {
		SearchRequest searchRequest = new SearchRequest(yourIndex);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // prop1和prop2表示keyWord至少出现在其中一个字段,prop有多少都行,但是必须是索引里存在的字段
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(keyWord, "prop1", "prop2");
        searchSourceBuilder.query(multiMatchQueryBuilder);
        searchSourceBuilder.from(start);
        searchSourceBuilder.size(size);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("查询es失败,原因为:", e);
        }
        assert response != null;
        SearchHit[] hits = response.getHits().getHits();
        ArrayList<String> strings = new ArrayList<>();
        // 以字符串的形式读取数据
        for (SearchHit searchHit : hits) {
            strings.add(searchHit.getSourceAsString());
        }
        // 总数
        CountRequest countRequest = new CountRequest();
        countRequest.indices(getOriginIndex(type));
        countRequest.query(multiMatchQueryBuilder);
        CountResponse countResponse = null;
        try {
            countResponse = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("查询总数失败:", e);
        }
        assert countResponse != null;
        long total = countResponse.getCount();
        return EsOriginVo.builder().list(strings).total(total).build();
	}

	private List<String> search(String type, List<String> keys) {
        keys = handleKeys(keys);
        MultiGetRequest multiGetRequest = new MultiGetRequest();
        keys.forEach(e -> multiGetRequest.add(new MultiGetRequest.Item(type, e)));
        MultiGetItemResponse[] responses = null;
        try {
            responses = restHighLevelClient.mget(multiGetRequest, RequestOptions.DEFAULT).getResponses();
        } catch (Exception e) {
            log.error("查询es失败:", e);
        }
        if (responses == null) {
            return null;
        }
        ArrayList<String> strings = new ArrayList<>();
        for (MultiGetItemResponse e : responses) {
            if (e != null && e.getResponse() != null) {
                strings.add(e.getResponse().getSourceAsString());
            }
        }
        return strings;
    }
}

你可能感兴趣的:(springboot,Java,elasticsearch,spring,boot,java)