首先安装 Elasticsearch和Kibana
Download Elasticsearch | Elastic Download Kibana Free | Get Started Now | Elastic
导入相关maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
yml中配置相关参数
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9300 #9200是图形界面端,9300代码端
创建文档对象
该文档对象可用来做如下几个事情
- 索引库的创建
- 文档的映射
- 存储到ES的数据封装
/**
* 针对于student表的文档映射
* indexName:索引库
* type:类型(表类型)
*/
@Document(indexName = "stu" , type = "student")
public class StudentDoc {
//对应文档的id PUT /index/type/id
@Id
private Long id;
//指定为 不分词
@Field(type = FieldType.Keyword)
private String userName;
private int age;
//指定为 分词
@Field(type =FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String intro;
初始化索引库和文档映射
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EsServiceApplication.class)
public class ElasticsearchTest {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Test
public void testCreateIndex() {
//创建索引
elasticsearchTemplate.createIndex(StudentDoc.class);
//做文档映射
elasticsearchTemplate.putMapping(StudentDoc.class);
}
}
到此为止基础的集成就已经完成,可以通过Kibana测试索引是否创建成功。