• Springboot整合Elasticsearch


    一、导入依赖

    创建一个spring boot项目

    1. <dependencies>
    2. <dependency>
    3. <groupId>com.alibabagroupId>
    4. <artifactId>fastjsonartifactId>
    5. <version>1.2.78version>
    6. dependency>
    7. <dependency>
    8. <groupId>org.springframework.bootgroupId>
    9. <artifactId>spring-boot-starter-data-elasticsearchartifactId>
    10. dependency>
    11. <dependency>
    12. <groupId>org.springframework.bootgroupId>
    13. <artifactId>spring-boot-starter-webartifactId>
    14. dependency>
    15. <dependency>
    16. <groupId>mysqlgroupId>
    17. <artifactId>mysql-connector-javaartifactId>
    18. <scope>runtimescope>
    19. dependency>
    20. <dependency>
    21. <groupId>org.projectlombokgroupId>
    22. <artifactId>lombokartifactId>
    23. <optional>trueoptional>
    24. dependency>
    25. <dependency>
    26. <groupId>org.springframework.bootgroupId>
    27. <artifactId>spring-boot-starter-testartifactId>
    28. <scope>testscope>
    29. dependency>
    30. dependencies>

    二、创建一个配置类

    这个配置类是我们获取ES的工具

    1. package com.gsh.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. @Configuration
    8. public class ESConfig {
    9. //该对象可以对我们的ES进行相关的操作
    10. @Bean
    11. public RestHighLevelClient restHighLevelClient(){
    12. RestHighLevelClient client = new RestHighLevelClient(
    13. RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
    14. return client;
    15. }
    16. }

    三、ES的有关操作

    1.对索引的操作

    对索引的操作:

    es对象.indices().相关操作

    (1)创建索引

    1. @Test
    2. //创建索引
    3. void CreateIndex() throws Exception {
    4. //把该类创建的索引信息封装在该类中
    5. CreateIndexRequest createIndexRequest=new CreateIndexRequest("qy151-index");
    6. CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
    7. System.out.println(createIndexResponse);
    8. }

    (2)删除索引

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

    (3)判断该索引是否存在

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

    2.对文档的相关操作

    对文档的操作:

    es对象.直接操作

    (1)添加一个文档

    1. @Test
    2. //添加文档
    3. void addWendang() throws Exception {
    4. IndexRequest indexRequest = new IndexRequest("qy151-index");
    5. indexRequest.id("2");//指定添加文档的id不指定随机生成
    6. //指定文档的内容:String文档的json内容,XContentType :以什么格式
    7. System.out.println(indexRequest.source(JSON.toJSONString(new User("张三", 24, "郑州")), XContentType.JSON));
    8. IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
    9. System.out.println(index.getResult());
    10. }

    (2)查询/获取一个文档

    1. @Test
    2. //获取文档
    3. public void GetWendang ()throws Exception{
    4. GetRequest getRequest=new GetRequest("qy151-index");
    5. getRequest.id("1");
    6. GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
    7. //获取查询到的对象
    8. String source = documentFields.getSourceAsString();//将获取到的结果以字符串的形式
    9. User user = JSON.parseObject(source, User.class);
    10. System.out.println(user);
    11. Map sourceAsMap = documentFields.getSourceAsMap();//将获取到的结果以map的形式
    12. System.out.println(sourceAsMap.get("age"));
    13. }

    (3) 查询一个文档是否存在

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

    (4)删除文档

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

    (5)修改文档

    1. @Test
    2. //修改文档
    3. void updateWendang()throws Exception{
    4. UpdateRequest updateRequest=new UpdateRequest("qy151-index","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. }

    (6)批量添加文档

    1. @Test
    2. //批量添加文档
    3. public void buckWendang()throws Exception {
    4. BulkRequest bulkRequest=new BulkRequest("qy151-index");
    5. //定义一个集合用于存放批量添加的对象
    6. List list=new ArrayList<>();
    7. list.add(new Student("1","李四","男"));
    8. list.add(new Student("2","王五","女"));
    9. list.add(new Student("3","赵六","男"));
    10. list.add(new Student("4","徐七","女"));
    11. //使用Stream流
    12. list.stream().
    13. forEach(item->bulkRequest.add(new IndexRequest().id(item.getId()).source(JSON.toJSONString(item),XContentType.JSON)));
    14. BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    15. System.out.println(bulk);
    16. }

     (7)复杂查询

    1. @Test
    2. void Search()throws Exception{
    3. SearchRequest searchRequest=new SearchRequest("qy151-index");
    4. //创建条件对象
    5. SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
    6. //精准查询
    7. TermQueryBuilder matchQuery = QueryBuilders.termQuery("name","王");
    8. searchSourceBuilder.query(matchQuery);
    9. //分页查找
    10. searchSourceBuilder.from(0);
    11. searchSourceBuilder.size(1);
    12. //排序查找,不能以名字作为条件
    13. //searchSourceBuilder.sort("age");
    14. //高量查询
    15. HighlightBuilder highlightBuilder=new HighlightBuilder();
    16. highlightBuilder.field("name");
    17. highlightBuilder.preTags("");//前面添加
    18. highlightBuilder.postTags("");//后面添加
    19. searchSourceBuilder.highlighter(highlightBuilder);
    20. searchRequest.source(searchSourceBuilder);
    21. SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
    22. //输出总条数
    23. System.out.println("总条数:"+search.getHits().getTotalHits().value);
    24. SearchHit[] hits = search.getHits().getHits();
    25. Arrays.stream(hits).forEach(iteam-> System.out.println(iteam.getSourceAsString()));
    26. //输出高量
    27. Arrays.stream(hits).forEach(iteam-> System.out.println(iteam.getHighlightFields()));
    28. System.out.println(search);
    29. }

  • 相关阅读:
    windows下安装hbase
    Kubernetes 笔记 / kubeadm / 高可用注意事项
    msf辅助模块详细操作
    为什么很多人赚不到钱?赚了钱又存不了钱呢
    【Spring面试】十、SpringBoot相关
    JavaScript——变量
    定制排序小案例
    视频剪辑SDK,实现高效的移动端视频编辑
    计算机基础知识47
    卧槽,Log4j2 再爆雷,Log4j v2.17.0 横空出世。。。
  • 原文地址:https://blog.csdn.net/Have_MonkeyG/article/details/126375105