当前位置:   article > 正文

史上最全的ElasticSearch系列之实战SpringBoot+ElasticSearch+HighLevelClient

史上最全的ElasticSearch系列之实战SpringBoot+ElasticSearch+HighLevelClient

一、什么是搜索?

百度:我们比如说想找寻任何的信息的时候,就会上百度去搜索一下,比如说找一部自己喜欢的电影,或者说找一本喜欢的书,或者找一条感兴趣的新闻(提到搜索的第一印象)。百度 != 搜索

  • 互联网的搜索:电商网站,招聘网站,新闻网站,各种app
  • IT系统的搜索:OA软件,办公自动化软件,会议管理,日程管理,项目管理。 搜索,就是在任何场景下,找寻你想要的信息,这个时候,会输入一段你要搜索的关键字,然后就期望找到这个关键字相关的有些信息

二、什么是全文检索和Lucene?

  • 全文检索,倒排索引

全文检索是指计算机索引程序通过扫描文章中的每一个词,对每一个词建立一个索引,指明该词在文章中出现的次数和位置,当用户查询时,检索程序就根据事先建立的索引进行查找,并将查找的结果反馈给用户的检索方式。这个过程类似于通过字典中的检索字表查字的过程。全文搜索搜索引擎数据库中的数据。

  • lucene

lucene,就是一个jar包,里面包含了封装好的各种建立倒排索引,以及进行搜索的代码,包括各种算法。我们就用java开发的时候,引入lucene jar,然后基于lucene的api进行去进行开发就可以了。

三、Elasticsearch是什么?

  • Elasticsearch,基于lucene.分布式的Restful实时搜索和分析引擎(实时)
  • 分布式的实时文件存储,每个字段都被索引并可被搜索
  • 高扩展性,可扩展至上百台服务器,处理PB级结构化或非结构化数据
  • Elasticsearch用于全文检索,结构化搜索,分析/合并使用

四、Elasticsearch的特性:

  • Elasticsearch没有典型意义的事务(无事务性)
  • Elasticsearch是一种面向文档的数据库
  • Elasticsearch没有提供授权和认证特性

五、Elasticsearch 可以做什么?

  • 你有一个在线网上商城,提供用户搜索你所卖的商品功能。在这个例子中,你可以使用Elasticsearch去存储你的全部的商品目录和存货清单并且提供搜索和搜索自动完成以及搜索推荐功能。
  • 你想去收集日志或者业务数据,并且去分析并从这些数据中挖掘寻找市场趋势、统计资料、摘要信息或者反常情况。在这个例子中,你可以使用Logstash(part of the Elasticsearch/Logstash/Kibana stack)去收集、聚合并且解析你的数据,然后通过Logstash将数据注入Elasticsearch。一旦数据进入Elasticsearch,你就可以运行搜索和聚集并且从中挖掘任何你感兴趣的数据。
  • 你运行一个价格预警平台,它可以让那些对价格精明的客户指定一个规则,比如:“我相中了一个电子产品,并且我想在下个月任何卖家的这个电子产品的价格低于多少钱的时候提醒我”。在这个例子中,你可以抓取所有卖家的价格,把价格放入Elasticsearch并且使用Elasticsearch的反向搜索(过滤器/抽出器)功能来匹配价格变动以应对用户的查询并最终一旦发现有匹配结果时给用户弹出提示框。
  • 你有分析学/商业情报的需求并且想快速审查、分析并使用图像化进行展示,并且在一个很大的数据集上查询点对点的问题(试想有百万或千万的记录)。在这个例子中,你可以使用Elasticsearch去存储你的数据然后使用Kibana(part of the Elasticsearch/Logstash/Kibana stack)去构建定制化的仪表盘。这样你就可以很直观形象的了解对你重要的数据。此外,你可以使用Elasticsearch的集成功能,靠你的数据去展现更加复杂的商业情报查询。

怎么说呢?其实elk 就是一个技术解决方案,可以做很多的东西。目前我们只是单单先把es入门把,他的搜索功能学会,用好。

Cluster(集群)

集群包含多个节点,每个节点属于哪个集群是通过一个配置(集群名称,默认是elasticsearch)来决定的,对于中小型应用来说,刚开始一个集群就一个节点很正常

Node(节点)

集群中的一个节点,节点也有一个名称(默认是随机分配的),节点名称很重要(在执行运维管理操作的时候),默认节点会去加入一个名称为“elasticsearch”的集群,如果直接启动一堆节点,那么它们会自动组成一个elasticsearch集群,当然一个节点也可以组成一个elasticsearch集群。

Index(索引-数据库)

索引包含一堆有相似结构的文档数据,比如可以有一个客户索引,商品分类索引,订单索引,索引有一个名称。一个index包含很多document,一个index就代表了一类类似的或者相同的document。比如说建立一个product index,商品索引,里面可能就存放了所有的商品数据,所有的商品document。

索引(index)类似于关系型数据库里的“数据库”——它是我们存储和索引关联数据的地方。
提示:

事实上,我们的数据被存储和索引在分片(shards)中,索引只是一个把一个或多个分片分组在一起的逻辑空间。然而,这只是一些内部细节——我们的程序完全不用关心分片。对于我们的程序而言,文档存储在索引(index)中。剩下的细节由Elasticsearch关心既可。 我们唯一需要做的仅仅是选择一个索引名。这个名字必须是全部小写,不能以下划线开头,不能包含逗号

Type(类型-表)

每个索引里都可以有一个或多个type,type是index中的一个逻辑数据分类,一个type下的document,都有相同的field,比如博客系统,有一个索引,可以定义用户数据type,博客数据type,评论数据type。
商品index,里面存放了所有的商品数据,商品document
但是商品分很多种类,每个种类的document的field可能不太一样,比如说电器商品,可能还包含一些诸如售后时间范围这样的特殊field;生鲜商品,还包含一些诸如生鲜保质期之类的特殊field 例如

  • 日化商品type:product_id,product_name,product_desc,category_id,category_name
  • 电器商品type:product_id,product_name,product_desc,category_id,category_name,service_period
  • 生鲜商品type:product_id,product_name,product_desc,category_id,category_name,eat_period

Document(文档-行)

文档是es中的最小数据单元,一个document可以是一条客户数据,一条商品分类数据,一条订单数据,通常用JSON数据结构表示,每个index下的type中,都可以去存储多个document。

Field(字段-列)

Field是Elasticsearch的最小单位。一个document里面有多个field,每个field就是一个数据字段。

mapping(映射-约束)

数据如何存放到索引对象上,需要有一个映射配置,包括:数据类型、是否存储、是否分词等。

这样就创建了一个名为blog的Index。Type不用单独创建,在创建Mapping 时指定就可以。Mapping用来定义Document中每个字段的类型,即所使用的 analyzer、是否索引等属性,非常关键等。创建Mapping 的代码示例如下:

  1. client.indices.putMapping({
  2.     index : 'blog',
  3.     type : 'article',
  4.     body : {
  5.         article: {
  6.             properties: {
  7.                 id: {
  8.                     type: 'string',
  9.                     analyzer: 'ik',
  10.                     store: 'yes',
  11.                 },
  12.                 title: {
  13.                     type: 'string',
  14.                     analyzer: 'ik',
  15.                     store: 'no',
  16.                 },
  17.                 content: {
  18.                     type: 'string',
  19.                     analyzer: 'ik',
  20.                     store: 'yes',
  21.                 }
  22.             }
  23.         }
  24.     }
  25. });

elasticsearch与数据库的类比

六、基本使用

  1. // 创建一个文档并且创建索引test1/user
  2. PUT /test1/user/1
  3. {
  4. "name":"程一同学",
  5. "age":6,
  6. "desc":"青年才俊精神小伙子",
  7. "tag":["直男","看电影","高颜值"]
  8. }
  9. //创建一个索引
  10. POST /test1/user
  11. {
  12. "mappings": {
  13. "properties": {
  14. "name":{
  15. "type": "text"
  16. },
  17. "age":{
  18. "type": "long"
  19. },
  20. "desc":{
  21. "type": "text"
  22. },
  23. "tag":{
  24. "type": "text"
  25. }
  26. }
  27. }
  28. }
  29. //创建一个索引
  30. POST /test1
  31. {
  32. "user":{
  33. "mappings": {
  34. "properties": {
  35. "name":{
  36. "type": "text"
  37. },
  38. "age":{
  39. "type": "long"
  40. },
  41. "desc":{
  42. "type": "text"
  43. },
  44. "tag":{
  45. "type": "text"
  46. }
  47. }
  48. }
  49. }
  50. }
  51. //获取一个文档信息
  52. GET test1/type1/1
  53. POST /test1/type1/1/_update
  54. {
  55. "doc":{
  56. "name":"李四小伙子"
  57. }
  58. }
  59. //添加文档信息
  60. PUT /test1/type1/1
  61. {
  62. "name":"王五",
  63. "age":"24",
  64. "brithday":"2023-10-31"
  65. }
  66. //删除索引
  67. DELETE /test1
  68. //获取文档信息
  69. POST /test1/type1/_search
  70. //查询文档信息
  71. GET /test1/type1/_search
  72. {
  73. "query": {
  74. "term": {
  75. "name": {
  76. "value": "程一同学"
  77. }
  78. }
  79. }
  80. }
  81. //使用高亮查询
  82. GET test1/user/_search
  83. {
  84. "query": {
  85. "match": {
  86. "name":"程一"
  87. }
  88. },
  89. "highlight": {
  90. "fields": {
  91. "name":{}
  92. }
  93. }
  94. }

1、项目结构

2、pom 文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.2.6.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.mk</groupId>
  12. <artifactId>es-api</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>es-api</name>
  15. <description>es-api</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <!--自己定义es版本依赖,保证和本地一致-->
  19. <elasticsearch.version>7.6.1</elasticsearch.version>
  20. </properties>
  21. <dependencies>
  22. <!--导入了elasticsearch-->
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-web</artifactId>
  30. <version>2.2.6.RELEASE</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-devtools</artifactId>
  35. <scope>runtime</scope>
  36. <optional>true</optional>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-configuration-processor</artifactId>
  41. <optional>true</optional>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.projectlombok</groupId>
  45. <artifactId>lombok</artifactId>
  46. <optional>true</optional>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-test</artifactId>
  51. <scope>test</scope>
  52. </dependency>
  53. <dependency>
  54. <groupId>com.alibaba</groupId>
  55. <artifactId>fastjson</artifactId>
  56. <version>2.0.32</version>
  57. </dependency>
  58. </dependencies>
  59. <build>
  60. <plugins>
  61. <plugin>
  62. <groupId>org.springframework.boot</groupId>
  63. <artifactId>spring-boot-maven-plugin</artifactId>
  64. <configuration>
  65. <excludes>
  66. <exclude>
  67. <groupId>org.projectlombok</groupId>
  68. <artifactId>lombok</artifactId>
  69. </exclude>
  70. </excludes>
  71. </configuration>
  72. </plugin>
  73. </plugins>
  74. </build>
  75. </project>

3、config 连接es的配置

  1. package com.mk.config;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. /**
  8. *
  9. * @version 1.0
  10. * @date 2023/11/2 15:10
  11. */
  12. @Configuration
  13. public class ElasticsearchConfig {
  14. @Bean
  15. public RestHighLevelClient restHighLevelClient(){
  16. RestHighLevelClient client = new RestHighLevelClient(
  17. RestClient.builder(
  18. new HttpHost("localhost",9200,"http")));
  19. return client;
  20. }
  21. }

4、创建一个实体类user

  1. package com.mk.pojo;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. *
  8. * @version 1.0
  9. * @date 2023/11/2 15:55
  10. */
  11. @Data
  12. @AllArgsConstructor
  13. @NoArgsConstructor
  14. @Component
  15. public class User {
  16. private String name;
  17. private int age;
  18. }

5、测试方法

  1. package com.mk;
  2. import com.alibaba.fastjson.JSON;
  3. import com.mk.pojo.User;
  4. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  5. import org.elasticsearch.action.bulk.BulkRequest;
  6. import org.elasticsearch.action.bulk.BulkResponse;
  7. import org.elasticsearch.action.delete.DeleteRequest;
  8. import org.elasticsearch.action.delete.DeleteResponse;
  9. import org.elasticsearch.action.get.GetRequest;
  10. import org.elasticsearch.action.get.GetResponse;
  11. import org.elasticsearch.action.index.IndexRequest;
  12. import org.elasticsearch.action.index.IndexResponse;
  13. import org.elasticsearch.action.search.SearchRequest;
  14. import org.elasticsearch.action.search.SearchResponse;
  15. import org.elasticsearch.action.support.master.AcknowledgedResponse;
  16. import org.elasticsearch.action.update.UpdateRequest;
  17. import org.elasticsearch.action.update.UpdateResponse;
  18. import org.elasticsearch.client.RequestOptions;
  19. import org.elasticsearch.client.RestHighLevelClient;
  20. import org.elasticsearch.client.indices.CreateIndexRequest;
  21. import org.elasticsearch.client.indices.CreateIndexResponse;
  22. import org.elasticsearch.client.indices.GetIndexRequest;
  23. import org.elasticsearch.common.unit.TimeValue;
  24. import org.elasticsearch.common.xcontent.XContentType;
  25. import org.elasticsearch.index.query.QueryBuilders;
  26. import org.elasticsearch.index.query.TermQueryBuilder;
  27. import org.elasticsearch.search.SearchHit;
  28. import org.elasticsearch.search.builder.SearchSourceBuilder;
  29. import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
  30. import org.junit.jupiter.api.Test;
  31. import org.springframework.beans.factory.annotation.Autowired;
  32. import org.springframework.beans.factory.annotation.Qualifier;
  33. import org.springframework.boot.test.context.SpringBootTest;
  34. import java.io.IOException;
  35. import java.util.ArrayList;
  36. import java.util.List;
  37. import java.util.concurrent.TimeUnit;
  38. /**
  39. * es7.6.x 高级客户端测试API
  40. */
  41. @SpringBootTest
  42. class EsApiApplicationTests {
  43. @Autowired
  44. @Qualifier("restHighLevelClient")
  45. private RestHighLevelClient client;
  46. //测试索引的创建
  47. @Test
  48. void testCreateIndex() throws IOException {
  49. //1、创建索引请求
  50. CreateIndexRequest request = new CreateIndexRequest("kuang_index");
  51. //2、客户端执行请求 IndicesClient,请求后获得响应
  52. CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
  53. System.out.println(createIndexResponse);
  54. }
  55. //获取一个索引
  56. @Test
  57. void testExistIndex() throws IOException {
  58. GetIndexRequest request = new GetIndexRequest("kuang_index");
  59. boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
  60. System.out.println(exists);
  61. }
  62. //删除一个索引
  63. @Test
  64. void testDeleteIndex() throws IOException {
  65. DeleteIndexRequest request = new DeleteIndexRequest("kuang_index");
  66. AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
  67. System.out.println(delete.isAcknowledged());
  68. }
  69. //测试添加文档
  70. @Test
  71. void testAddDocument() throws IOException {
  72. //1、创建对象user
  73. User user = new User("张三", 18);
  74. //2、创建请求
  75. IndexRequest request = new IndexRequest("kuang_index");
  76. //规则 PUT kuang_index/_doc/1
  77. request.id("1");
  78. request.timeout(TimeValue.timeValueSeconds(1));
  79. request.timeout("1s");
  80. //3、将我们的数据放进请求 json
  81. IndexRequest source = request.source(JSON.toJSONString(user), XContentType.JSON);
  82. //4、客户端发送请求 获取响应结果
  83. IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
  84. System.out.println(indexResponse.toString());
  85. System.out.println(indexResponse.status());
  86. }
  87. //获取文档 判断文档是否存在
  88. @Test
  89. void testIsExistDocument() throws IOException {
  90. GetRequest request = new GetRequest("kuang_index", "1");
  91. GetRequest getRequest = request.fetchSourceContext(new FetchSourceContext(false));
  92. getRequest.storedFields("_none_");
  93. boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
  94. System.out.println(exists);
  95. }
  96. // 获取文档的信息
  97. @Test
  98. void testGetDocument() throws IOException {
  99. GetRequest request = new GetRequest("kuang_index", "1");
  100. GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
  101. String source = getResponse.getSourceAsString();
  102. System.out.println(getResponse);
  103. System.out.println(source);
  104. }
  105. //更新文档的信息
  106. @Test
  107. void testUpdateDocument() throws IOException {
  108. //1、创建更新请求
  109. UpdateRequest request = new UpdateRequest("kuang_index", "1");
  110. //2、设置请求响应时间
  111. request.timeout("1s");
  112. //3、创建要修改的对象
  113. User user = new User("李四", 6);
  114. //4、将我们的数据放进请求中 json
  115. UpdateRequest updateRequest = request.doc(JSON.toJSONString(user), XContentType.JSON);
  116. //5、客户端发送请求
  117. UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
  118. System.out.println(update);
  119. System.out.println(update.status());
  120. }
  121. //删除文档信息
  122. @Test
  123. void testDeleteDocument() throws IOException {
  124. DeleteRequest request = new DeleteRequest("kuang_index", "1");
  125. request.timeout("1s");
  126. DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
  127. System.out.println(delete);
  128. System.out.println(delete.status());
  129. }
  130. //特殊情况 一般真实项目中批量插入数据
  131. @Test
  132. void testBulkDocument() throws IOException {
  133. BulkRequest request = new BulkRequest();
  134. request.timeout("10s");
  135. List<User> userList = new ArrayList<>();
  136. userList.add(new User("张三",18));
  137. userList.add(new User("李四",6));
  138. userList.add(new User("王五",20));
  139. //批量请求
  140. for (int i = 0; i < userList.size(); i++) {
  141. request.add(new IndexRequest("kuang_index")
  142. .id(""+i+1)//设置ID
  143. .type("user")//设置type
  144. .source(JSON.toJSONString(userList.get(i)),XContentType.JSON)
  145. );
  146. }
  147. BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
  148. System.out.println(bulk.hasFailures());//是否失败,FALSE表示操作成功
  149. System.out.println(bulk);
  150. }
  151. //查询文档信息
  152. @Test
  153. void testSearchDocument() throws IOException {
  154. SearchRequest request = new SearchRequest("kuang_index");
  155. // 构建搜索条件
  156. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  157. //查询条件,我们可以使用 QueryBuilder工具类来实现 注意使用name.keyword一定要加上这个keyword不然搜索不到
  158. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name.keyword", "张三");
  159. sourceBuilder.query(termQueryBuilder);
  160. sourceBuilder.timeout(new TimeValue(120, TimeUnit.SECONDS));
  161. request.source(sourceBuilder);
  162. SearchResponse search = client.search(request, RequestOptions.DEFAULT);
  163. System.out.println(JSON.toJSON(search.getHits()));
  164. System.out.println("=======================");
  165. for (SearchHit documentFields : search.getHits().getHits()) {
  166. System.out.println(documentFields.getSourceAsMap());
  167. }
  168. }
  169. // 批量更新
  170. BulkRequest bulkUpdateRequest = new BulkRequest();
  171. for (int i = 0; i < usersList.size(); i++) {
  172. users = usersList.get(i);
  173. users.setName(users.getName() + " updated");
  174. UpdateRequest updateRequest = new UpdateRequest("kuang_index", "_doc", users.getId().toString());
  175. updateRequest.doc(JSON.toJSONString(users), XContentType.JSON);
  176. bulkUpdateRequest.add(updateRequest);
  177. }
  178. BulkResponse bulkUpdateResponse = client.bulk(bulkUpdateRequest, RequestOptions.DEFAULT);
  179. System.out.println("bulkUpdate: " + JSON.toJSONString(bulkUpdateResponse));
  180. search(INDEX_TEST, TYPE_TEST, "updated");
  181. // 批量删除
  182. BulkRequest bulkDeleteRequest = new BulkRequest();
  183. for (int i = 0; i < testsList.size(); i++) {
  184. users = usersList.get(i);
  185. DeleteRequest deleteRequest = new DeleteRequest("kuang_index", "_doc", users.getId().toString());
  186. bulkDeleteRequest.add(deleteRequest);
  187. }
  188. BulkResponse bulkDeleteResponse = client.bulk(bulkDeleteRequest, RequestOptions.DEFAULT);
  189. System.out.println("bulkDelete: " + JSON.toJSONString(bulkDeleteResponse));
  190. search(INDEX_TEST, TYPE_TEST, "this");
  191. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/543402
推荐阅读
相关标签
  

闽ICP备14008679号