SpringBoot默認支持兩種技術來和ES交互;
java
建立項目須要引入ES的啓動器node
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <!--集合工具包--> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> |
第一種:git
一、Jest(默認不生效) 須要導入jest的工具包(io.searchbox.client.JestClient)github
操做步驟:web
1) 引入jest的依賴spring
<!-- https://mvnrepository.com/artifact/io.searchbox/jest --> <dependency> <groupId>io.searchbox</groupId> <artifactId>jest</artifactId> <version>6.3.1</version> </dependency> |
2)在配置文件中jest添加相關配置json
#使用jest客戶端操做ES spring.elasticsearch.jest.uris=http://10.2.193.102:9200 |
3)使用jest客戶端操做ESapi
import cn.xiwei.springboot.es.bean.Article; import io.searchbox.client.JestClient; import io.searchbox.core.Index; import io.searchbox.core.Search; import io.searchbox.core.SearchResult; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
@RunWith(SpringRunner.class) @SpringBootTest public class EsApplicationTests {
@Autowired JestClient jestClient; @Test public void contextLoads() {
//一、給Es中索引(保存)一個文檔; Article article = new Article(); article.setId(1); article.setTitle("好消息"); article.setAuthor("zhangsan"); article.setContent("Hello World");
//構建一個索引功能 Index index = new Index.Builder(article).index("xiwei").type("news").build();
try { //執行 jestClient.execute(index); } catch (IOException e) { e.printStackTrace(); } }
//測試搜索 @Test public void search(){ //構建查詢表達式 String json = "{\n" + " \"query\" : {\n" + " \"match\" : {\n" + " \"content\" : \"hello\"\n" + " }\n" + " }\n" + "}"; Search search = new Search.Builder(json).addIndex("xiwei").addType("news").build();
try { SearchResult result = jestClient.execute(search); System.out.println(result.getJsonString()); } catch (IOException e) { e.printStackTrace(); } }
} |
第二種:
一、SpringData ElasticSearch【ES版本有可能不合適】
* 版本適配說明:https://github.com/spring-projects/spring-data-elasticsearch
* 若是版本不適配:2.4.6
* 1)、升級SpringBoot版本
* 2)、安裝對應版本的ES
1)、Client 節點信息clusterNodes;clusterNamespringboot
#ES集羣的名稱 spring.data.elasticsearch.cluster-name=my-application
#Es節點的訪問地址及端口 spring.data.elasticsearch.cluster-nodes=10.2.193.102:9300
#開啓repositories spring.data.elasticsearch.repositories.enabled=true
#項目端口號 server.port=8080 |
2)、ElasticsearchTemplate 操做es (略)app
3)、編寫一個 ElasticsearchRepository 的子接口來操做ES;
import cn.xiwei.springboot.es.bean.Notice; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Component;
@Component public interface NoticeRepository extends ElasticsearchRepository<Notice, Long> {
} |
4)、測試
import cn.xiwei.springboot.es.bean.Notice; import cn.xiwei.springboot.es.repository.NoticeRepository; import com.google.common.collect.Lists; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.web.PageableDefault; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList; import java.util.List;
/** * @author lykan * @create 2019-09-11 18:40 */ @RestController @RequestMapping("/api/v1/article") public class NoticeController {
@Autowired private NoticeRepository nticeRepository; @Autowired ElasticsearchTemplate elasticsearchTemplate;
@GetMapping("/save") public Object save(long id, String title){
Notice article = new Notice(); article.setId(id); article.setReadCount(123); article.setTitle(title); return nticeRepository.save(article); }
/** * @param title 搜索標題 * @param pag page = 第幾頁參數, value = 每頁顯示條數 */ @GetMapping("/search") public Object search(String title ,@PageableDefault() Pageable pag){
//按標題進行搜索 QueryBuilder builder = QueryBuilders.matchQuery("title", title); //若是實體和數據的名稱對應就會自動封裝,pageable分頁參數 Iterable<Notice> listIt = nticeRepository.search(builder, pag); //Iterable轉list List<Notice> list= Lists.newArrayList(listIt);
return list; }
@RequestMapping("/all") public List<Notice> all() throws Exception { Iterable<Notice> data = nticeRepository.findAll(); List<Notice> ds = new ArrayList<>(); for (Notice d : data) { ds.add(d); } return ds; } @RequestMapping("/id") public Object findid(long id) throws Exception { return nticeRepository.findById(id).get();
}
} |
5)、實體類
import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.data.elasticsearch.annotations.Document;
/** * @author lykan * @create 2019-09-11 18:00 */ //indexName表明因此名稱,type表明表名稱 @Document(indexName = "wantu_notice_info", type = "doc") public class Notice { //id @JsonProperty("auto_id") private Long id; //標題 @JsonProperty("title") private String title; //公告標籤 @JsonProperty("exchange_mc") private String exchangeMc; //公告發布時間 @JsonProperty("create_time") private String originCreateTime; //公告閱讀數量 @JsonProperty("read_count") private Integer readCount; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getExchangeMc() { return exchangeMc; } public void setExchangeMc(String exchangeMc) { this.exchangeMc = exchangeMc; } public String getOriginCreateTime() { return originCreateTime; } public void setOriginCreateTime(String originCreateTime) { this.originCreateTime = originCreateTime; } public Integer getReadCount() { return readCount; } public void setReadCount(Integer readCount) { this.readCount = readCount; } public Notice(Long id, String title, String exchangeMc, String originCreateTime, Integer readCount) { super(); this.id = id; this.title = title; this.exchangeMc = exchangeMc; this.originCreateTime = originCreateTime; this.readCount = readCount; } public Notice() { super(); } } |
兩種用法:https://github.com/spring-projects/spring-data-elasticsearch