當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot高级-检索-SpringBoot整合Jest操作ES
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot高级-检索-SpringBoot整合Jest操作ES
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
接下來就用SpringBoot來整合ElasticSearch進行測試,pom文件引入了spring-boot-starter-data-elasticsearch,其實加了data都是用springdata來操作的,他這里確實引入了<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId><version>1.5.12.RELEASE</version>
</dependency>SpringBoot默認使用SpringData操作ElasticSearch模塊進行操作的,那我們再來分析一下ES的自動配置,來到autoconfigure里邊
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.learn</groupId><artifactId>springboot-03-elastic</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>springboot-03-elastic</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.12.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><!--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><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
這里有一個data,org.springframework.boot.autoconfigure.data,data里面有elasticsearch,這是SpringData對ElasticSearch的支持,包括下邊大家來看org.springframework.boot.autoconfigure.data.elasticsearch下邊還有一個elasticsearchorg.springframework.boot.autoconfigure.elasticsearch.jest這叫jest,這是一個非常流行的ES客戶端工具,他利用HTTP的方式,跟ES進行交互的,所以它有兩種方式來操作ES,我們來記錄一下,SpringBoot默認支持兩種技術,來和ES交互,第一種是JEST,第二種是SpringData ElasticSearch,那我們來看哪種技術生效,到底怎么生效呢,我們還是來下翻,我們先看jest的自動配置,來看JestAutoConfiguration,@Configuration
@ConditionalOnClass(JestClient.class)
@EnableConfigurationProperties(JestProperties.class)
@AutoConfigureAfter(GsonAutoConfiguration.class)
public class JestAutoConfiguration {由于我們缺少導了一個包,其實是不生效的,所以默認如果想要他生效,我們需要導入這個包import io.searchbox.client.JestClient;JEST默認是不生效的,需要導入jest的工具包,這里有一個完整描述,我們來看SpringData的自動配置,如果生效就用9200端口進行HTTP交互@Bean(destroyMethod = "shutdownClient")
@ConditionalOnMissingBean
public JestClient jestClient() {JestClientFactory factory = new JestClientFactory();factory.setHttpClientConfig(createHttpClientConfig());return factory.getObject();
}SpringData有ElasticsearchAutoConfiguration,他給我們配置了什么呢,他給我們配置了一個連接,@Bean
@ConditionalOnMissingBean
public Client elasticsearchClient() {try {return createClient();}catch (Exception ex) {throw new IllegalStateException(ex);}
}這個客戶端需要指定一些屬性,比如集群里面每一個節點的信息,private Client createNodeClient() throws Exception {Settings.Builder settings = Settings.settingsBuilder();for (Map.Entry<String, String> entry : DEFAULTS.entrySet()) {if (!this.properties.getProperties().containsKey(entry.getKey())) {settings.put(entry.getKey(), entry.getValue());}}settings.put(this.properties.getProperties());Node node = new NodeBuilder().settings(settings).clusterName(this.properties.getClusterName()).node();this.releasable = node;return node.client();
}幫我們配置了這么些內容,第一個給我們一個客戶端,我們可以用客戶端,public String getClusterNodes() {return this.clusterNodes;
}我們需要配這個信息,public String getClusterName() {return this.clusterName;
}這是我們節點的信息,第二個他還為我們配了什么呢,這個我們就不看了,ElasticsearchDataAutoConfiguration,他給我們配了一個ElasticsearchTemplate@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(Client.class)
public ElasticsearchTemplate elasticsearchTemplate(Client client,ElasticsearchConverter converter) {try {return new ElasticsearchTemplate(client, converter);}catch (Exception ex) {throw new IllegalStateException(ex);}
}我們這個寫template用的已經非常多了,比如我們以前用的JDBC template,操作Redis的Template,操作Rabbit的Template,那么由此可見,Spring在整合很多技術的時候呢,都會引入相關的Template操作就行了,他來操作ES,還引入了ElasticsearchRepositoriesAutoConfiguration,他的作用就是啟用了ElasticsearchRepository接口,他就類似于JPA的操作方式一樣,我們可以寫一個接口,來繼承于這個Repository,@NoRepositoryBean
public interface ElasticsearchRepository<T, ID extends Serializable> extends ElasticsearchCrudRepository<T, ID> {<S extends T> S index(S entity);Iterable<T> search(QueryBuilder query);Page<T> search(QueryBuilder query, Pageable pageable);Page<T> search(SearchQuery searchQuery);Page<T> searchSimilar(T entity, String[] fields, Pageable pageable);void refresh();Class<T> getEntityClass();
}ES的增刪改查操作,我們的接口就會有相關的方法,比如這個方法有索引,我們ES中存數據,還有搜索等等,我們可以用這種編程方式,我們可以編寫ElasticsearchRepository這個的子接口,來操作ES,這就是類似JPA的操作方式一樣,這兩種技術,我們先來測Jest,SpringData我們稍后來測,我先把SpringData先注掉,springdata來操作的我們先注掉,<!--SpringBoot默認使用SpringData ElasticSearch模塊進行操作-->
<!-- <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency> -->我們來導入jest<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency><groupId>io.searchbox</groupId><artifactId>jest</artifactId><version>5.3.3</version>
</dependency>我們先來看JestAutoConfiguration,protected HttpClientConfig createHttpClientConfig() {HttpClientConfig.Builder builder = new HttpClientConfig.Builder(this.properties.getUris());if (StringUtils.hasText(this.properties.getUsername())) {builder.defaultCredentials(this.properties.getUsername(),this.properties.getPassword());}String proxyHost = this.properties.getProxy().getHost();if (StringUtils.hasText(proxyHost)) {Integer proxyPort = this.properties.getProxy().getPort();Assert.notNull(proxyPort, "Proxy port must not be null");builder.proxy(new HttpHost(proxyHost, proxyPort));}Gson gson = this.gsonProvider.getIfUnique();if (gson != null) {builder.gson(gson);}builder.multiThreaded(this.properties.isMultiThreaded());builder.connTimeout(this.properties.getConnectionTimeout()).readTimeout(this.properties.getReadTimeout());customize(builder);return builder.build();
}
比如用戶名,密碼,重要的是uris,@ConfigurationProperties(prefix = "spring.elasticsearch.jest")
public class JestProperties {/*** Comma-separated list of the Elasticsearch instances to use.*/private List<String> uris = new ArrayList<String>(Collections.singletonList("http://localhost:9200"));我們是遠程主機的,我們只需要配置spring.elasticsearch.jest.uris=http://59.110.158.145:9200我們先來看有沒有啟動報錯,打印連接池已經連接到9200端口了
我們給ES中保存索引,也就是保存工作,一個文檔,我們寫一個bean類,叫Article,我們要索引一篇文章,這個文章有文章的id,來寫一個Integer,還有作者,還有文章的標題,還有文章的內容,我們還要給id字段加一個id注解,來標識這是一個主鍵
package com.learn.bean;import io.searchbox.annotations.JestId;public class Article {@JestIdprivate Integer id;private String author;private String title;private String 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;}@Overridepublic String toString() {return "Article [id=" + id + ", author=" + author + ", title=" + title + ", content=" + content + "]";}}
如何將Article保存在ES中呢,比如我們new了一個Article,我們把它創建出來,我們來設置上他的屬性,這是我們的一個文章,如何給ES中保存呢,非常簡單,我們Jest里面有一個對象,new一個Index,里面的buider,我們要指定一個索引位置,比如我們把他保存在china,類型是什么呢,我們也來繼續指定,type來指定類型,比如news都是一些新聞,保存完我們還可以指定一個id,這個id是什么呢,我們把這幾個寫好了以后呢,我們接下來點一個build構建,這是我們一個index索引,構建一個索引功能,然后就來執行,指定的時候可能會拋異常,同樣的位置try catch一下,這是我們接下來執行,那我們來測試一下能不能run,我們發現執行成功,控制臺也沒有報錯,我們來查詢一下,我們有一個索引叫china,我們找news/159.110.158.145:9200/china/news/1
package com.learn.springboot;import java.io.IOException;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 com.learn.bean.Article;import io.searchbox.client.JestClient;
import io.searchbox.core.Index;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootAmqpApplicationTests {@AutowiredJestClient jestClient;@Testpublic void contextLoads() {// 1.給ES中索引(保存)一個文檔Article article = new Article();article.setId(1);article.setTitle("好消息");article.setAuthor("zhangshan");article.setContent("Hello World");// 構建一個索引功能Index index = new Index.Builder(article).index("china").type("news").build();try {// 執行jestClient.execute(index);} catch (IOException e) {e.printStackTrace();} }
}
我們發現查到了1號的新聞,我們再來嘗試一下搜索,使用Jest來進行搜索,我們就以全文搜索為例,這個搜索我們怎么做呢,還是一樣,我們這個搜索還是非常簡單,Build里面就是查詢表達式,我們把JSON直接復制來,指定在哪個索引下搜索,我們在china這個索引下,我們在哪個類型下搜,我們來添加一個news,我們都在這兒搜,然后選一個build,搜索操作我們來構建出來,那么構建出來以后呢,還是一樣,用JestClient來執行就行了,把這個搜索放進來,執行完以后會返回一個SearchResult,拿到result給大家輸出一下,這里列出了非常多的方法,比如獲得命中的記錄,轉成需要的類型,而且還可以獲取相關性的最高得分,總記錄數,把它的字符串打印一下就行了{"took":5,
"timed_out":false,
"_shards":{"total":5,"successful":5,"failed":0},
"hits":{"total":1,"max_score":0.19178301,
"hits":[{"_index":"china","_type":"news",
"_id":"1","_score":0.19178301,
"_source":{"id":1,"author":"zhangshan","title":"好消息","content":"Hello World"}}]}}
package com.learn.springboot;import java.io.IOException;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 com.learn.bean.Article;import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.Search.Builder;
import io.searchbox.core.SearchResult;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootAmqpApplicationTests {@AutowiredJestClient jestClient;@Testpublic void contextLoads() {// 1.給ES中索引(保存)一個文檔Article article = new Article();article.setId(1);article.setTitle("好消息");article.setAuthor("zhangshan");article.setContent("Hello World");// 構建一個索引功能Index index = new Index.Builder(article).index("china").type("news").build();try {// 執行jestClient.execute(index);} catch (IOException e) {e.printStackTrace();} }@Testpublic void search() {// 查詢表達式String json = "{\r\n" + " \"query\": {\r\n" + " \"match\": {\r\n" + " \"content\": \"hello\"\r\n" + " }\r\n" + " }\r\n" + "}";// 構建搜索功能Search search = new Search.Builder(json).addIndex("china").addType("news").build();try {SearchResult result = jestClient.execute(search);System.out.println(result.getJsonString());} catch (IOException e) {e.printStackTrace();}}
}
?
總結
以上是生活随笔為你收集整理的SpringBoot高级-检索-SpringBoot整合Jest操作ES的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 尚硅谷-SpringBoot高级-检索-
- 下一篇: SpringBoot-高级-检索-整合S