- 新建Springboot项目
- xml文件添加依赖
- 添加配置
- 新建配置类
- 创建实体类
- Dao层代码
- 测试代码
- 自定义查询
此步骤不再赘述
xml文件添加依赖第一步当然是添加依赖了,本次测试主要使用了以下三个依赖:
添加配置4.0.0 org.springframework.boot spring-boot-starter-parent 2.6.7 com.wpp springdata_es 0.0.1-SNAPSHOT springdata_es Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-test test org.projectlombok lombok org.springframework.boot spring-boot-starter-data-elasticsearch org.springframework.boot spring-boot-maven-plugin
第二步自然是在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;
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;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(indexName = "product",shards = 2,replicas = 1)
public class Product {
//必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id"
@Id
private Long id;//商品唯一ID
@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; public interface ProductDao extends ElasticsearchRepository测试代码{ }
接下来操作对象就是操作索引了。
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; public interface ProductDao extends ElasticsearchRepository{ //自定义查询 List findByPriceBetweenOrderByPrice(double price1, double price2); }
测试代码如下:
//自定义 查询
@Test
public void test(){
List products = productDao.findByPriceBetweenOrderByPrice(2000, 2005);
for (Product product1 : products) {
System.out.println(product1);
}
}
更多的自定义方法命名约定
| Keyword | Sample | Elasticsearch Query String |
|---|---|---|
| And | findByNameAndPrice | {“bool” : {“must” : [ {“field” : {“name” : “?”}}, {“field” : {“price” : “?”}} ]}} |
| Or | findByNameOrPrice | {“bool” : {“should” : [ {“field” : {“name” : “?”}}, {“field” : {“price” : “?”}} ]}} |
| Is | findByName | {“bool” : {“must” : {“field” : {“name” : “?”}}}} |
| Not | findByNameNot | {“bool” : {“must_not” : {“field” : {“name” : “?”}}}} |
| Between | findByPriceBetween | {“bool” : {“must” : {“range” : {“price” : {“from” : ?,“to” : ?,“include_lower” : true,“include_upper” : true}}}}} |
| LessThanEqual | findByPriceLessThan | {“bool” : {“must” : {“range” : {“price” : {“from” : null,“to” : ?,“include_lower” : true,“include_upper” : true}}}}} |
| GreaterThanEqual | findByPriceGreaterThan | {“bool” : {“must” : {“range” : {“price” : {“from” : ?,“to” : null,“include_lower” : true,“include_upper” : true}}}}} |
| Before | findByPriceBefore | {“bool” : {“must” : {“range” : {“price” : {“from” : null,“to” : ?,“include_lower” : true,“include_upper” : true}}}}} |
| After | findByPriceAfter | {“bool” : {“must” : {“range” : {“price” : {“from” : ?,“to” : null,“include_lower” : true,“include_upper” : true}}}}} |
| Like | findByNameLike | {“bool” : {“must” : {“field” : {“name” : {“query” : “?*”,“analyze_wildcard” : true}}}}} |
| StartingWith | findByNameStartingWith | {“bool” : {“must” : {“field” : {“name” : {“query” : “?*”,“analyze_wildcard” : true}}}}} |
| EndingWith | findByNameEndingWith | {“bool” : {“must” : {“field” : {“name” : {“query” : “*?”,“analyze_wildcard” : true}}}}} |
| Contains/Containing | findByNameContaining | {“bool” : {“must” : {“field” : {“name” : {“query” : “?”,“analyze_wildcard” : true}}}}} |
| In | findByNameIn(Collectionnames) | {“bool” : {“must” : {“bool” : {“should” : [ {“field” : {“name” : “?”}}, {“field” : {“name” : “?”}} ]}}}} |
| NotIn | findByNameNotIn(Collectionnames) | {“bool” : {“must_not” : {“bool” : {“should” : {“field” : {“name” : “?”}}}}}} |
| Near | findByStoreNear | Not Supported Yet ! |
| True | findByAvailableTrue | {“bool” : {“must” : {“field” : {“available” : true}}}} |
| False | findByAvailableFalse | {“bool” : {“must” : {“field” : {“available” : false}}}} |
| OrderBy | findByAvailableTrueOrderByNameDesc | {“sort” : [{ “name” : {“order” : “desc”} }],“bool” : {“must” : {“field” : {“available” : true}}}} |



