使用的工具:
IDEA 2018、elasticsearch-5.6.5;
1、下载elasticsearch,解压,打开config文件目录下的elasticsearch.yml文件,可在文件中配置集群名称、集群节点名、端口等信息;
2、打开idea,创建spring-boot工程,在web选项中勾选web,在nosql选项中勾选elasticsearch,点击next继续
3、在工程pom.xml中加入dependency(注意版本号对应,避免兼容问题),如下图:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.5</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.6.5</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
4、在application.properties中配置elasticsearch,如下图:
# elasticsearch
spring.data.elasticsearch.cluster-name=elasticsearch(自行定义)
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
#spring.data.elasticsearch.local=false
spring.data.elasticsearch.repositories.enable=true
5、编写configuration:
@Configuration
public class ElasticsearchConf {
@Bean
public ElasticsearchOperations elasticsearchTemplate(Client client) {
return new ElasticsearchTemplate(client);
}
}
6、编写dao层接口
@Component(value = "articleDao")
public interface ArticleDao extends ElasticsearchCrudRepository<Article, String> {
}
7、编写model,(index=》DB,type=》table)
@Document(indexName = "blog",type = "article", shards = 1,replicas = 0, refreshInterval = "-1")
public class Article {
@Id
private String id;
private String title;
private String content;
private String[] newcontent;
private String about;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String[] getNewcontent() {
return newcontent;
}
public void setNewcontent(String[] newcontent) {
this.newcontent = newcontent;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
}
8、编写controller(service由于懒得原因,暂省)
@Controller
@RequestMapping("/index")
public class IndexController {
@Autowired
private ArticleDao articleDao;
@RequestMapping("/article")
@ResponseBody
public Article getArticle(HttpServletRequest request) {
String id = request.getParameter("id");
return articleDao.findById(id).get();
}
}