深入学习java笔记-13.SpringBoot2.1之elasticsearch集成

pom.xml
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
            2.1.4.RELEASE
        
application.yml
spring:
    data:
        elasticsearch:
          cluster-name: elasticsearch
          cluster-nodes: 127.0.0.1:9300
          repositories:
            enabled: true
Article.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Document(indexName = "blog", type = "article")
public class Article implements Serializable {
    private static final long serialVersionUID = 1525231207462514536L;
    private long id;
    private String title;
    private String summary;
    private String content;
    private Integer pv;
}
ArticleRepository.java
import com.ctgu.springstart.domain.Article;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;


@Component
@Document(indexName = "blog", type = "article", shards = 1, replicas = 0)
public interface ArticleRepository extends ElasticsearchRepository {

}
ArticleController.java
import com.ctgu.springstart.domain.Article;
import com.ctgu.springstart.domain.JsonData;
import com.ctgu.springstart.repository.ArticleRepository;
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/es")
public class ArticleController {

    @Autowired
    private ArticleRepository articleRepository;

    @GetMapping("save")
    public Object save(){
        Article article = Article.builder()
                .id(2L)
                .pv(888)
                .content("this is content")
                .title("I love xdclass 教程")
                .summary("概要搜索")
                .build();
        articleRepository.save(article);
        return JsonData.builder().data(article).build();
    }

    @GetMapping("search")
    public Object search(String title){
        QueryBuilder queryBuilder = QueryBuilders.matchQuery("title", title);
        Iterable
list = articleRepository.search(queryBuilder); return JsonData.builder().data(list).build(); } }

你可能感兴趣的:(深入学习java笔记-13.SpringBoot2.1之elasticsearch集成)