首页 > 其他分享 >SpringBoot整合ElasticSearch-SpringData

SpringBoot整合ElasticSearch-SpringData

时间:2022-12-01 17:32:48浏览次数:43  
标签:product SpringBoot void Product ElasticSearch Test elasticsearch public SpringDa

前言

之前写过一篇SpringBoot整合ElasticSearch是使用的elasticsearch-rest-high-level-client,这篇文章使用Spring-Data来操作ElasticSearch。关于ElasticSearch的搭建我这里都不想提了,往期文章都有,各种版本的!这里Spring-Data就是为了简化数据操作的,对于ElasticSearch中的所有,数据都可以转换成对象的操作!

前置环境

POM

	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

注意不同版本的parent具体操作的API不同,2.3.6.RELEAS,使用的ElasticSearch为7.4.2

实体类

/**
 * @author TAO
 * @description: 实体类和索引的Mapping
 * @date 2021/8/28 18:27
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(indexName = "product", shards = 3, replicas = 1)
public class Product {


    @Id
    private Long id;

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String title;

    @Field(type = FieldType.Keyword)/*不能分词*/
    private String category;

    @Field(type = FieldType.Double)
    private Double price;

    @Field(type = FieldType.Keyword, index = false)/*不能分词*/
    private String image;

}

ElasticSearch配置类


/**
* @description: Spring-Data-ElasticSearch
* @author TAO
* @date 2021/8/28 18:43
*/

@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
@Data
public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {

    private String host;

    private Integer port;

    @Override
    public RestHighLevelClient elasticsearchClient() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(host,port));
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
        return restHighLevelClient;
    }
}

ElasticsearchRepository

import com.tao.es.estest.entity.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProduceDao extends ElasticsearchRepository<Product,Long> {
}

启动类

@EnableElasticsearchRepositories(basePackages = "com.tao.es.estest.dao")

properties配置

#es服务器地址
elasticsearch.host=192.168.1.12
elasticsearch.port=9200


索引测试


@Slf4j
@SpringBootTest
class EsTestSpringData {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Test
    public void createIndex(){
        log.info("创建索引");
    }


    @Test
    public void deleteIndex(){
        boolean b = elasticsearchRestTemplate.deleteIndex(Product.class);
        log.info("删除===>{}",b);
    }

}

SpringBoot整合ElasticSearch-SpringData_elasticsearch

文档测试

	//保存
    @Test
    public void save(){
        Product product = new Product().setId(1L).setTitle("华为手机天下第一").setCategory("手机").setPrice(9999.99).setImage("http://baidu.com/image.png");
        produceDao.save(product);
    }

SpringBoot整合ElasticSearch-SpringData_elasticsearch_02

   //更新
    @Test
    public void update(){
        Product product = new Product().setId(1L).setTitle("华为手机天下第一,非常牛逼").setCategory("手机").setPrice(9999.99).setImage("http://baidu.com/image.png");
        produceDao.save(product);
    }

SpringBoot整合ElasticSearch-SpringData_elasticsearch_03

 	//根据id查询数据
    @Test
    public void findById(){
        Product product = produceDao.findById(1L).get();
        log.info("product===>{}",product);
    }

SpringBoot整合ElasticSearch-SpringData_数据_04

	 //查询所有
    /**
     * findAll此API对elasticsearch-rest-high-level-client的版本有要求,
     * 如果POM中还单独引用了elasticsearch-rest-high-level-client并指定了其他版本可能会不兼容
     * 这里elasticsearch-rest-high-level-client版本为7.6.2时下面API是可以运行的
     */
    @Test
    public void findAll(){
        Iterable<Product> all = produceDao.findAll();

        for (Product product:all){
            log.info("product===>{}",product);
        }

    }

SpringBoot整合ElasticSearch-SpringData_数据_05
SpringBoot整合ElasticSearch-SpringData_其他_06
说明一下,我个项目并不是一个干净的Spring-Data整合ElasticSearch的项目,而是之前整合elasticsearch-rest-high-level-client的时候使用的,这里也能反映一点Spring-Data整合ElasticSearch,实际上通过Maven依赖可以看出底层还是使用的是elasticsearch-rest-high-level-client来操作ELasticSearch的,只不过又在elasticsearch-rest-high-level-client的基础上封装了一层,其实我本人是不喜欢使用过度封装的东西,比较喜欢使用elasticsearch-rest-high-level-client更加灵活,就如操作Redis我比较喜欢使用jedis来操作!

	//根据id删除数据
    @Test
    public void deleteById(){
        Product product = new Product().setId(1L);
        produceDao.delete(product);
    }

SpringBoot整合ElasticSearch-SpringData_数据_07

  //批量保存
    @Test
    public void batchSave(){
        List<Product> productList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Product product = new Product().setId(Long.valueOf(i)).setTitle("华为手机天下第一"+i).setCategory("手机").setPrice(9999.99*i).setImage("http://baidu.com/image.png");
            productList.add(product);
        }
        produceDao.saveAll(productList);
    }

SpringBoot整合ElasticSearch-SpringData_其他_08

	//分页查询
    @Test
    public void pageQuery(){

        //构建排序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");

        int from = 0;
        int size = 5;

        //设置查询分页
        PageRequest pageRequest = PageRequest.of(from, size,sort);


        Page<Product> all = produceDao.findAll(pageRequest);
        for (Product product:all){
            log.info("product===>{}",product);
        }

    }

SpringBoot整合ElasticSearch-SpringData_数据_09

	 //term查询
    @Test
    public void termQuery(){
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
        Iterable<Product> all = produceDao.search(termQueryBuilder);
        for (Product product:all){
            log.info("product===>{}",product);
        }
    }
	//term分页查询
    @Test
    public void termPageQuery(){

        int from = 0;
        int size = 5;

        //设置查询分页
        PageRequest pageRequest = PageRequest.of(from, size);


        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
        Iterable<Product> all = produceDao.search(termQueryBuilder,pageRequest);
        for (Product product:all){
            log.info("product===>{}",product);
        }
    }

标签:product,SpringBoot,void,Product,ElasticSearch,Test,elasticsearch,public,SpringDa
From: https://blog.51cto.com/u_15899048/5903413

相关文章

  • ElasticSearch集群概念
    单机存在的问题单台Elasticsearch服务器提供服务,往往都有最大的负载能力,超过这个阈值,服务器性能就会大大降低甚至不可用,所以生产环境中,一般都是运行在指定服务器集......
  • Windows安装ElasticSearch
    前言习惯使用docker安装各种中间件了,但是程序包安装方式也不能丢呀。官网下载地址,我这里使用的是7.4.2,如果需要使用其他版本,更改连接后面的版本号即可!下载下载速度还......
  • ElasticSearch集群系统架构
    前言全面几篇文章主要是使用单机跑ElasticSearch的,在生产环境为了保证高可用和高吞吐量我们都会采用集群的方式部署。那么本章不涉及ElasticSearch集群的搭建,只涉及理论......
  • Windows搭建ElasticSearch集群
    前言在搭建ElasticSearch集群前,可以先看看往期文章Windows安装ElasticSearch,可以使用上篇文章中下载ElasticSearch搭建准备将下载好的ElasticSearch复制三分,node1为......
  • springboot启动报错:Failed to start bean ‘documentationPluginsBootstrapper‘
    今天启动时,突然报了这个错误,网上查了下是springboot版本和swagger版本之间的问题,解决办法如下:原因:这是因为Springfox使用的路径匹配是基于AntPathMatcher的,而SpringBoot......
  • 搜索引擎之Lucene,Solr,ElasticSearch比较
    目录1搜索引擎1.1简介1.2结构化数据和非结构化数据1.3使用全文搜索引擎条件2Lucene,Solr,ElasticSearch2.1Lucene2.2Solr2.3ElasticSearch2.4区别和选择2.4.1如何......
  • SpringBoot(六) - 阿里巴巴的EasyExcel
    1、依赖<!--阿里EasyExcelstart--><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.1.7</version></depe......
  • SpringBoot(七) - Redis 缓存
    1、五大基本数据类型和操作1.1字符串-string命令说明setkeyvalue如果key还没有,那就可以添加,如果key已经存在了,那会覆盖原有key的值getkey如果key还没有,......
  • SpringBoot(九) - Swagger
    1、依赖<!--swagger核心--><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.8.0</version></......
  • vscode+springboot+gradle
    vscode+springboot+gradle项目搭建demo目标:项目中抛弃所有xml格式文件啰嗦:  一直在用maven作为项目的依赖包管理,最近看到基于Java17的Springframwork6......