<!--SpringBoot默認使用SpringData ElasticSearch模塊進行操做 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>--> <!-- https://mvnrepository.com/artifact/io.searchbox/jest --> <dependency> <groupId>io.searchbox</groupId> <artifactId>jest</artifactId> <version>5.3.3</version> </dependency>
SpringBoot默認使用兩種技術來和ES交互java
一、Jest(默認不生效)git
須要導入jest的工具包(io.searchbox.client.JestClient)github
二、SpringData ElasticSearchspring
1)、Client 節點 :配置clusterNodes、clusterNamejson
2)、ElasticSearchTemplate 操做eselasticsearch
3)、編寫ElasticSearchRepository的子接口來操做esspring-boot
spring.elasticsearch.jest.uris=http://tanghu.tk:9200
ElasticSearch的默認url爲:localhost:9200工具
package com.fdzang.mblog.pojo.es; import io.searchbox.annotations.JestId; public class EsBlog { @JestId // 主鍵 private String id; private Long blogId; private String title; private String summary; private String content; public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getBlogId() { return blogId; } public void setBlogId(Long blogId) { this.blogId = blogId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package com.fdzang.mblog; import com.fdzang.mblog.pojo.es.EsBlog; import io.searchbox.client.JestClient; import io.searchbox.core.Index; 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 MblogApplicationTests { @Autowired JestClient jestClient; @Test public void contextLoads() { //1.給es中索引(保存)一個文檔 EsBlog esBlog=new EsBlog(); esBlog.setBlogId(10001l); esBlog.setId("10001"); esBlog.setContent("content"); esBlog.setSummary("summary"); esBlog.setTitle("title"); //構建一個索引功能 Index index=new Index.Builder(esBlog).index("thblog").type("blog").build(); try { //執行 jestClient.execute(index); } catch (IOException e) { e.printStackTrace(); } } }
成功!測試
@Test public void testSearch(){ //查詢表達式 String json="{\n" + " \"query\" : {\n" + " \"match\" : {\n" + " \"title\" : \"tle\"\n" + " }\n" + " }\n" + "}"; //構建搜索功能 Search search=new Search.Builder(json).addIndex("thblog").addType("blog").build(); try { SearchResult result=jestClient.execute(search); System.out.println(result.getJsonString()); } catch (IOException e) { e.printStackTrace(); } }
獲得結果集:ui
github文檔地址:https://github.com/searchbox-io/Jest/tree/master/jest