目录
1 相关配置
2 相关测试
2.1 索引测试
2.2 文档操作
2.3 文档搜索
1 相关配置
1)相关依赖:
4.0.0 org.springframework.boot spring-boot-starter-parent2.3.7.RELEASE com.liubujun springdata-elasticsearch0.0.1-SNAPSHOT springdata-elasticsearch Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-data-elasticsearchorg.springframework.boot spring-boot-devtoolsruntime true org.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-testjunit junitorg.springframework spring-testorg.projectlombok lomboktrue org.springframework.boot spring-boot-maven-pluginorg.projectlombok lombok
2)相关配置类:
//ConfigurationProperties会自动读取application.properties配置文件下elasticsearch开头的配置
@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;
}
}
3)配置文件application.properties
#es的服务地址 elasticsearch.host=127.0.0.1 #es服务端口 elasticsearch.port = 9200 #配置日志级别,开启debug日志 logging.level.com.atguigu.es=debug
4)实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(indexName = "product",shards = 3,replicas = 1)
public class Product {
@Id
private Long 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; //图片地址
}
5)持久层
@Repository public interface ProductDao extends ElasticsearchRepository{ }
2 相关测试
2.1 索引测试
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringdataElasticsearchApplicationTests {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@Test
public void createIndex(){
//系统初始化会自动创建索引,会自动找到实体类中的product索引,如果有则跳过,没有则创建
System.out.println("创建索引");
}
@Test
public void deleteIndex(){
//系统初始化会自动创建索引
boolean flag = elasticsearchRestTemplate.deleteIndex(Product.class);
System.out.println("删除索引="+flag);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringdataElasticsearchApplicationTests {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@Test
public void createIndex(){
//系统初始化会自动创建索引,会自动找到实体类中的product索引,如果有则跳过,没有则创建
System.out.println("创建索引");
}
@Test
public void deleteIndex(){
//系统初始化会自动创建索引
boolean flag = elasticsearchRestTemplate.deleteIndex(Product.class);
System.out.println("删除索引="+flag);
}
}
先查一下当前ES中的索引。
运行测试类添加索引之后:
可以发现索引正常添加。
运行删除索引后:
2.2 文档操作
1)保存文档:
@Autowired
private ProductDao productDao;
@Test
public void createIndex(){
//新增
Product product = new Product();
product.setId(2L);
product.setTitle("华为手机");
product.setCategory("手机");
product.setPrice(2999.0);
product.setImages("http://jdvzvcz.jpg");
productDao.save(product);
}
注意:运行之后可能会出现如下错误:
Unable to parse response body for Response{requestLine=PUT /product/_doc/2?timeout=1m HTTP/1.1, host=http://127.0.0.1:9200, response=HTTP/1.1 201 Created}; nested exception is java.lang.RuntimeException: Unable to parse response body for Response{requestLine=PUT /product/_doc/2?timeout=1m HTTP/1.1, host=http://127.0.0.1:9200, response=HTTP/1.1 201 Created}
但是数据是已经保存到我们的es中的,这可能是由于我的es版本过低导致的。
2)修改文档:
@Test
public void updateIndex(){
//新增
Product product = new Product();
product.setId(2L);
product.setTitle("华为手机");
product.setCategory("手机");
product.setPrice(1999.0);
product.setImages("http://jdvzvcz.jpg");
productDao.save(product);
}
其实和新增文档一样,修改之后查询es看是否修改成功
如上所示:价格已经修改成功。
3)根据id查询
//根据id查询
@Test
public void findById(){
Product product = productDao.findById(2L).get();
System.out.println(product);
}
4)查询所有
//查询所有
@Test
public void findAll(){
Iterable products = productDao.findAll();
for (Product product: products){
System.out.println(product);
}
}
5)批量插入
//批量新增
@Test
public void saveAll(){
List productList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
//新增
Product product = new Product();
product.setId(Long.valueOf(i));
product.setTitle("华为手机");
product.setCategory("手机");
product.setPrice(1999.0+i);
product.setImages("http://jdvzvcz.jpg");
productList.add(product);
}
productDao.saveAll(productList);
}
es查询:
6)分页查询
//分页查询
@Test
public void findByPageable(){
//设置排序方式
Sort sort = Sort.by(Sort.Direction.DESC, "id");
int from = 0;
int to = 5;
//设置查询分页
PageRequest pageRequest = PageRequest.of(from, to, sort);
Page productPage = productDao.findAll(pageRequest);
for (Product product : productPage.getContent()) {
System.out.println(product);
}
}
结果:
2.3 文档搜索
1)全部搜索
@Test
public void termQuery(){
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
Iterable products = productDao.search(termQueryBuilder);
for (Product product : products){
System.out.println(product);
}
}
2)分页搜索
@Test
public void termQueryPage(){
int currentPage = 0;
int pageSize = 5;
PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
Iterable products = productDao.search(termQueryBuilder, pageRequest);
for (Product product : products){
System.out.println(product);
}
}



