1、新建一個springboot項目,選擇web、nosql中的elasticsearch。
2、springboot默認使用spring-data操作elasticsearch,也可以使用jest操作elasticsearch。
3、在pom.xml中注釋掉spring-data的elasticsearch依賴,並添加一下依賴:
<dependency> <groupId>io.searchbox</groupId> <artifactId>jest</artifactId> <version>2.4.0</version> </dependency>
根據elasticsearch版本的不同導入不同版本的jest依賴,我使用的elasticsearch版本是2.4.9。
4、進行測試:
首先要在application.properties中配置連接地址,否則不會啟動jest。
spring.elasticsearch.jest.uris=192.168.124.22:9200
我這個版本的這個配置被移除了。。。。,接下去測試不了了,還是寫下測試的代碼。
Article.java
package com.gong.spingbootes.bean; import io.searchbox.annotations.JestId; public class Article { @JestId private Integer id; private String author; private String title; private String content; public Article(){} public Article(Integer id, String author, String title, String content) { this.id = id; this.author = author; this.title = title; this.content = content; } @Override public String toString() { return "Article{" + "id=" + id + ", author='" + author + '\'' + ", title='" + title + '\'' + ", content='" + content + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
SrpingbootEsApplicationTests.java
package com.gong.spingbootes; import com.gong.spingbootes.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 SpingbootEsApplicationTests { @Autowired JestClient jestClient; @Test public void contextLoads() { //給es索引中保存五個文檔 Article article = new Article(1,"好消息","張三","你好啊"); //構建一個索引功能 Index index = new Index.Builder(article).index("gong").type("news").build(); try { //執行 jestClient.execute(index); } catch (IOException e) { e.printStackTrace(); } }
//查詢 @Test public void search(){ String json="{" + "\"query\" : {" + " \"match\" : {" + " \"content\" : \"smith\" "+ " }" + " }" + "}" ; Search search = new Search.Builder(json).addIndex("gong").addType("news").build(); try { SearchResult searchResult = jestClient.execute(search); System.out.println(searchResult.getJsonString()); } catch (IOException e) { e.printStackTrace(); } } }