• Springboot整合Elasticsearch(Es)


    一. 引入依赖

    
        com.alibaba
        fastjson
        1.2.75
    
    
        org.springframework.boot
        spring-boot-starter-data-elasticsearch
    

     二. 创建ES配置类

    1. package com.lrs.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. * @创建时间 2022/8/16 16:30
    10. **/
    11. @Configuration
    12. public class EsConfig {
    13. @Bean
    14. public RestHighLevelClient restHighLevelClient(){
    15. RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
    16. return restHighLevelClient;
    17. }
    18. }

     三. 关于对文档的操作

    首先 在测试类中引入RestHighLevelClient对象

    1. @Resource
    2. private RestHighLevelClient client;

    其次 准备一个User对象

    1. package com.lrs.entity;
    2. import lombok.AllArgsConstructor;
    3. import lombok.Data;
    4. import lombok.NoArgsConstructor;
    5. /**
    6. * @作者:刘壬杉
    7. * @创建时间 2022/8/16 19:21
    8. **/
    9. @Data
    10. @AllArgsConstructor
    11. @NoArgsConstructor
    12. public class User {
    13. private String id;
    14. private String name;
    15. private String address;
    16. private Integer age;
    17. public User(String name, String address, Integer age) {
    18. this.name = name;
    19. this.address = address;
    20. this.age = age;
    21. }
    22. }

    3.1 对索引的操作

    3.1.1 创建索引

    1. //创建索引
    2. @Test
    3. void testCreateIndex() throws IOException {
    4. CreateIndexRequest createIndexRequest = new CreateIndexRequest("test04");
    5. CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
    6. System.out.println(createIndexResponse.isAcknowledged());
    7. }

     运行结果:创建成功返回true

    3.1.2 删除索引

    1. //删除索引
    2. @Test
    3. void testDeleteIndex() throws Exception{
    4. DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("test04");
    5. AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
    6. System.out.println(delete.isAcknowledged());
    7. }

    运行结果:删除成功返回true

     3.1.3 判断索引是否存在

    1. //判断索引是否存在
    2. @Test
    3. void testExistsIndex() throws Exception{
    4. GetIndexRequest getIndexRequest = new GetIndexRequest("test04");
    5. boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
    6. System.out.println(exists);
    7. }

    运行结果:存在返回true,不存在返回false.

    3.2 对文档的操作

    3.2.1 添加文档

    1. //添加文档
    2. @Test
    3. void testCreateDoc() throws Exception{
    4. IndexRequest indexRequest = new IndexRequest("test04");
    5. indexRequest.id("1");
    6. indexRequest.source(JSON.toJSONString(new User("张三","北京",25)), XContentType.JSON);
    7. IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
    8. System.out.println(index.getResult());
    9. }

    运行结果:添加成功返回 CREATED

    3.2.2 查询文档----根据id查询

    1. //查询文档 -- id
    2. @Test
    3. void testGetDoc() throws Exception{
    4. GetRequest getRequest = new GetRequest("test04");
    5. getRequest.id("1");
    6. GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
    7. System.out.println(documentFields.getSourceAsMap());
    8. }

    运行结果:

    3.2.3 判断文档是否存在

    1. //判断文档是否存在
    2. @Test
    3. void testExistsDoc() throws Exception{
    4. GetRequest getRequest = new GetRequest("test04");
    5. getRequest.id("1");
    6. boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
    7. System.out.println(exists);
    8. }

    运行结果:存在返回true,不存在返回false.

    3.2.4 删除文档

    1. //删除文档
    2. @Test
    3. void testDeleteDoc() throws Exception{
    4. DeleteRequest deleteRequest = new DeleteRequest("test04");
    5. deleteRequest.id("1");
    6. DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
    7. System.out.println(delete.getResult());
    8. }

    运行结果:删除成功返回 DELETED

    3.2.5 修改文档

    1. //修改文档
    2. @Test
    3. void testUpdateDoc() throws Exception{
    4. UpdateRequest updateRequest = new UpdateRequest("test04","1");
    5. User user = new User();
    6. user.setName("王五");
    7. updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
    8. UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
    9. System.out.println(update.getResult());
    10. }

    运行结果:修改成功返回 UPDATED

    3.2.6 批量添加文档

    1. //批量添加文档
    2. @Test
    3. void testBulk() throws Exception{
    4. BulkRequest bulkRequest = new BulkRequest("test04");
    5. List list = new ArrayList<>();
    6. list.add(new User("1","张三1","北京1",18));
    7. list.add(new User("2","张三2","北京2",19));
    8. list.add(new User("3","张三3","北京3",20));
    9. list.add(new User("4","张三4","北京4",21));
    10. list.add(new User("5","张三5","北京5",22));
    11. list.stream().forEach(item->bulkRequest.add(new IndexRequest().id(item.getId()).source(JSON.toJSONString(item),XContentType.JSON)));
    12. BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    13. System.out.println(bulk.hasFailures());
    14. }

    运行结果:     bulk.hasFailures():判断是否有故障,返回false代表没有故障,添加成功

    3.3 复杂查询

    复杂查询中包含一个条件对象,条件对象里包含了很多条件,比如 分页,高亮,排序,查询指定列,精准匹配,范围查询等等

    1. //复杂查询
    2. @Test
    3. void testSearch() throws Exception{
    4. SearchRequest searchRequest = new SearchRequest("test04");
    5. //创建条件对象
    6. SearchSourceBuilder builder = new SearchSourceBuilder();
    7. //bool
    8. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("name", "3"))
    9. .should(QueryBuilders.matchQuery("age", 20));
    10. builder.query(boolQueryBuilder);
    11. //分页
    12. builder.from(0);
    13. builder.size(2);
    14. //指定列
    15. String[] includes = {"name","address"};
    16. String[] excludes = {"id"};
    17. builder.fetchSource(includes,null);
    18. //高亮
    19. HighlightBuilder highlightBuilder = new HighlightBuilder();
    20. highlightBuilder.field("name");
    21. highlightBuilder.preTags("");
    22. highlightBuilder.postTags("");
    23. builder.highlighter(highlightBuilder);
    24. //排序
    25. builder.sort("age", SortOrder.ASC);
    26. searchRequest.source(builder);
    27. SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
    28. SearchHit[] hits = search.getHits().getHits();
    29. Arrays.stream(hits).forEach(item-> System.out.println(item.getSourceAsMap()));
    30. Arrays.stream(hits).forEach(item-> System.out.println(item.getHighlightFields()));
    31. }

    运行结果:

  • 相关阅读:
    剑指 Offer 05. 替换空格
    MapReduce & YARN 的部署
    bootstrap下拉菜单学习(五)
    Shopee开店要花多少钱?
    SpringBoot SpringBoot 运维实用篇 3 多环境开发 3.1 多环境开发【yaml版】
    Fiddle日常运用手册(3)-对移动端产品进行数据接口抓包
    Python面试题:如何在 Python 中处理大数据集?
    用HTML+CSS+JS写的切水果小游戏它来了
    【Exploit trick】利用poll_list对象构造kmalloc-32任意释放 (corCTF 2022-CoRJail)
    MATLAB绘制伪彩图和切片轮廓线图
  • 原文地址:https://blog.csdn.net/lrs998563/article/details/126373156