Elastic Search和用戶端互動,可以使用很多語言來完成搜尋,如:Java、Python、Php和Go等多種語言。由于我平常使用最多的就是Java,這裡僅基本于Java語言來示範。基于Java語言可以選擇的用戶端包括RestClient、Spring Data Elasticsearch。安裝的話可以參考《Elastic Search 8.6.2叢集安裝部署》。
4.1使用RestClient【簡單介紹】
參考文檔:
https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/introduction.html
建立項目Spring Boot Web項目 es-demo,配置項目pom.xml檔案:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.study</groupId> <artifactId>es-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>es-demo</name> <description>Elastic Search Demo project for Spring Boot</description> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>8.6.2</version> </dependency> <dependency> <groupId>co.elastic.clients</groupId> <artifactId>elasticsearch-java</artifactId> <version>8.6.2</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>8.6.2</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> |
在項目的application.yml檔案中配置Elastic Search連接配接屬性。host、username和password需要分别填寫協調節點服務位址(IP位址+端口号)、使用者名、密碼。
server: port: 18000 elasticsearch: rest: host: 10.1.43.74:9200 username: elastic password: hhxxttxs123BoSs465 |
建立EsClient類并注冊到Spring容器中。
package com.study.es.component; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @Component public class EsClient { @Value("${elasticsearch.rest.host}") private String hosts; @Value("${elasticsearch.rest.username}") private String username; @Value("${elasticsearch.rest.password}") private String password; @Bean public RestClient init() { String[] hostParams = hosts.split(":"); int port = Integer.parseInt(hostParams[1]); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); RestClientBuilder builder = RestClient.builder( new HttpHost(hostParams[0], port)) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient( HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder .setDefaultCredentialsProvider(credentialsProvider); } }); return builder.build(); } } |
建立文章Service類。
package com.study.es.service; import com.study.es.component.EsClient; import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Request; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; @Service public class ArticleService { @Autowired private EsClient esClient; public String queryAll() throws IOException { Request request = new Request("GET", "/article/_search"); return EntityUtils.toString(esClient.init().performRequest(request).getEntity()); } } |
建立文章Controller類。
package com.study.es.controller; import com.study.es.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController @RequestMapping("/article") public class ArticleController { @Autowired private ArticleService articleService; @GetMapping("/queryAll") public String queryAll() throws IOException { return articleService.queryAll(); } } |
建立啟動類。
package com.study.es; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class EsDemoApplication { public static void main(String[] args) { SpringApplication.run(EsDemoApplication.class, args); } } |
通路 http://localhost:18000/article/queryAll
{ "took":4, "timed_out":false, "_shards":{ "total":1, "successful":1, "skipped":0, "failed":0 }, "hits":{ "total":{ "value":1, "relation":"eq" }, "max_score":1, "hits":[ { "_index":"article", "_id":"001", "_score":1, "_source":{ "title": "浙江...", "brief": "【浙江麗水...", "author": "黃甯", "content": "【浙江麗水:住房公積...", "readNumber": "188" } } ] } } |
4.2使用Spring Boot用戶端【重點】
參考文檔 https://spring.io/projects/spring-data-elasticsearch
Spring Data Elasticsearch是Spring Boot套件中的一個元件。緻力于提供一緻的基于Spring的資料查詢和存儲程式設計模型。Spring Data Elasticsearch封裝了建立用戶端的邏輯并與服務端保持長連接配接,讓我們不必關注于網絡連接配接問題。通過對Repository接口的自動實作,可以直接通過方法名的語義實作查詢功能。還具有OR-Mapping功能,即查詢到資料後,可以将資料直接封裝到自定義的POJO中,友善後續對資料進行加工處理。
建立項目Spring Boot Web項目 es-spring-demo,配置項目pom.xml檔案:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> |
在項目的application.yml檔案中配置Elastic Search連接配接屬性。當有多個協調節點時,可以設定uris的值為多個協調節點的服務位址,中間用逗号分隔。至此,當項目啟動時Spring Data Elasticsearch就會建立用戶端,然後連接配接ES服務端并與其保持長連接配接。
server: port: 18000 spring: elasticsearch: rest: uris: 10.1.43.74:9200,10.1.43.75:9200,10.1.43.76:9200 username: elastic password: hhxxttxs123BoSs465 |
封裝資訊文章POJO類。
package com.study.es.pojo; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "article") @Data public class ArticlePojo { //對應文檔ID @Id private String id; //标題 private String title; //摘要 private String brief; //作者 private String author; //内容 private String content; //閱讀量 private Integer readNumber; } |
建立資訊文章Repository接口。
package com.study.es.repository; import com.study.es.pojo.ArticlePojo; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface ArticleRepository extends CrudRepository<ArticlePojo, String> { Long countArticlePojoByAuthor(String author); List<ArticlePojo> findArticlePojoByAuthor(String author); ArticlePojo save(ArticlePojo articlePojo); } |
建立資訊文章Service類。
package com.study.es.service; import com.study.es.pojo.ArticlePojo; import com.study.es.repository.ArticleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ArticleService { @Autowired ArticleRepository articleRepository; public Long countByAuthor(String author) { return articleRepository.countArticlePojoByAuthor(author); } public List<ArticlePojo> queryByAuthor(String author) { return articleRepository.findArticlePojoByAuthor(author); } public ArticlePojo saveArticle(ArticlePojo articlePojo) { return articleRepository.save(articlePojo); } public void remove(String id) { articleRepository.deleteById(id); } } |
建立資訊文章Controller類。
package com.study.es.controller; import com.study.es.pojo.ArticlePojo; import com.study.es.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.List; import java.util.Random; import java.util.UUID; @RestController @RequestMapping("/article") public class ArticleController { @Autowired private ArticleService articleService; @GetMapping("/countByAuthor") public Long countByAuthor(String author) throws IOException { return articleService.countByAuthor(author); } @GetMapping("/queryByAuthor") public List<ArticlePojo> queryByAuthor(String author) throws IOException { return articleService.queryByAuthor(author); } @PostMapping("/saveArticle") public ArticlePojo saveArticle() throws IOException { ArticlePojo articlePojo = new ArticlePojo(); String uuid = UUID.randomUUID().toString(); articlePojo.setTitle("标題" + uuid); articlePojo.setBrief("摘要" + uuid); articlePojo.setAuthor("黃甯"); articlePojo.setContent("内容" + uuid); articlePojo.setReadNumber(new Random().nextInt(1000)); return articleService.saveArticle(articlePojo); } @PostMapping("/remove") public String remove(String id){ articleService.remove(id); return "It was removed"; } } |
通路 http://localhost:18000/article/queryByAuthor?author=黃甯
[ { "id":"001", "brief": "【浙江麗水...", "author": "黃甯", "content": "【浙江麗水:住房公積...", "readNumber": "188" } ] |
建立文章Controller類。
package com.study.es; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class EsSpringDemoApplication { public static void main(String[] args) { SpringApplication.run(EsSpringDemoApplication.class, args); } } |
查詢文章數量
http://localhost:18000/article/countByAuthor?author=黃甯
查詢文章清單
http://localhost:18000/article/queryByAuthor?author=黃甯
儲存文章
http://localhost:18000/article/saveArticle
删除文章
http://localhost:18000/article/remove?id=f5ubCIcBF2lPvPT87-04
#頭條創作挑戰賽#