Spring Boot 揭祕與實戰(二) 資料儲存篇 - ElasticSearch

樑桂釗發表於2016-12-20

本文講解Spring Boot基礎下,如何使用 ElasticSearch,實現全文搜尋。
原文地址:Spring Boot 揭祕與實戰(二) 資料儲存篇 - ElasticSearch
部落格地址:blog.720ui.com/

版本須知

spring data elasticSearch 的版本與Spring boot、Elasticsearch版本需要匹配。

Spring Boot Version (x) Spring Data Elasticsearch Version (y) Elasticsearch Version (z)
x <= 1.3.5 y <= 1.3.4 z <= 1.7.2
x >= 1.4.x 2.0.0 <=y <5.0.0 2.0.0 <= z < 5.0.0

環境依賴

修改 POM 檔案,新增 spring-boot-starter-data-elasticsearch 依賴。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>複製程式碼

資料來源

方案一 使用 Spring Boot 預設配置

在 src/main/resources/application.properties 中配置資料來源資訊。

spring.data.elasticsearch.properties.host = 127.0.0.1
spring.data.elasticsearch.properties.port = 9300複製程式碼

通過 Java Config 建立ElasticSearchConfig。

@Configuration
@EnableElasticsearchRepositories("com.lianggzone.springboot.action.data.elasticsearch")
public class ElasticSearchConfig {}複製程式碼

方案二 手動建立

通過 Java Config 建立ElasticSearchConfig。

@Configuration
@EnableElasticsearchRepositories("com.lianggzone.springboot.action.data.elasticsearch")
public class ElasticsearchConfig2 {

    private String hostname = "127.0.0.1";
    private int port = 9300;

    @Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchTemplate(client());
    }

    @Bean
    public Client client() {
        TransportClient client = new TransportClient();
        TransportAddress address = new InetSocketTransportAddress(hostname, port);

        client.addTransportAddress(address);
        return client;
    }
}複製程式碼

業務操作

實體物件

@Document(indexName = "springbootdb", type = "news")
public class News {

    @Id
    private String id;

    private String title;

    private String content;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd'T'HHmmss.SSS'Z'")
    @Field(type = FieldType.Date, format = DateFormat.basic_date_time, index = FieldIndex.not_analyzed)
    @CreatedDate
    private Date createdDateTime;

    // GET和SET方法
}複製程式碼

DAO相關

public interface NewsRepository extends ElasticsearchRepository<News, String> {
    public List<News> findByTitle(String title);
}複製程式碼

Service相關

我們來定義實現類,Service層呼叫Dao層的方法,這個是典型的套路。

@Service
public class NewsService {

    @Autowired
    private NewsRepository newsRepository;

    public Iterable<News> findAll(){
        return newsRepository.findAll();
    }

    public Iterable<News> search(QueryBuilder query){
        return newsRepository.search(query);
    }

    public List <News> findByTitle(String title) {
        return this.newsRepository.findByTitle(title);
    }

    public void deleteAll(String id){
        this.newsRepository.delete(id);
    }

    public void init(){
        for (int i = 0; i < 100; i++) {
            News news = new News();
            news.setId(i+"");
            news.setTitle(i + ".樑桂釗單元測試用例");
            news.setContent("樑桂釗單元測試用例"+i+"xxxxx");
            news.setCreatedDateTime(new Date());
            this.newsRepository.save(news);
        }
    }
}複製程式碼

Controller相關

為了展現效果,我們先定義一組簡單的 RESTful API 介面進行測試。

@RestController
@RequestMapping(value="/data/elasticsearch/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    /**
     * 初始化
     * @param request
     */
    @RequestMapping(value = "/init", method = RequestMethod.POST)
    public void init(HttpServletRequest request) {
        this.newsService.init();
    }

    /**
     * findAll        
     * @param request
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Map<String, Object> findList(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("items", this.newsService.findAll());
        return params;
    }

    /**
     * find      
     * @param request
     * @return
     */
    @RequestMapping(value = "/{title}", method = RequestMethod.GET)
    public Map<String, Object> search(@PathVariable String title) {
        // 構建查詢條件
        QueryBuilder queryBuilder = QueryBuilders.queryString(title);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("items", this.newsService.search(queryBuilder));
        return params;
    }
}複製程式碼

總結

上面這個簡單的案例,讓我們看到了 Spring Boot 整合 ElasticSearch 流程如此簡單。

原始碼

相關示例完整程式碼: springboot-action

(完)

更多精彩文章,盡在「服務端思維」微信公眾號!

Spring Boot 揭祕與實戰(二) 資料儲存篇 - ElasticSearch

相關文章