今天在实验室摸索了一天Elasticsearch与Spring Boot集成,终于初见成效,很开心,mark一下。
启动Elasticsearch
首先,确保已经正确启动了Elasticsearch服务器,windows系统运行Elasticsearch解压文件下的bin/elasticsearch.bat文件(linux系统运行bin/elasticsearch文件)即可。
运行成功后,在浏览器中访问http://localhost:9200,查看是否启动成功,启动成功结果如下:
{
"name" : "Rg9hQgw", // 默认的节点名称
"cluster_name" : "elasticsearch", // 默认的集群名称
"cluster_uuid" : "phE0-t5oTCqeX8XIYsd1Tw",
"version" : {
"number" : "6.6.1",
"build_flavor" : "default",
"build_type" : "zip",
"build_hash" : "1fd8f69",
"build_date" : "2019-02-13T17:10:04.160291Z",
"build_snapshot" : false,
"lucene_version" : "7.6.0",
"minimum_wire_compatibility_version" : "5.6.0",
"minimum_index_compatibility_version" : "5.0.0"
},
"tagline" : "You Know, for Search"
}
修改application.properties
#Elasticsearch 服务地址
spring.data.elasticsearch.cluster-nodes=localhost:9300
#设置连接超时时间
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s
这里一定要把端口号改为9300。9300 是 Java 客户端的端口,9200 是支持 Restful HTTP 的接口,这两个在使用中应注意区分。
创建文档类
这里我创建了一个简单的博客类EsBlog,专门用于在ES中存储博客文档。代码如下:
package com.minproject.easynews.model.ES;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
/**
* created time: 2019/03/12 17:57
* author AmyZhang
**/
@Document(indexName = "blogtest", type = "blogtest")
public class EsBlog implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String id;
private String title;
private String summary;
private String content;
// JPA的规范要求无参构造函数;设置为protected防止直接使用
protected EsBlog() {
}
public EsBlog(String title, String summary