irpas技术客

Springboot整合Elasticsearch_$驽马十驾$_springboot整合elasticsearch

网络 7921

Springboot整合Elasticsearch 新建Springboot项目xml文件添加依赖添加配置新建配置类创建实体类Dao层代码测试代码自定义查询

新建Springboot项目

此步骤不再赘述

xml文件添加依赖

第一步当然是添加依赖了,本次测试主要使用了以下三个依赖:

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.7</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.wpp</groupId> <artifactId>springdata_es</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springdata_es</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 添加配置

第二步自然是在yml配置文件中添加elasticsearch的信息,如下:

# es 服务地址 elasticsearch: host: localhost # es 服务端口 port: 9200 新建配置类

第三步,涉及到Springboot整合的往往离不开配置类,如下配置,在启动项目的时候就实例化了elasticsearch的客户端:

package com.wpp.springdata_es.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration; /** * @Author wpp * @Date 2022/04/27/10:30 * @Description */ public class ElasticsearchConfig extends AbstractElasticsearchConfiguration { //对应yml文件中的配置 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; } } 创建实体类

第四步,下面就是我们要操作的实体类了,类似于MyBatis-Plus,针对elasticsearch也有自己的注解:

package com.wpp.springdata_es.esentity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; /** * @Author wpp * @Date 2022/04/27/10:35 * @Description */ @Data @NoArgsConstructor @AllArgsConstructor @ToString @Document(indexName = "product",shards = 2,replicas = 1) public class Product { //必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id" @Id private Long id;//商品唯一ID /** * type:字段数据类型 * index:是否索引(默认:true) * Keyword:短语,不进行分词 */ @Field(type = FieldType.Text) 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 images;//图片地址 } Dao层代码

同样类似于Mybatis-Plus,我们也有自己的interface,并且继承于ElasticsearchRepository,这样就像MyBatis-Plus一样已经提供了很多的用于操作的Api。

package com.wpp.springdata_es.dao; import com.wpp.springdata_es.esentity.Product; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * @Author wpp * @Date 2022/04/27/10:33 * @Description */ public interface ProductDao extends ElasticsearchRepository<Product,Long> { } 测试代码

接下来操作对象就是操作索引了。

package com.wpp.springdata_es; import com.wpp.springdata_es.dao.ProductDao; import com.wpp.springdata_es.esentity.Product; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; @SpringBootTest class SpringdataEsApplicationTests { @Autowired private ElasticsearchRestTemplate elasticsearchRestTemplate; @Autowired private ProductDao productDao; //创建索引 @Test void createIndex() { //创建索引,系统初始化会自动创建索引 System.out.println("创建索引"); } //删除索引 @Test void deleteIndex() { boolean delete = elasticsearchRestTemplate.indexOps(Product.class).delete(); System.out.println("删除索引:" + delete); } //新增文档 @Test void save() { Product product = new Product(); product.setId(1L); product.setTitle("华为笔记本"); product.setCategory("电脑"); product.setPrice(3980.0); product.setImages("http://www.baidu/hw.jpg"); Product save = productDao.save(product); } } 自定义查询

ElasticsearchRepository虽然为我们提供了一些方法,但是我们依然可以根据约定进行自定义方法 例如:

package com.wpp.springdata_es.dao; import com.wpp.springdata_es.esentity.Product; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; /** * @Author wpp * @Date 2022/04/27/10:33 * @Description */ public interface ProductDao extends ElasticsearchRepository<Product,Long> { //自定义查询 List<Product> findByPriceBetweenOrderByPrice(double price1, double price2); }

测试代码如下:

//自定义 查询 @Test public void test(){ List<Product> products = productDao.findByPriceBetweenOrderByPrice(2000, 2005); for (Product product1 : products) { System.out.println(product1); } }

更多的自定义方法命名约定

KeywordSampleElasticsearch Query StringAndfindByNameAndPrice{“bool” : {“must” : [ {“field” : {“name” : “?”}}, {“field” : {“price” : “?”}} ]}}OrfindByNameOrPrice{“bool” : {“should” : [ {“field” : {“name” : “?”}}, {“field” : {“price” : “?”}} ]}}IsfindByName{“bool” : {“must” : {“field” : {“name” : “?”}}}}NotfindByNameNot{“bool” : {“must_not” : {“field” : {“name” : “?”}}}}BetweenfindByPriceBetween{“bool” : {“must” : {“range” : {“price” : {“from” : ?,“to” : ?,“include_lower” : true,“include_upper” : true}}}}}LessThanEqualfindByPriceLessThan{“bool” : {“must” : {“range” : {“price” : {“from” : null,“to” : ?,“include_lower” : true,“include_upper” : true}}}}}GreaterThanEqualfindByPriceGreaterThan{“bool” : {“must” : {“range” : {“price” : {“from” : ?,“to” : null,“include_lower” : true,“include_upper” : true}}}}}BeforefindByPriceBefore{“bool” : {“must” : {“range” : {“price” : {“from” : null,“to” : ?,“include_lower” : true,“include_upper” : true}}}}}AfterfindByPriceAfter{“bool” : {“must” : {“range” : {“price” : {“from” : ?,“to” : null,“include_lower” : true,“include_upper” : true}}}}}LikefindByNameLike{“bool” : {“must” : {“field” : {“name” : {“query” : “?*”,“analyze_wildcard” : true}}}}}StartingWithfindByNameStartingWith{“bool” : {“must” : {“field” : {“name” : {“query” : “?*”,“analyze_wildcard” : true}}}}}EndingWithfindByNameEndingWith{“bool” : {“must” : {“field” : {“name” : {“query” : “*?”,“analyze_wildcard” : true}}}}}Contains/ContainingfindByNameContaining{“bool” : {“must” : {“field” : {“name” : {“query” : “?”,“analyze_wildcard” : true}}}}}InfindByNameIn(Collectionnames){“bool” : {“must” : {“bool” : {“should” : [ {“field” : {“name” : “?”}}, {“field” : {“name” : “?”}} ]}}}}NotInfindByNameNotIn(Collectionnames){“bool” : {“must_not” : {“bool” : {“should” : {“field” : {“name” : “?”}}}}}}NearfindByStoreNearNot Supported Yet !TruefindByAvailableTrue{“bool” : {“must” : {“field” : {“available” : true}}}}FalsefindByAvailableFalse{“bool” : {“must” : {“field” : {“available” : false}}}}OrderByfindByAvailableTrueOrderByNameDesc{“sort” : [{ “name” : {“order” : “desc”} }],“bool” : {“must” : {“field” : {“available” : true}}}}


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。