springboot对es的增删改查细节

梦想不抛弃苦心追求的人,只要不停止追求,你们会沐浴在梦想的光辉之中。再美好的梦想与目标,再完美的计划和方案,如果不能尽快在行动中落实,最终只能是纸上谈兵,空想一番。只要瞄准了大方向,坚持不懈地做下去,才能够扫除挡在梦想前面的障碍,实现美好的人生蓝图。springboot对es的增删改查细节,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

版本约定

  • 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.RELEASE</springboot.version>
    <elasticsearch.version>7.6.2</elasticsearch.version>
</properties>

<dependencyManagement>
	<dependencies>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${springboot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>transport-netty4-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>${elasticsearch.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
	</dependencies>
</dependencyManagement>

子文件

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-elasticsearch</artifactId>
    <version>3.2.5.RELEASE</version>
</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;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/153505.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!