1. 在idea中新建项目,选择spring模板。
2. 选择elasticsearch依赖。
3. 项目的pom文件是这样的。
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.6.1
com.mujl
springelasticsearch
0.0.1-SNAPSHOT
springelasticsearch
Demo project for Spring Boot
1.8
org.projectlombok
lombok
org.springframework.boot
spring-boot-starter-data-elasticsearch
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
4. application.properties文件的内容
spring.elasticsearch.uris=http://101.43.8.200:9200,http://47.104.165.141:9200,http://82.156.163.91:9200
5. javaBean类
package com.mujl.springelasticsearch.bean;
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;
import java.io.Serializable;
import java.math.BigDecimal;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@document(indexName = "shop",shards=5,replicas = 1,createIndex = false)
public class Goods implements Serializable {
@Id
private Integer goodsId;
@Field(type = FieldType.Text,analyzer = "ik_max_word")
private String goodsName;
@Field(type = FieldType.Double)
private BigDecimal marketPrice;
@Field(type=FieldType.Keyword)
private String originalImg;
private static final long serialVersionUID = 1L;
}
javaBean内容解释
6. GoodsRepository类
package com.mujl.springelasticsearch.dao;
import com.mujl.springelasticsearch.bean.Goods;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
public interface GoodsRepository extends ElasticsearchRepository {
List findByGoodsName(String goodsName);
@Query("{"match":{"goodsId":{"query":"?0"}}}")
Goods findByIdValue(Integer id);
}
GoodsRepository类内容解释
7. 测试方法(//注释的方法也是可用的,只是为了测试效果注释掉了一些其他效果)
package com.mujl.springelasticsearch;
import com.mujl.springelasticsearch.bean.Goods;
import com.mujl.springelasticsearch.dao.GoodsRepository;
import lombok.val;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SpringBootTest
class SpringelasticsearchApplicationTests {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@Autowired
private GoodsRepository goodsRepository;
@Test
void contextLoads() {
}
@Test
public void testIndex(){
// //获取索引对象
IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Goods.class);
// //创建索引
// indexOperations.create();
// //获取映射,根据Goods类中的@Field注解,生成映射。
// document mapping = indexOperations.createMapping(Goods.class);
// //把映射放入索引中去
// indexOperations.putMapping(mapping);
//
// //判断索引是否存在
// Boolean exists = indexOperations.exists();
// System.out.println(exists);
//删除索引
indexOperations.delete();
}
@Test
public void testRepository(){
//添加
// List list = new ArrayList<>();
// list.add(new Goods(150,"测试手机1",new BigDecimal("200"),"png"));
// list.add(new Goods(151,"测试手机2",new BigDecimal("200"),"png"));
// goodsRepository.saveAll(list);
//根据商品名称查询商品
// List goodsList = goodsRepository.findByGoodsName("%测试%");
// goodsList.forEach(System.out::println);
Goods goods = goodsRepository.findByIdValue(150);
System.out.println(goods);
}
@Test
public void testCUD(){
List list = new ArrayList<>();
//添加/更新(id存在就是更新,id不存在就是添加)
list.add(new Goods(158,"测试手机9",new BigDecimal("200"),"png"));
list.add(new Goods(159,"测试手机10",new BigDecimal("200"),"png"));
elasticsearchRestTemplate.save(list);
//删除
// elasticsearchRestTemplate.delete("150", IndexCoordinates.of("shop"));
//删除查询出来的结果
// NativeSearchQuery query = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchQuery("goodsName", "测试")).build();
// elasticsearchRestTemplate.delete(query,Goods.class,IndexCoordinates.of("shop"));
}
@Test
public void testSearch(){
NativeSearchQuery query = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchQuery("goodsName", "测试")).build();
SearchHits search = elasticsearchRestTemplate.search(query,Goods.class);
search.getSearchHits().forEach(System.out::println);
}
@Test
public void testSearchHigh(){
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.multiMatchQuery("测试","goodsName"))
//分页
// .withPageable(PageRequest.of(0,5))
//分页和排序写在一起
.withPageable(PageRequest.of(0,5,Sort.Direction.DESC,"goodsId","marketPrice"))
//排序,分数正序
// .withSort(SortBuilders.scoreSort().order(SortOrder.ASC))
// .withSort(SortBuilders.fieldSort("goodsId").order(SortOrder.ASC))
//高亮,默认斜体
// .withHighlightFields(new HighlightBuilder.Field("goodsName"))
//指定样式的高亮
.withHighlightBuilder(new HighlightBuilder().field("goodsName").preTags("").postTags(""))
.build();
SearchHits searchHits = elasticsearchRestTemplate.search(query,Goods.class);
for(SearchHit searchHit:searchHits){
float score = searchHit.getScore();
String id = searchHit.getId();
List list = searchHit.getSortValues();
list.forEach(System.out::println);
String goodsName = searchHit.getHighlightField("goodsName").get(0);
Goods goods = searchHit.getContent();
System.out.println("score:"+score);
System.out.println("id:"+id);
// System.out.println("sortValue:"+sortValue);
System.out.println("goods:"+goods);
System.out.println("goodsName高亮:"+goodsName);
System.out.println("==============================");
}
}
}
SpringelasticsearchApplicationTests类的相关解释