pom
<!-- elasticsearch 启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
yml
spring: elasticsearch: uris: - http://111.111.111.111:9200
创建文档document
@Document(indexName = "product") @Data /** * name: 当前字段在索引中的名称,不设置默认使用字段名称 * type: 字段类型 * analyzer: 创建索引的分词器类型 不设置使用默认 * searchAnalyzer: 搜索条件的分词器类型,不设置使用 analyzer * index: 是否索引(默认:true) * keyword : 短语,不进行分词 * format: 日期格式化,预设的值没一个符合中国人习惯的, * format = {}, pattern = "yyyy-MM-dd HH:mm:ss" 覆盖默认设置 */ public class ProductDoc { //商品Id @Id private Long id; //分类Id @Field(type = FieldType.Long) private Long categoryId; //图片地址 @Field(type = FieldType.Text,index = false) private String img; //商品标题 @Field(type = FieldType.Text,analyzer = "ik_smart") private String title; //商品简介 @Field(type = FieldType.Text,analyzer = "ik_smart") private String intro; //一级分类名称 @Field(type = FieldType.Keyword) private String categoryNameLevel1; //二级分类名称 @Field(type = FieldType.Keyword) private String categoryNameLevel2; //三级分类名称 @Field(type = FieldType.Keyword) private String categoryNameLevel3; //商品价格 @Field(type = FieldType.Double) private BigDecimal price; //商品销量 @Field(type = FieldType.Integer) private Integer sales; //更新时间 @Field(type = FieldType.Date, format = {}, pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; //创建时间 @Field(type = FieldType.Date, format = {}, pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; }
创建repository public interface ProductRepository extends ElasticsearchRepository<ProductDoc, Long> { }
注入ProductRepository和ElasticsearchRestTemplate
搜索
List<SearchHit<ProductDoc>> searchHits=template.search(query,ProductDoc.class).getSearchHits(); List<ProductDoc> list=new ArrayList<>(); searchHits.forEach(item->{ list.add(item.getContent()); });
新增或更新
productRepository.save(productDoc);
删除
productRepository.deleteById(id);