ToB企服应用市场:ToB评测及商务社交产业平台

标题: ES(Elasticsearch)的根本使用 [打印本页]

作者: 飞不高    时间: 2024-7-18 21:25
标题: ES(Elasticsearch)的根本使用
一、常见的NoSQL办理方案

1、redis

Redis是一个基于内存的 key-value 结构数据库。Redis是一款采用key-value数据存储格式的内存级NoSQL数据库,重点关注数据存储格式,是key-value格式,也就是键值对的存储情势。与MySQL数据库差别,MySQL数据库有表、有字段、有记载,Redis没有这些东西,就是一个名称对应一个值,并且数据以存储在内存中使用为主。redis的根本使用
2、mongodb

3、ES(Elasticsearch)

二、ES的使用

ES简介

全文搜刮

ES的应用场景

Es的windows版安装

ES的基础操作

ES的基础操作-----索引操作

不具备分词结果的索引的创建(没有指定分词器)

创建索引:注意这里使用的哀求方式是put而不是post

获取索引

获取无分词器的索引返回的信息:
  1. {
  2.     "book": {
  3.         "aliases": {},
  4.         "mappings": {},
  5.         "settings": {
  6.             "index": {
  7.                 "routing": {
  8.                     "allocation": {
  9.                         "include": {
  10.                             "_tier_preference": "data_content"
  11.                         }
  12.                     }
  13.                 },
  14.                 "number_of_shards": "1",
  15.                 "provided_name": "book",
  16.                 "creation_date": "1704103713618",
  17.                 "number_of_replicas": "1",
  18.                 "uuid": "1mabgD9eR7WvHVZeCBfVqw",
  19.                 "version": {
  20.                     "created": "7160299"
  21.                 }
  22.             }
  23.         }
  24.     }
  25. }
复制代码
删除索引

利用分词器进行创建索引(创建索引并指定分词器)

创建带分词器的索引:创建索引并指定规则

参数数据如下:
  1. {
  2.     "mappings":{        //mapping表示:定义mappings属性,替换创建索引时对应的mappings属性
  3.         "properties":{  // properties表示:定义索引中包含的属性设置(属性是自定义的)
  4.             "id":{       // 设置索引中包含id属性(相当于数据库表中创建一个id字段)
  5.                 "type":"keyword"    //设置当前属性为关键字,可以被直接搜索
  6.             },
  7.             "name":{             // 设置索引中包含name属性
  8.                 "type":"text",      //设置当前属性是文本信息,参与分词
  9.                 "analyzer":"ik_max_word",  //选择当前属性的分词策略,这里表示使用IK分词器进行分词   
  10.                 "copy_to":"all" // 表示把分词结果拷贝到all属性中,即all属性中也有name属性同样的作用
  11.             },
  12.             "type":{
  13.                 "type":"keyword"
  14.             },
  15.             "description":{
  16.                 "type":"text",
  17.                 "analyzer":"ik_max_word",
  18.                 "copy_to":"all"
  19.             },
  20.             "all":{  //all是一个定义属性(虚拟的属性,数据库中不存在的属性),用来描述多个字段的分词结果集合,当前属性可以参与查询
  21.                 "type":"text",
  22.                 "analyzer":"ik_max_word"
  23.             }
  24.         }
  25.     }
  26. }
复制代码
查询带分词器的索引

返回值:(与前面的查询不带分词器的相比,会发现mappings里面多了许多数据信息)
  1. {
  2.     "books": {
  3.         "aliases": {},
  4.         "mappings": {   //mappings属性已经被替换
  5.             "properties": {
  6.                 "all": {
  7.                     "type": "text",
  8.                     "analyzer": "ik_max_word"
  9.                 },
  10.                 "description": {
  11.                     "type": "text",
  12.                     "copy_to": [
  13.                         "all"
  14.                     ],
  15.                     "analyzer": "ik_max_word"
  16.                 },
  17.                 "id": {
  18.                     "type": "keyword"
  19.                 },
  20.                 "name": {
  21.                     "type": "text",
  22.                     "copy_to": [
  23.                         "all"
  24.                     ],
  25.                     "analyzer": "ik_max_word"
  26.                 },
  27.                 "type": {
  28.                     "type": "keyword"
  29.                 }
  30.             }
  31.         },
  32.         "settings": {
  33.             "index": {
  34.                 "routing": {
  35.                     "allocation": {
  36.                         "include": {
  37.                             "_tier_preference": "data_content"
  38.                         }
  39.                     }
  40.                 },
  41.                 "number_of_shards": "1",
  42.                 "provided_name": "books",
  43.                 "creation_date": "1704103876876",
  44.                 "number_of_replicas": "1",
  45.                 "uuid": "nQ2Jmml6QSOGwOI2cswwJw",
  46.                 "version": {
  47.                     "created": "7160299"
  48.                 }
  49.             }
  50.         }
  51.     }
  52. }
复制代码
ES的基础操作-----文档操作

添加文档:

  1. POST请求        http://localhost:9200/books/_doc                #使用系统生成id(自动帮你创建)
  2. POST请求        http://localhost:9200/books/_doc/1                  #使用指定id,不存在创建,存在更新(版本递增)
  3. POST请求        http://localhost:9200/books/_create/1           #使用指定id(必须指定id)
复制代码
传参数据一般不使用id属性:由于指定了也不访问效,要么默认帮你创建,要么在哀求路径上进行指定
参数的使用:
  1. {
  2.     "id": 1,  //一般不使用这一行
  3.     "name": "springboot1",
  4.     "type": "book",
  5.     "desctiption": "an book"
  6. }
复制代码
第一种哀求方式:

返回结果:
  1. {
  2.     "_index": "books",
  3.     "_type": "_doc",
  4.     "_id": "MgeZxIwB35gR6M6IUssu",
  5.     "_version": 1,
  6.     "result": "created",
  7.     "_shards": {
  8.         "total": 2,
  9.         "successful": 1,
  10.         "failed": 0
  11.     },
  12.     "_seq_no": 1,
  13.     "_primary_term": 1
  14. }
复制代码
第二种哀求方式:

返回结果:
  1. {
  2.     "_index": "books",
  3.     "_type": "_doc",
  4.     "_id": "55",
  5.     "_version": 1,
  6.     "result": "created",
  7.     "_shards": {
  8.         "total": 2,
  9.         "successful": 1,
  10.         "failed": 0
  11.     },
  12.     "_seq_no": 2,
  13.     "_primary_term": 1
  14. }
复制代码
第三种哀求方式:

返回结果:
  1. {
  2.     "_index": "books",
  3.     "_type": "_doc",
  4.     "_id": "1",
  5.     "_version": 1,
  6.     "result": "created",
  7.     "_shards": {
  8.         "total": 2,
  9.         "successful": 1,
  10.         "failed": 0
  11.     },
  12.     "_seq_no": 0,
  13.     "_primary_term": 1
  14. }
复制代码
获取文档


3. 根据指定条件获取某个索引的所有的文档:
  1. GET请求        http://localhost:9200/books/_search?q=name:springboot       
  2. # q=查询属性名:查询属性值
复制代码

删除文档

修改文档(分为全量更新和部分更新)

全量更新(注意这里是put哀求,以及_doc)

  1. //文档通过请求参数传递,数据格式json
  2. {
  3.     "name":"springboot",
  4.     "type":"springboot",
  5.     "description":"springboot"
  6. }
复制代码

修改文档(部分更新)注意:这里是post哀求,以及_update

  1. //文档通过请求参数传递,数据格式json
  2. {                       
  3.     "doc":{        //部分更新并不是对原始文档进行更新,而是对原始文档对象中的doc属性中的指定属性更新
  4.         "name":"springboot"                //仅更新提供的属性值,未提供的属性值不参与更新操作
  5.     }
  6. }
复制代码

三、Springboot整合ES

Springboot整合Low Level Client的ES(不保举使用了,这里了解一下)

  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  4. </dependency>
复制代码
步骤②:进行基础配置
  1. spring:
  2.   elasticsearch:
  3.     rest:
  4.       uris: http://localhost:9200
复制代码
配置ES服务器地址,端口9200(默认就是9200)
步骤③:使用springboot整合ES的专用客户端接口ElasticsearchRestTemplate来进行操作
  1. @SpringBootTest
  2. class Springboot18EsApplicationTests {
  3.     @Autowired
  4.     private ElasticsearchRestTemplate template;
  5. }
复制代码
springboot测试类中的测试类的初始化方法和销毁方法的使用

  1. @SpringBootTest
  2. class Springbootests {
  3.     @BeforeEach                //在测试类中每个操作运行前运行的方法
  4.     void setUp() {
  5.        //各种操作
  6.     }
  7.     @AfterEach                //在测试类中每个操作运行后运行的方法
  8.     void tearDown() {
  9.         //各种操作
  10.     }
  11. }
复制代码
Springboot整合High Level Client的ES

  1. <dependency>
  2.     <groupId>org.elasticsearch.client</groupId>
  3.     <artifactId>elasticsearch-rest-high-level-client</artifactId>
  4. </dependency>
复制代码
这里的springboot版本为:2.5.4,es的版本为7.16.2,那时间的springboot没有整合高级别的ES,所以配置文件里不需要配置,只能写硬编码配置
步骤②:使用编程的情势设置连接的ES服务器,并获取客户端对象
步骤③:使用客户端对象操作ES,例如创建索引为索引添加文档等等操作。
ES-----创建客户端

  1. @SpringBootTest
  2. class Springboot18EsApplicationTests {
  3.          @Autowired
  4.     private BookMapper bookMapper;
  5.    
  6.     private RestHighLevelClient client;
  7.       @Test
  8.       void testCreateClient() throws IOException {
  9.       //先创建ES客户端
  10.           HttpHost host = HttpHost.create("http://localhost:9200");
  11.           RestClientBuilder builder = RestClient.builder(host);
  12.           client = new RestHighLevelClient(builder);
  13.   
  14.           client.close();
  15.       }
  16. }
复制代码
配置ES服务器地址与端口9200,记得客户端使用完毕需要手工关闭。由于当前客户端是手工维护的,因此不能通过自动装配的情势加载对象。
ES-----根据客户端创建索引

  1. @SpringBootTest
  2. class Springboot18EsApplicationTests {
  3.          @Autowired
  4.     private BookMapper bookMapper;
  5.    
  6.     private RestHighLevelClient client;
  7.       @Test
  8.       void testCreateIndex() throws IOException {
  9.       //先创建ES客户端
  10.           HttpHost host = HttpHost.create("http://localhost:9200");
  11.           RestClientBuilder builder = RestClient.builder(host);
  12.           client = new RestHighLevelClient(builder);
  13.          
  14.       //在通过ES客户端创建索引
  15.           CreateIndexRequest request = new CreateIndexRequest("books");
  16.           client.indices().create(request, RequestOptions.DEFAULT);
  17.          
  18.           client.close();
  19.       }
  20. }
复制代码
高级别客户端操作是通过发送哀求的方式完成所有操作的,ES针对各种差别的操作,设定了各式各样的哀求对象,上例中创建索引的对象是CreateIndexRequest,其他操作也会有自己专用的Request对象。
ES-----根据客户端创建索引(使用Ik分词器)

使用分词器IK:
  1. //json的参数:
  2. {
  3.     "mappings":{
  4.         "properties":{
  5.             "id":{
  6.                 "type":"keyword"
  7.             },
  8.             "name":{
  9.                 "type":"text",
  10.                 "analyzer":"ik_max_word",
  11.                 "copy_to":"all"
  12.             },
  13.             "type":{
  14.                 "type":"keyword"
  15.             },
  16.             "description":{
  17.                 "type":"text",
  18.                 "analyzer":"ik_max_word",
  19.                 "copy_to":"all"
  20.             },
  21.             "all":{
  22.                 "type":"text",
  23.                 "analyzer":"ik_max_word"
  24.             }
  25.         }
  26.     }
  27. }
复制代码
  1. @Test
  2.     void testCreateClientIndexByIk() throws IOException {
  3. //            创建客户端
  4.         HttpHost host = HttpHost.create("http://localhost:9200");
  5.         RestClientBuilder builder = RestClient.builder(host);
  6.         client = new RestHighLevelClient(builder);
  7.         CreateIndexRequest request = new CreateIndexRequest("books");
  8.         String json = "{\n" +
  9.                 "    "mappings":{\n" +
  10.                 "        "properties":{\n" +
  11.                 "            "id":{\n" +
  12.                 "                "type":"keyword"\n" +
  13.                 "            },\n" +
  14.                 "            "name":{\n" +
  15.                 "                "type":"text",\n" +
  16.                 "                "analyzer":"ik_max_word",\n" +
  17.                 "                "copy_to":"all"\n" +
  18.                 "            },\n" +
  19.                 "            "type":{\n" +
  20.                 "                "type":"keyword"\n" +
  21.                 "            },\n" +
  22.                 "            "description":{\n" +
  23.                 "                "type":"text",\n" +
  24.                 "                "analyzer":"ik_max_word",\n" +
  25.                 "                "copy_to":"all"\n" +
  26.                 "            },\n" +
  27.                 "            "all":{\n" +
  28.                 "                "type":"text",\n" +
  29.                 "                "analyzer":"ik_max_word"\n" +
  30.                 "            }\n" +
  31.                 "        }\n" +
  32.                 "    }\n" +
  33.                 "}";
  34.         //设置请求中的参数(添加分词器)
  35.         request.source(json, XContentType.JSON);
  36.         client.indices().create(request, RequestOptions.DEFAULT);
  37.         client.close();
  38.     }
复制代码
IK分词器是通过哀求参数的情势进行设置的,设置哀求参数使用request对象中的source方法进行设置,至于参数是什么,取决于你的操作种类。当哀求中需要参数时,均可使用当前情势进行参数设置。
ES-----为索引添加文档

  1. //    添加文档:
  2.     @Test
  3.     void testCreateClientIndexByIkAddData() throws IOException {
  4. //            创建客户端
  5.         HttpHost host = HttpHost.create("http://localhost:9200");
  6.         RestClientBuilder builder = RestClient.builder(host);
  7.         client = new RestHighLevelClient(builder);
  8.         
  9. //        进行添加操作,因为前面已经创建好了books索引
  10.         Book book = bookMapper.selectById(1);
  11. //        把book对象数据转换为json数据,
  12.         String json = JSON.toJSONString(book);
  13. //        指定添加的文档的id为book.getId(),需要添加文档的索引为books
  14.         IndexRequest request = new IndexRequest("books").id(book.getId().toString());
  15. //        传入数据
  16.         request.source(json,XContentType.JSON);
  17.         client.index(request,RequestOptions.DEFAULT);
  18.         client.close();
  19.     }
复制代码
添加文档使用的哀求对象是IndexRequest,与创建索引使用的哀求对象差别。
ES-----为索引批量添加文档

  1. //    批量添加
  2.     @Test
  3.     void testCreateClientIndexByIkAddBatchData() throws IOException {
  4. //            创建客户端
  5.         HttpHost host = HttpHost.create("http://localhost:9200");
  6.         RestClientBuilder builder = RestClient.builder(host);
  7.         client = new RestHighLevelClient(builder);
  8. //        进行添加操作,因为前面已经创建好了books索引
  9.         List<Book> bookList= bookMapper.selectList(null);
  10. //       BulkRequest的对象,可以将该对象理解为是一个保存request对象的容器,
  11. //       将所有的请求都初始化好后,添加到BulkRequest对象中,再使用BulkRequest对象的bulk方法,一次性执行完毕
  12.         BulkRequest bulk = new BulkRequest();
  13.         for (Book book : bookList) {
  14.             //        把book对象数据转换为json数据,
  15.             String json = JSON.toJSONString(book);
  16. //        指定添加的文档的id为book.getId(),需要添加文档的索引为books
  17.             IndexRequest request = new IndexRequest("books").id(book.getId().toString());
  18. //        传入数据
  19.             request.source(json,XContentType.JSON);
  20. //            把数据放进BulkRequest对象里面
  21.             bulk.add(request);
  22.         }
  23. //        批量执行
  24.         client.bulk(bulk,RequestOptions.DEFAULT);
  25. //        关闭客户端
  26.         client.close();
  27.     }
复制代码
批量做时,先创建一个BulkRequest的对象,可以将该对象理解为是一个保存request对象的容器,将所有的哀求都初始化好后,添加到BulkRequest对象中,再使用BulkRequest对象的bulk方法,一次性执行完毕。
ES-----查询文档

根据id查询

  1. @Test
  2.         //按id查询
  3.     void testGetById() throws IOException {
  4.         //            创建客户端
  5.         HttpHost host = HttpHost.create("http://localhost:9200");
  6.         RestClientBuilder builder = RestClient.builder(host);
  7.         client = new RestHighLevelClient(builder);
  8. //        根据id查询
  9.         GetRequest request = new GetRequest("books","1");
  10.         GetResponse response = client.get(request, RequestOptions.DEFAULT);
  11. //        获取查询到的数据中的source属性的数据
  12.         String json = response.getSourceAsString();
  13.         System.out.println(json);
  14.         client.close();
  15.     }
复制代码
条件查询

  1. @Test
  2.         //按条件查询
  3.     void testSearch() throws IOException {
  4.         //            创建客户端
  5.         HttpHost host = HttpHost.create("http://localhost:9200");
  6.         RestClientBuilder builder = RestClient.builder(host);
  7.         client = new RestHighLevelClient(builder);
  8. //
  9.         SearchRequest request = new SearchRequest("books");
  10.         //创建条件查询对象
  11.         SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  12. //        设置查询条件
  13.         searchSourceBuilder.query(QueryBuilders.termQuery("all", "spring"));
  14. //       把查询条件放进请求中
  15.         request.source(searchSourceBuilder);
  16. //        根据请求获取返回数据
  17.         SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  18. //        获取返回数据里面的hits属性(获取的具体属性,可以看上面的postman操作)
  19.         SearchHits hits = response.getHits();
  20.         for (SearchHit hit : hits) {
  21.             String source = hit.getSourceAsString();
  22.             //把json数据转换为对象
  23.             Book book = JSON.parseObject(source, Book.class);
  24.             System.out.println(book);
  25.         }
  26.     }
复制代码
Mysql与Es数据同步的实现(这里只是根本了解一下)

1、同步双写

2. 异步双写

3、基于sql抽取(定时使命)

4、基于Binlog实现同步

数据迁移工具选型


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4