本文共 3132 字,大约阅读时间需要 10 分钟。
Spring Data Elasticsearch 是 Spring 提供的一种以 Spring Data 风格操作数据存储的方式,它能够显著减少样板代码的编写量。
public @interface Document { String indexName(); // 索引库名,类似 MySQL 中的数据库名称 String type() default ""; // 文档类型,类似 MySQL 中的表名称 short shards() default 5; // 默认分片数 short replicas() default 1; // 默认副本数量}
public @interface Id {}
public @interface Field { FieldType type() default FieldType.Auto; // 文档字段的类型,Auto 表示自动检测类型 boolean index() default true; // 是否建立倒排索引 boolean store() default false; // 是否存储字段值 String analyzer() default ""; // 分词器名称}
public enum FieldType { Text, Integer, Long, Date, Float, Double, Boolean, Object, Auto, Nested, Ip, Attachment, Keyword;}
org.springframework.boot spring-boot-starter-data-elasticsearch
spring: data: elasticsearch: enabled: true cluster-name: elasticsearch cluster-nodes: 192.168.49.14:9300
@Configurationpublic class ElasticSearchConfig { @PostConstruct void init() { System.setProperty("es.set.netty.runtime.available.processors", "false"); }}
@Document(indexName = "product", type = "product", shards = 1, replicas = 0)public class Product { @Id private Long id; @Field(type = FieldType.Text, analyzer = "ik_max_word") private String title; @Field(type = FieldType.Keyword) private String category; @Field(type = FieldType.Double) private Double price; @Field(index = false, type = FieldType.Keyword) private String images; // setter方法省略...}
@Servicepublic interface ProductRepository extends ElasticsearchRepository{ List findByTitle(String title);}
@RestControllerpublic class ProductController { @Autowired private ProductRepository productRepository; @RequestMapping("/importProduct") public void importProduct() { Listlist = new ArrayList<>(); // 添加产品1到4,具体代码省略... productRepository.saveAll(list); } @RequestMapping("/selectProductAll") public void selectProductAll() { Iterable list = productRepository.findAll(); // 操作数据... } // 其他操作方法类似...}
通过继承 ElasticsearchRepository
接口,可以定义自定义查询方法。例如:
public interface ProductRepository extends ElasticsearchRepository{ List findByTitle(String title);}
@PostConstructvoid init() { System.setProperty("es.set.netty.runtime.available.processors", "false");}
public interface ProductRepository extends ElasticsearchRepository{ List findByTitle(String title);}
@GetMapping("/selectProductByCustom")public ListselectProductByCustom(String title) { List result = productRepository.findByTitle(title); return result;}
转载地址:http://miasz.baihongyu.com/