Elasticsearch基本概念
mysql:database(数据库) table(表) rocord(记录)
es : index type(只能存在一个) document
1 添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2 修改application.properties文件
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
spring.data.elasticsearch.repositories.enabled=true
3 编写实体类Article,并添加Elasticsearch相关的注解
import java.io.Serializable;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "blog", type = "article")
public class Article implements Serializable{
private long id;
private String title;
private String summary;
private String content;
private int pv;
//生成get,set方法
}
4 编写接口ArticleRepository并继承ElasticSearchRepository,里面有很多默认实现
@Component
//@Repository
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
}
5 测试调用
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/article")
public class ArticleController {
@Autowired
private ArticleRepository articleRepository;
@GetMapping("save")
public Object save(long id,String title){
Article article = new Article();
article.setId(id);
article.setPv(123);
article.setContent("springboot整合elasticsearch");
article.setTitle(title);
article.setSummary("搜索框架整合");
articleRepository.save(article);
return JsonData.buildSuccess();
}
@GetMapping("search")
public Object search(String title){
//QueryBuilder queryBuilder = QueryBuilders.matchAllQuery(); //搜索全部文档
QueryBuilder queryBuilder = QueryBuilders.matchQuery("title", title);
Iterable<Article> list = articleRepository.search(queryBuilder);
return JsonData.buildSuccess(list);
}
}
Elasticsearch基本命令
查看集群状态:http://localhost:9200/_cat/health?v
查看索引列表:http://localhost:9200/_cat/indices?v
查看某个索引库结构:http://localhost:9200/blog
查看某个对象:http://localhost:9200/blog/article/1