整合ElasticSearch
一、引入依赖及配置
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2、配置yml
spring:
data:
elasticsearch:
cluster-name: elasticsearch # 集群名字
cluster-nodes: localhost:9300 # 集群结点,多个节点用逗号隔开
二、Repository接口的使用
Repository
就是ES的Dao
,和JPA的里的用法大致一样。
1、创建实体类
这里以Article
类为例,介绍了注解
常用的用法,更多用法可以百度~
@Data // lombok生成get/set
// indexName:ElasticSearch里的索引名 type:类型名
@Document(indexName = "lcy_article",type = "article")
public class Article {
@Id // Id标识主键
// Field标识属性,type:属性类型,store:是否存储,默认否,index:是否索引,默认是,analyzer:分词的方式
@Field(type = FieldType.Long,store = true)
private Long id;
@Field(type = FieldType.Keyword,store = true)
private String author;
@Field(type = FieldType.Text,store = true,analyzer = "ik_smart")
private String title;
@Field(type = FieldType.Text,store = true,analyzer = "ik_smart")
private String content;
@Field(type = FieldType.Integer,store = true)
private Integer price;
public Article() {
}
public Article(Long id, String author, String title, String content,Integer price) {
this.id = id;
this.author = author;
this.title = title;
this.content = content;
this.price = price;
}
@Override
public String toString() {
return "ID:" + id + "\t\t标题:" + title + "\t\t作者:" + author + "\t\t内容:" + content;
}
}
2、继承ElasticSearchRepository
接口
// ElasticsearchRepository<文档类型,主键类型>
public interface ArticleRepository extends ElasticsearchRepository<Article,Long> {
// 自定义查询 - 符合方法命名规范即可
List<Article> findByTitle(String title);
List<Article> findByIdBetween(Long start,Long end);
}
启动类上需要添加EnableElasticsearchRepositories
注解扫描Repository
接口。
@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "pers.liuchengyin.es.repository") // 配置ES扫描repository的包
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
3、测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class ArticleTest {