• Elasticsearch (ES) (上万字)详细学习总结


    一、认识ES

    二、ES相关安装和部署(elasticsearch 、kbana、ik)

    这部分的内容可以查看我之前写的Docker常用部署这篇文章

    三、Mapping映射

    3.1 Mapping映射属性

    3.2 索引库操作 

    3.2.1 遵循Restful规范说明

    3.2.2 具体使用方式说明 

     3.2.3增删改查示例

    1. #创建
    2. PUT /heima
    3. {
    4. "mappings":{
    5. "properties": {
    6. "info":{
    7. "type": "text",
    8. "analyzer": "ik_smart"
    9. },
    10. "email": {
    11. "type": "keyword",
    12. "index": false
    13. },
    14. "name": {
    15. "type": "object",
    16. "properties": {
    17. "firstName":{
    18. "type": "keyword"
    19. },
    20. "lastName": {
    21. "type": "keyword"
    22. }
    23. }
    24. }
    25. }
    26. }
    27. }
    28. #查询
    29. GET /heima
    30. #删除
    31. DELETE /heima
    32. #添加
    33. PUT /heima/_mapping
    34. {
    35. "properties":{
    36. "age":{
    37. "type":"byte"
    38. }
    39. }
    40. }

    3.2.4 总结

    3.3 文档的操作

    3.3.1 文档的增删改查示例

    1. #新增文档(如果已经存在则进行修改)
    2. POST /heima/_doc/1
    3. {
    4. "info": "Java入门到精通",
    5. "email": "csh@qq.com",
    6. "name": {
    7. "firstName": "云",
    8. "lastName": "赵"
    9. }
    10. }
    11. #查询文档
    12. GET /heima/_doc/1
    13. #删除文档
    14. DELETE /heima/_doc/1
    15. #全量修改(直接覆盖之前的文档,如果不存在该文档则会创建新的文档)
    16. PUT /heima/_doc/1
    17. {
    18. "info": "Python入门到精通",
    19. "email": "csh@163.com",
    20. "name": {
    21. "firstName": "白",
    22. "lastName": "李"
    23. }
    24. }
    25. #增量修改(局部修改)
    26. POST /heima/_update/1
    27. {
    28. "doc":{
    29. "email":"333@163.com"
    30. }
    31. }

    3.3.2 文档批量处理

    1. #批量添加
    2. POST /_bulk
    3. {"index": {"_index" : "heima" , "_id":1}}
    4. {"info":"Java入门到精通","email":"csh@qq.com","name":{"firstName": "云","lastName": "赵"}}
    5. {"index": {"_index" : "heima" , "_id":2}}
    6. {"info":"Python入门到精通","email":"csh@163.com","name":{"firstName": "白","lastName": "李"}}
    7. #批量删除
    8. POST /heima/_bulk
    9. {"delete": {"_index" : "heima" , "_id":1}}
    10. {"delete": {"_index" : "heima" , "_id":2}}

    3.3.3 总结

    四、JavaRestClient(索引库)

    4.1 客户端初始化

     第一步:

    引入依赖:

    1. <dependency>
    2. <groupId>org.elasticsearch.client</groupId>
    3. <artifactId>elasticsearch-rest-high-level-client</artifactId>
    4. </dependency>

    第二步:

    在Spring-boot-dependency中找出7.17.0

    将其复制在父工程的中修改版本号好为7.12.1(可根据自己所需要的版本进行修改

    第三步:通过RestHighLevelClient使用ES

    建立ES连接示例:
     

    1. package com.etc.search;
    2. import org.apache.http.HttpHost;
    3. import org.elasticsearch.client.RestClient;
    4. import org.elasticsearch.client.RestHighLevelClient;
    5. import org.junit.jupiter.api.AfterEach;
    6. import org.junit.jupiter.api.BeforeEach;
    7. import org.junit.jupiter.api.Test;
    8. import org.springframework.boot.test.context.SpringBootTest;
    9. import java.io.IOException;
    10. @SpringBootTest
    11. class TripSearchApplicationTests {
    12. private RestHighLevelClient client;
    13. @Test
    14. void testConnection() {
    15. System.out.println("client: "+client);
    16. }
    17. @BeforeEach
    18. void setUp(){
    19. client = new RestHighLevelClient(RestClient.builder(
    20. HttpHost.create("http://192.168.92.136:9200")
    21. ));
    22. }
    23. @AfterEach
    24. void tearDown() throws IOException{
    25. if(client != null){
    26. client.close();
    27. }
    28. }
    29. }

    4.2 商品映射Mapping

     kibana创建示例:

    1. PUT /item
    2. {
    3. "mappings": {
    4. "properties": {
    5. "id":{
    6. "type": "keyword"
    7. },
    8. "name":{
    9. "type": "text",
    10. "analyzer": "ik_smart"
    11. },
    12. "price":{
    13. "type": "integer"
    14. },
    15. "image":{
    16. "type": "keyword",
    17. "index": false
    18. },
    19. "category":{
    20. "type":"keyword"
    21. },
    22. "brand":{
    23. "type": "keyword"
    24. },
    25. "sold":{
    26. "type": "integer"
    27. },
    28. "commentCount":{
    29. "type": "integer",
    30. "index": false
    31. },
    32. "isAD":{
    33. "type": "boolean"
    34. },
    35. "updateTime":{
    36. "type": "date"
    37. }
    38. }
    39. }
    40. }

    4.3 使用Java客户端示例:

    1. package com.etc.search;
    2. import org.apache.http.HttpHost;
    3. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
    4. import org.elasticsearch.client.RequestOptions;
    5. import org.elasticsearch.client.RestClient;
    6. import org.elasticsearch.client.RestHighLevelClient;
    7. import org.elasticsearch.client.indices.CreateIndexRequest;
    8. import org.elasticsearch.client.indices.GetIndexRequest;
    9. import org.elasticsearch.common.xcontent.XContentType;
    10. import org.junit.jupiter.api.AfterEach;
    11. import org.junit.jupiter.api.BeforeEach;
    12. import org.junit.jupiter.api.Test;
    13. import org.springframework.boot.test.context.SpringBootTest;
    14. import org.springframework.web.bind.annotation.DeleteMapping;
    15. import java.io.IOException;
    16. @SpringBootTest
    17. class TripSearchApplicationTests {
    18. private RestHighLevelClient client;
    19. @Test
    20. void testConnection() {
    21. System.out.println("client: "+client);
    22. }
    23. @Test
    24. void testCreateIndex() throws IOException{
    25. CreateIndexRequest request = new CreateIndexRequest("items");
    26. request.source(MAPPING_TEMPLATE, XContentType.JSON);
    27. client.indices().create(request, RequestOptions.DEFAULT);
    28. }
    29. @Test
    30. void testGetIndex() throws IOException{
    31. GetIndexRequest request = new GetIndexRequest("items");
    32. boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    33. System.out.println("exists:"+exists);
    34. }
    35. @Test
    36. void testDeleteIndex() throws IOException{
    37. DeleteIndexRequest request = new DeleteIndexRequest("items");
    38. client.indices().delete(request, RequestOptions.DEFAULT);
    39. }
    40. @BeforeEach
    41. void setUp(){
    42. client = new RestHighLevelClient(RestClient.builder(
    43. HttpHost.create("http://192.168.92.136:9200")
    44. ));
    45. }
    46. @AfterEach
    47. void tearDown() throws IOException{
    48. if(client != null){
    49. client.close();
    50. }
    51. }
    52. private static final String MAPPING_TEMPLATE = "{\n" +
    53. " \"mappings\": {\n" +
    54. " \"properties\": {\n" +
    55. " \"id\":{\n" +
    56. " \"type\": \"keyword\"\n" +
    57. " },\n" +
    58. " \"name\":{\n" +
    59. " \"type\": \"text\",\n" +
    60. " \"analyzer\": \"ik_smart\"\n" +
    61. " },\n" +
    62. " \"price\":{\n" +
    63. " \"type\": \"integer\"\n" +
    64. " },\n" +
    65. " \"image\":{\n" +
    66. " \"type\": \"keyword\",\n" +
    67. " \"index\": false\n" +
    68. " },\n" +
    69. " \"category\":{\n" +
    70. " \"type\":\"keyword\"\n" +
    71. " },\n" +
    72. " \"brand\":{\n" +
    73. " \"type\": \"keyword\"\n" +
    74. " },\n" +
    75. " \"sold\":{\n" +
    76. " \"type\": \"integer\"\n" +
    77. " },\n" +
    78. " \"commentCount\":{\n" +
    79. " \"type\": \"integer\",\n" +
    80. " \"index\": false\n" +
    81. " },\n" +
    82. " \"isAD\":{\n" +
    83. " \"type\": \"boolean\"\n" +
    84. " },\n" +
    85. " \"updateTime\":{\n" +
    86. " \"type\": \"date\"\n" +
    87. " }\n" +
    88. " }\n" +
    89. " }\n" +
    90. "}";
    91. }

    4.4 总结

    五、JavaRestClient(文档)

    5.1 使用Java客户端示例:

     示例代码:

    1. package com.etc.search;
    2. import org.apache.http.HttpHost;
    3. import org.bouncycastle.cert.ocsp.Req;
    4. import org.elasticsearch.action.delete.DeleteRequest;
    5. import org.elasticsearch.action.get.GetRequest;
    6. import org.elasticsearch.action.get.GetResponse;
    7. import org.elasticsearch.action.index.IndexRequest;
    8. import org.elasticsearch.action.update.UpdateRequest;
    9. import org.elasticsearch.client.RequestOptions;
    10. import org.elasticsearch.client.RestClient;
    11. import org.elasticsearch.client.RestHighLevelClient;
    12. import org.elasticsearch.common.xcontent.XContentType;
    13. import org.junit.jupiter.api.AfterEach;
    14. import org.junit.jupiter.api.BeforeEach;
    15. import org.junit.jupiter.api.Test;
    16. import org.springframework.boot.test.context.SpringBootTest;
    17. import java.io.IOException;
    18. @SpringBootTest
    19. class TripSearchApplicationTests {
    20. private RestHighLevelClient client;
    21. @Test
    22. void testConnection() {
    23. System.out.println("client: "+client);
    24. }
    25. private static final String DOCUMENT_TEMPLATE = "{\n" +
    26. " \"id\":\"1\",\n" +
    27. " \"name\":\"csh\",\n" +
    28. " \"price\":\"11\"\n" +
    29. "}";
    30. @Test
    31. void testCreateDocument() throws IOException{
    32. IndexRequest request = new IndexRequest("items").id("1");
    33. request.source(DOCUMENT_TEMPLATE,XContentType.JSON);
    34. client.index(request,RequestOptions.DEFAULT);
    35. }
    36. @Test
    37. void testDeleteDocument() throws IOException{
    38. DeleteRequest request = new DeleteRequest("items","1");
    39. client.delete(request,RequestOptions.DEFAULT);
    40. }
    41. @Test
    42. void testGetDocument() throws IOException{
    43. GetRequest request = new GetRequest("items","1");
    44. GetResponse response = client.get(request, RequestOptions.DEFAULT);
    45. String json = response.getSourceAsString();
    46. System.out.println(json);
    47. }
    48. @Test
    49. void testUpdateDocument() throws IOException{
    50. UpdateRequest request = new UpdateRequest("items","1");
    51. request.doc(
    52. "name","csh2024",
    53. "price",2024
    54. );
    55. client.update(request,RequestOptions.DEFAULT);
    56. }
    57. @BeforeEach
    58. void setUp(){
    59. client = new RestHighLevelClient(RestClient.builder(
    60. HttpHost.create("http://192.168.92.136:9200")
    61. ));
    62. }
    63. @AfterEach
    64. void tearDown() throws IOException{
    65. if(client != null){
    66. client.close();
    67. }
    68. }
    69. }

    5.2 文档批量操作

    5.3 总结:

     

     六、DSL查询

    6.1 DSL查询介绍

    6.2 DSL查询所有 

    6.3 DSL叶子查询

     match查询单个字段,需要更改key和value的值,而multi_match查询多个字段,key值无需改变。

    6.4 复合查询

    6.4.1 复合查询的bool查询

     6.4.2 复合查询的排序和分页

     示例:先按照销量降序排列,若销量一直则按升序排列

    1. GET /items/_search
    2. {
    3. "query": {
    4. "match_all": {}
    5. },
    6. "sort": [
    7. {
    8. "sold": {
    9. "order": "desc"
    10. },
    11. "price": {
    12. "order": "asc"
    13. }
    14. }
    15. ]
    16. }

     

    from的计算公式:(页数-1)*页条;

    ES对from和size进行限制,两者相加不能超过10000 

     6.5 高亮

    6.6 搜索总结

    七、JavaRestClient (搜索)

    7.1 查询所有

    示例:查询所有(match_all)

    1. package com.etc.search;
    2. import org.apache.http.HttpHost;
    3. import org.elasticsearch.action.search.SearchRequest;
    4. import org.elasticsearch.action.search.SearchResponse;
    5. import org.elasticsearch.client.RequestOptions;
    6. import org.elasticsearch.client.RestClient;
    7. import org.elasticsearch.client.RestHighLevelClient;
    8. import org.elasticsearch.index.query.QueryBuilders;
    9. import org.junit.jupiter.api.AfterEach;
    10. import org.junit.jupiter.api.BeforeEach;
    11. import org.junit.jupiter.api.Test;
    12. import org.springframework.boot.test.context.SpringBootTest;
    13. import java.io.IOException;
    14. @SpringBootTest
    15. class TripSearchApplicationTests {
    16. private RestHighLevelClient client;
    17. @Test
    18. void testMatchAll() throws IOException{
    19. SearchRequest request = new SearchRequest("items");
    20. request.source()
    21. .query(QueryBuilders.matchAllQuery());
    22. SearchResponse response = client.search(request,RequestOptions.DEFAULT);
    23. System.out.println("response = "+ response);
    24. }
    25. @BeforeEach
    26. void setUp(){
    27. client = new RestHighLevelClient(RestClient.builder(
    28. HttpHost.create("http://192.168.92.136:9200")
    29. ));
    30. }
    31. @AfterEach
    32. void tearDown() throws IOException{
    33. if(client != null){
    34. client.close();
    35. }
    36. }
    37. }

    7.2 解析查询结果

    7.3 构建查询条件

     7.3.1 构建查询条件(matchQuery,multiMatchQuery)

      7.3.2 构建查询条件(termQuery,rangeQuery) 

      7.3.3 构建查询条件(bool查询)  

       示例:使用JavaRestClient实现以下的搜索:

    • 搜索关键字为脱脂牛奶
    • 品牌为德亚
    • 价格必须低于300

    代码:

    1. package com.etc.search;
    2. import net.minidev.json.JSONUtil;
    3. import org.apache.http.HttpHost;
    4. import org.elasticsearch.action.search.SearchRequest;
    5. import org.elasticsearch.action.search.SearchResponse;
    6. import org.elasticsearch.client.RequestOptions;
    7. import org.elasticsearch.client.RestClient;
    8. import org.elasticsearch.client.RestHighLevelClient;
    9. import org.elasticsearch.index.query.QueryBuilders;
    10. import org.elasticsearch.search.SearchHit;
    11. import org.elasticsearch.search.SearchHits;
    12. import org.junit.jupiter.api.AfterEach;
    13. import org.junit.jupiter.api.BeforeEach;
    14. import org.junit.jupiter.api.Test;
    15. import org.springframework.boot.test.context.SpringBootTest;
    16. import java.io.IOException;
    17. @SpringBootTest
    18. class TripSearchApplicationTests {
    19. private RestHighLevelClient client;
    20. @Test
    21. void testSearch() throws IOException{
    22. SearchRequest request = new SearchRequest("items");
    23. request.source()
    24. .query(QueryBuilders.boolQuery()
    25. .must(QueryBuilders.matchQuery("name","脱脂牛奶"))
    26. .filter(QueryBuilders.termQuery("brand","德亚"))
    27. .filter(QueryBuilders.rangeQuery("price").lt(300)));
    28. SearchResponse response = client.search(request,RequestOptions.DEFAULT);
    29. parseResponseResult(response);
    30. }
    31. private static void parseResponseResult(SearchResponse response) {
    32. //总条数
    33. SearchHits searchHits = response.getHits();
    34. long total = searchHits.getTotalHits().value;
    35. System.out.println("total = "+total);
    36. //命中条数
    37. SearchHit[] hits = searchHits.getHits();
    38. for (SearchHit hit: hits){
    39. String json = hit.getSourceAsString();
    40. System.out.println("doc = "+ json);
    41. }
    42. }
    43. @BeforeEach
    44. void setUp(){
    45. client = new RestHighLevelClient(RestClient.builder(
    46. HttpHost.create("http://192.168.92.136:9200")
    47. ));
    48. }
    49. @AfterEach
    50. void tearDown() throws IOException{
    51. if(client != null){
    52. client.close();
    53. }
    54. }
    55. }

      7.3.4 排序和分页

    7.4 高亮

    高亮显示结果解析

     示例:解析结果方法

    1. private static void parseResponseResult(SearchResponse response) {
    2. //总条数
    3. SearchHits searchHits = response.getHits();
    4. long total = searchHits.getTotalHits().value;
    5. System.out.println("total = "+total);
    6. //命中条数
    7. SearchHit[] hits = searchHits.getHits();
    8. for (SearchHit hit: hits){
    9. String json = hit.getSourceAsString();
    10. //转换为ItemDoc
    11. ItemDoc doc = JSONUtil.toBean(json,ItemDoc.class);
    12. //处理高亮结果
    13. Map<String, HighlightField> hfs = hit.getHighlightFields();
    14. if(hfs != null && !hfs.isEmpty()){
    15. HighlightField hf = hfs.get("name");
    16. String hfName = hf.getFragments()[0].string();
    17. doc.setName(hfName);
    18. }
    19. System.out.println("doc = "+ doc);
    20. }
    21. }

    八、数据聚合

    8.1 数据聚合的介绍

    注意:参与聚合的字段必须是Keyword、数值、日期、布尔类型的字段 

    8.2 DSL聚合

     

    8.3 JavaRestClient数据聚合 

    1. package com.etc.search;
    2. import org.apache.http.HttpHost;
    3. import org.elasticsearch.action.search.SearchRequest;
    4. import org.elasticsearch.action.search.SearchResponse;
    5. import org.elasticsearch.client.RequestOptions;
    6. import org.elasticsearch.client.RestClient;
    7. import org.elasticsearch.client.RestHighLevelClient;
    8. import org.elasticsearch.search.aggregations.AggregationBuilders;
    9. import org.elasticsearch.search.aggregations.Aggregations;
    10. import org.elasticsearch.search.aggregations.bucket.terms.Terms;
    11. import org.junit.jupiter.api.AfterEach;
    12. import org.junit.jupiter.api.BeforeEach;
    13. import org.junit.jupiter.api.Test;
    14. import org.springframework.boot.test.context.SpringBootTest;
    15. import java.io.IOException;
    16. import java.util.List;
    17. import java.util.Map;
    18. @SpringBootTest
    19. class TripSearchApplicationTests {
    20. private RestHighLevelClient client;
    21. @Test
    22. void testAgg() throws IOException{
    23. SearchRequest request = new SearchRequest("items");
    24. request.source().size(0);
    25. String brandAggName = "brandAgg";
    26. request.source().aggregation(
    27. AggregationBuilders.terms(brandAggName).field("brand").size(10)
    28. );
    29. SearchResponse response = client.search(request,RequestOptions.DEFAULT);
    30. Aggregations aggregations = response.getAggregations();
    31. Terms brandTerms = aggregations.get(brandAggName);
    32. Listextends Terms.Bucket> buckets = brandTerms.getBuckets();
    33. for (Terms.Bucket bucket :buckets){
    34. System.out.println("brand: "+bucket.getKeyAsString());
    35. System.out.println("count: "+bucket.getDocCount());
    36. }
    37. }
    38. @BeforeEach
    39. void setUp(){
    40. client = new RestHighLevelClient(RestClient.builder(
    41. HttpHost.create("http://192.168.92.136:9200")
    42. ));
    43. }
    44. @AfterEach
    45. void tearDown() throws IOException{
    46. if(client != null){
    47. client.close();
    48. }
    49. }
    50. }

  • 相关阅读:
    列表按绝对值逆序排序,并保存下标 python
    C++第十单元 查找与检索10.1 顺序查找10.2 二分查找
    Visual Studio Community快速入门
    低代码-业务流程引擎
    机器学习的安全及隐私保护研究
    ABAP 设置开票后不允许修改采购订单价格
    【Electron】Not allowed to load local resource
    理科生的人生感悟-02-别忘了别人的痛苦 - 丰收之歌和围墙外的稻田
    基于51单片机智能恒温箱控制系统Proteus仿真
    JAVA计算机毕业设计宠物购物系统Mybatis+系统+数据库+调试部署
  • 原文地址:https://blog.csdn.net/qq_69183322/article/details/139047704