SpringBoot对Elasticsearch增删改查源码

准备环境:

1、JDK1.8.211以上

2、Elasticsearch6.8.6

3、Elasticsearch-analysis-ik-6.8.6  注:用来分词

4、elasticsearch-head-master   注:用来可视查询显示

5、kibana-6.8.6  注:es可视化分析

下载es及组件地址:https://elasticsearch.cn/download/

第一步:解压elasticsearch-6.8.6.tar.gz

        tar -zxvf elasticsearch-6.8.6.tar.gz

配置es下的config/elasticsearch.yml

  1. # ======================== Elasticsearch Configuration =========================
  2. #
  3. # NOTE: Elasticsearch comes with reasonable defaults for most settings.
  4. #       Before you set out to tweak and tune the configuration, make sure you
  5. #       understand what are you trying to accomplish and the consequences.
  6. #
  7. # The primary way of configuring a node is via this file. This template lists
  8. # the most important settings you may want to configure for a production cluster.
  9. #
  10. # Please consult the documentation for further information on configuration options:
  11. # https://www.elastic.co/guide/en/elasticsearch/reference/index.html
  12. #
  13. # ---------------------------------- Cluster -----------------------------------
  14. #
  15. # Use a descriptive name for your cluster:
  16. #
  17. #cluster.name: my-application
  18. #
  19. # ------------------------------------ Node ------------------------------------
  20. #
  21. # Use a descriptive name for the node:
  22. #
  23. #node.name: node-1
  24. #
  25. # Add custom attributes to the node:
  26. #
  27. #node.attr.rack: r1
  28. #
  29. # ----------------------------------- Paths ------------------------------------
  30. #
  31. # Path to directory where to store the data (separate multiple locations by comma):
  32. #
  33. #path.data: /path/to/data
  34. #
  35. # Path to log files:
  36. #
  37. #path.logs: /path/to/logs
  38. #
  39. # ----------------------------------- Memory -----------------------------------
  40. #
  41. # Lock the memory on startup:
  42. #
  43. #bootstrap.memory_lock: true
  44. #
  45. # Make sure that the heap size is set to about half the memory available
  46. # on the system and that the owner of the process is allowed to use this
  47. # limit.
  48. #
  49. # Elasticsearch performs poorly when the system is swapping the memory.
  50. #
  51. # ---------------------------------- Network -----------------------------------
  52. #
  53. # Set the bind address to a specific IP (IPv4 or IPv6):
  54. #
  55. network.host: 0.0.0.0#不要使用本IP,localhost和127.0.0.1,否则外网不能访问
  56. #
  57. # Set a custom port for HTTP:
  58. #
  59. http.port: 9200#端口号
  60. #
  61. # For more information, consult the network module documentation.
  62. #
  63. # --------------------------------- Discovery ----------------------------------
  64. #
  65. # Pass an initial list of hosts to perform discovery when new node is started:
  66. # The default list of hosts is ["127.0.0.1", "[::1]"]
  67. #
  68. #discovery.zen.ping.unicast.hosts: ["host1", "host2"]
  69. #
  70. # Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
  71. #
  72. #discovery.zen.minimum_master_nodes: 
  73. #
  74. # For more information, consult the zen discovery module documentation.
  75. #
  76. # ---------------------------------- Gateway -----------------------------------
  77. #
  78. # Block initial recovery after a full cluster restart until N nodes are started:
  79. #
  80. #gateway.recover_after_nodes: 3
  81. #
  82. # For more information, consult the gateway module documentation.
  83. #
  84. # ---------------------------------- Various -----------------------------------
  85. #
  86. # Require explicit names when deleting indices:
  87. #
  88. #action.destructive_requires_name: true
  89. http.cors.enabled: true#允许夸域访问,如head访问
  90. http.cors.allow-origin: "*"#允许夸域访问,如head访问

 

启动es:es/bin/elasticsearch

访问:http://192.168.0.104:9200出现如下即为成功

  1. {
  2.   "name" : "-cpaasX",
  3.   "cluster_name" : "elasticsearch",
  4.   "cluster_uuid" : "4P1Bir1mSAiNC1V1r7EPjg",
  5.   "version" : {
  6.     "number" : "6.8.6",
  7.     "build_flavor" : "default",
  8.     "build_type" : "tar",
  9.     "build_hash" : "3d9f765",
  10.     "build_date" : "2019-12-13T17:11:52.013738Z",
  11.     "build_snapshot" : false,
  12.     "lucene_version" : "7.7.2",
  13.     "minimum_wire_compatibility_version" : "5.6.0",
  14.     "minimum_index_compatibility_version" : "5.0.0"
  15.   },
  16.   "tagline" : "You Know, for Search"
  17. }

第二步:解压elasticsearch-analysis-ik-6.8.6.zip到es/plugins目标下

tar -zxvf elasticsearch-analysis-ik-6.8.6.zip

解压后为:es/plugins/elasticsearch-analysis-ik-6.8.6

注:es/plugins/elasticsearch-analysis-ik-6.8.6/config可自定义配置分词

重启es:es/bin/elasticsearch

第三步:解压kibana-6.8.6-darwin-x86_64.tar.gz,与elasticsearch在同一级目录

tar -zxvf kibana-6.8.6-darwin-x86_64.tar.gz

配置:kibana-6.8.6/config/kibana.yml

  1. # Kibana is served by a back end server. This setting specifies the port to use.
  2. #server.port: 5601
  3. # Specifies the address to which the Kibana server will bind. IP addresses and host names are both valid values.
  4. # The default is 'localhost', which usually means remote machines will not be able to connect.
  5. # To allow connections from remote users, set this parameter to a non-loopback address.
  6. server.host: "0.0.0.0"#不要使用本IP,localhost和127.0.0.1,否则外网不能访问
  7. # Enables you to specify a path to mount Kibana at if you are running behind a proxy.
  8. # Use the `server.rewriteBasePath` setting to tell Kibana if it should remove the basePath
  9. # from requests it receives, and to prevent a deprecation warning at startup.
  10. # This setting cannot end in a slash.
  11. #server.basePath: ""
  12. # Specifies whether Kibana should rewrite requests that are prefixed with
  13. # `server.basePath` or require that they are rewritten by your reverse proxy.
  14. # This setting was effectively always `false` before Kibana 6.3 and will
  15. # default to `true` starting in Kibana 7.0.
  16. #server.rewriteBasePath: false
  17. # The maximum payload size in bytes for incoming server requests.
  18. #server.maxPayloadBytes: 1048576
  19. # The Kibana server's name.  This is used for display purposes.
  20. #server.name: "your-hostname"
  21. # The URLs of the Elasticsearch instances to use for all your queries.
  22. #elasticsearch.hosts: ["http://localhost:9200"]
  23. elasticsearch.hosts: "http://192.168.0.104:9200"#es访问地址
  24. # When this setting's value is true Kibana uses the hostname specified in the server.host
  25. # setting. When the value of this setting is false, Kibana uses the hostname of the host
  26. # that connects to this Kibana instance.
  27. #elasticsearch.preserveHost: true
  28. # Kibana uses an index in Elasticsearch to store saved searches, visualizations and
  29. # dashboards. Kibana creates a new index if the index doesn't already exist.
  30. #kibana.index: ".kibana"
  31. # The default application to load.
  32. #kibana.defaultAppId: "home"
  33. # If your Elasticsearch is protected with basic authentication, these settings provide
  34. # the username and password that the Kibana server uses to perform maintenance on the Kibana
  35. # index at startup. Your Kibana users still need to authenticate with Elasticsearch, which
  36. # is proxied through the Kibana server.
  37. #elasticsearch.username: "user"
  38. #elasticsearch.password: "pass"
  39. # Enables SSL and paths to the PEM-format SSL certificate and SSL key files, respectively.
  40. # These settings enable SSL for outgoing requests from the Kibana server to the browser.
  41. #server.ssl.enabled: false
  42. #server.ssl.certificate: /path/to/your/server.crt
  43. #server.ssl.key: /path/to/your/server.key
  44. # Optional settings that provide the paths to the PEM-format SSL certificate and key files.
  45. # These files validate that your Elasticsearch backend uses the same key files.
  46. #elasticsearch.ssl.certificate: /path/to/your/client.crt
  47. #elasticsearch.ssl.key: /path/to/your/client.key
  48. # Optional setting that enables you to specify a path to the PEM file for the certificate
  49. # authority for your Elasticsearch instance.
  50. #elasticsearch.ssl.certificateAuthorities: [ "/path/to/your/CA.pem" ]
  51. # To disregard the validity of SSL certificates, change this setting's value to 'none'.
  52. #elasticsearch.ssl.verificationMode: full
  53. # Time in milliseconds to wait for Elasticsearch to respond to pings. Defaults to the value of
  54. # the elasticsearch.requestTimeout setting.
  55. #elasticsearch.pingTimeout: 1500
  56. # Time in milliseconds to wait for responses from the back end or Elasticsearch. This value
  57. # must be a positive integer.
  58. #elasticsearch.requestTimeout: 30000
  59. # List of Kibana client-side headers to send to Elasticsearch. To send *no* client-side
  60. # headers, set this value to [] (an empty list).
  61. #elasticsearch.requestHeadersWhitelist: [ authorization ]
  62. # Header names and values that are sent to Elasticsearch. Any custom headers cannot be overwritten
  63. # by client-side headers, regardless of the elasticsearch.requestHeadersWhitelist configuration.
  64. #elasticsearch.customHeaders: {}
  65. # Time in milliseconds for Elasticsearch to wait for responses from shards. Set to 0 to disable.
  66. #elasticsearch.shardTimeout: 30000
  67. # Time in milliseconds to wait for Elasticsearch at Kibana startup before retrying.
  68. #elasticsearch.startupTimeout: 5000
  69. # Logs queries sent to Elasticsearch. Requires logging.verbose set to true.
  70. #elasticsearch.logQueries: false
  71. # Specifies the path where Kibana creates the process ID file.
  72. #pid.file: /var/run/kibana.pid
  73. # Enables you specify a file where Kibana stores log output.
  74. #logging.dest: stdout
  75. # Set the value of this setting to true to suppress all logging output.
  76. #logging.silent: false
  77. # Set the value of this setting to true to suppress all logging output other than error messages.
  78. #logging.quiet: false
  79. # Set the value of this setting to true to log all events, including system usage information
  80. # and all requests.
  81. #logging.verbose: false
  82. # Set the interval in milliseconds to sample system and process performance
  83. # metrics. Minimum is 100ms. Defaults to 5000.
  84. #ops.interval: 5000
  85. # Specifies locale to be used for all localizable strings, dates and number formats.
  86. #i18n.locale: "en"
     

启动kibana:kibana/bin/kibana

访问:http://192.168.0.104:5601如出现页面,即为成功

第四步:解压elasticsearch-head-master.zip,与elasticsearch在同一级目录

配置:elasticsearch-head-master/Gruntfile.js及安装node.js,grunt环境

  1. module.exports = function(grunt) {
  2.     var fileSets = require("./grunt_fileSets.js");
  3.     // Project configuration.
  4.     grunt.initConfig({
  5.         clean: {
  6.             _site: {
  7.                 src: ['_site']
  8.             }
  9.         },
  10.         concat: {
  11.             vendorjs: {
  12.                 src: fileSets.vendorJs,
  13.                 dest: '_site/vendor.js'
  14.             },
  15.             vendorcss: {
  16.                 src: fileSets.vendorCss,
  17.                 dest: '_site/vendor.css'
  18.             },
  19.             appjs: {
  20.                 src: fileSets.srcJs,
  21.                 dest: '_site/app.js'
  22.             },
  23.             appcss: {
  24.                 src: fileSets.srcCss,
  25.                 dest: '_site/app.css'
  26.             }
  27.         },
  28.         copy: {
  29.             site_index: {
  30.                 src: 'index.html',
  31.                 dest: '_site/index.html',
  32.                 options: {
  33.                     process: function( src ) {
  34.                         return src.replace(/_site\//g, "");
  35.                     }
  36.                 }
  37.             },
  38.             base: {
  39.                 expand: true,
  40.                 cwd: 'src/app/base/',
  41.                 src: [ '*.gif', '*.png', '*.css' ],
  42.                 dest: '_site/base/'
  43.             },
  44.             iconFonts: {
  45.                 expand: true,
  46.                 cwd: 'src/vendor/font-awesome/fonts/',
  47.                 src: '**',
  48.                 dest: '_site/fonts'
  49.             },
  50.             i18n: {
  51.                 src: 'src/vendor/i18n/i18n.js',
  52.                 dest: '_site/i18n.js'
  53.             },
  54.             lang: {
  55.                 expand: true,
  56.                 cwd: 'src/app/lang/',
  57.                 src: '**',
  58.                 dest: '_site/lang/'
  59.             },
  60.             chrome: {
  61.                 src: 'src/chrome_ext/*.*',
  62.                 dest: '_site/'
  63.             }
  64.         },
  65.         jasmine: {
  66.             task: {
  67.                 src: [ fileSets.vendorJs, 'src/vendor/i18n/i18n.js', 'src/app/lang/en_strings.js', fileSets.srcJs ],
  68.                 options: {
  69.                     specs: 'src/app/**/*Spec.js',
  70.                     helpers: 'test/spec/*Helper.js',
  71.                     display: "short",
  72.                     summary: true
  73.                 }
  74.             }
  75.         },
  76.         watch: {
  77.             "scripts": {
  78.                 files: ['src/**/*', 'test/spec/*' ],
  79.                 tasks: ['default'],
  80.                 options: {
  81.                     spawn: false
  82.                 }
  83.             },
  84.             "grunt": {
  85.                 files: [ 'Gruntfile.js' ]
  86.             }
  87.         },
  88.         connect: {
  89.             server: {
  90.                 options: {
  91.                     port: 9100,
  92.                     hostname: '*',#增加通配地址,可以获取到集群es信息
  93.                     base: '.',
  94.                     keepalive: true
  95.                 }
  96.             }
  97.         }
  98.     });
  99.     grunt.loadNpmTasks('grunt-contrib-clean');
  100.     grunt.loadNpmTasks('grunt-contrib-concat');
  101.     grunt.loadNpmTasks('grunt-contrib-watch');
  102.     grunt.loadNpmTasks('grunt-contrib-connect');
  103.     grunt.loadNpmTasks('grunt-contrib-copy');
  104.     grunt.loadNpmTasks('grunt-contrib-jasmine');
  105.     // Default task(s).
  106.     grunt.registerTask('default', ['clean', 'concat', 'copy', 'jasmine']);
  107.     grunt.registerTask('server', ['connect:server']);
  108.     grunt.registerTask('dev', [ 'default', 'watch' ]);
  109.  
  110. };

启动head先进入head目录:cd elasticsearch-head-master

再启动head:grunt server

访问:http://localhost:9100出现页面,并能看到自带的kinaba索引即为成功

第五步:eclise新建一个springboot工程

配置POM.XML

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5.     <modelVersion>4.0.0</modelVersion>
  6.     <parent>
  7.         <groupId>org.springframework.boot</groupId>
  8.         <artifactId>spring-boot-starter-parent</artifactId>
  9.         <version>2.1.5.RELEASE</version>
  10.         <relativePath /> <!-- lookup parent from repository -->
  11.     </parent>
  12.     <groupId>com.shierwin</groupId>
  13.     <artifactId>es</artifactId>
  14.     <packaging>war</packaging>
  15.     <version>2.0.0-SNAPSHOT</version>
  16.     <name>es</name>
  17.     <description>es project</description>
  18.     <properties>
  19.         <java.version>1.8</java.version>
  20.     </properties>
  21.     <dependencies>
  22.         <dependency>
  23.             <groupId>org.springframework.boot</groupId>
  24.             <artifactId>spring-boot-starter-web</artifactId>
  25.         </dependency>
  26.         <dependency>
  27.             <groupId>org.springframework.boot</groupId>
  28.             <artifactId>spring-boot-starter-data-elasticsearch</artifactId>#spring与es结合包
  29.         </dependency>
  30.         <dependency>
  31.             <groupId>com.google.guava</groupId>
  32.             <artifactId>guava</artifactId>#数据集转换工具
  33.             <version>28.2-jre</version>
  34.         </dependency>
  35.         <dependency>
  36.             <groupId>junit</groupId>
  37.             <artifactId>junit</artifactId>
  38.             <version>3.8.1</version>
  39.             <scope>test</scope>
  40.         </dependency>
  41.     </dependencies>
  42.     <build>
  43.         <plugins>
  44.             <plugin>
  45.                 <groupId>org.springframework.boot</groupId>
  46.                 <artifactId>spring-boot-maven-plugin</artifactId>
  47.             </plugin>
  48.         </plugins>
  49.     </build>
  50. </project>

配置application.properties

  1. #访问端口
  2. server.port=80
  3. #工程名称的访问路径,可不配
  4. server.servlet.context-path=/es
  5. spring.data.elasticsearch.repositories.enabled =true#设置repositories可用
  6. spring.data.elasticsearch.cluster-name =elasticsearch#设置es集群名称
  7. spring.data.elasticsearch.cluster-nodes =192.168.0.104:9300#设置es集群名称地址,多地址可以用逗号分开

编写对象,如问题库对象:

  1. package com.shierwin.es;
  2. import org.springframework.data.elasticsearch.annotations.Document;
  3. @Document(indexName = "shierwin", type = "_doc", shards = 3, replicas = 1)//连接es的索引名,类型,分片,副文本
  4. public class QtDo {
  5.     
  6.     private String id;
  7.     
  8.     private String qustion;
  9.     
  10.     private String anwser;
  11.     public String getId() {
  12.         return id;
  13.     }
  14.     public void setId(String id) {
  15.         this.id = id;
  16.     }
  17.     public String getQustion() {
  18.         return qustion;
  19.     }
  20.     public void setQustion(String qustion) {
  21.         this.qustion = qustion;
  22.     }
  23.     public String getAnwser() {
  24.         return anwser;
  25.     }
  26.     public void setAnwser(String anwser) {
  27.         this.anwser = anwser;
  28.     }
  29. }

编写操作es增删改查接口:

  1. package com.shierwin.es;
  2. public interface QtService {
  3.     //查询所有,id倒序排
  4.     public void searchAll();
  5.     
  6.     //根据id查询
  7.     public void searchOne();
  8.     
  9.     //新增
  10.     public void addOne() ;
  11.     
  12.     //修改
  13.     public void updateOne();
  14.     
  15.     //删除
  16.     public void deleteOne();
  17.     
  18.     //聚合条件查询
  19.     public void searchCondition();
  20.     
  21. }
     

编写操作es增删改查接口实现类:

  1. package com.shierwin.es;
  2. import java.util.Iterator;
  3. import java.util.List;
  4. import java.util.Optional;
  5. import org.elasticsearch.index.query.QueryBuilder;
  6. import org.elasticsearch.index.query.QueryBuilders;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.data.domain.Page;
  9. import org.springframework.data.domain.PageRequest;
  10. import org.springframework.data.domain.Pageable;
  11. import org.springframework.data.domain.Sort;
  12. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  13. import org.springframework.stereotype.Service;
  14. import com.google.common.collect.Lists;
  15. @Service
  16. public class QtServiceImp implements QtService {
  17.     @Autowired
  18.     private ElasticsearchRepository<QtDo, String> qtRepository;
  19.     //查询所有,id倒序排
  20.     @Override
  21.     public void searchAll() {
  22.         Iterable<QtDo> iterable = qtRepository.findAll(Sort.by("_id").ascending());
  23.         List<QtDo> list = Lists.newArrayList(iterable);
  24.         for (int i = 0; i < list.size(); i++) {
  25.             QtDo qt = list.get(i);
  26.             System.out.println(qt.getId()+"::"+qt.getQustion()+"::"+qt.getAnwser());
  27.         }
  28.     }
  29.     
  30.     //根据id查询
  31.     @Override
  32.     public void searchOne() {
  33.         Optional<QtDo> qt = qtRepository.findById("WSUiL3ABPy5Bh_EkO65y");
  34.         QtDo tempQt = new QtDo();
  35.         QtDo qtObj = qt.orElse(tempQt);
  36.         System.out.println(qtObj.getId()+":"+qtObj.getQustion()+":"+qtObj.getAnwser());
  37.     }
  38.     
  39.     //新增
  40.     @Override
  41.     public void addOne() {
  42.         QtDo qt = new QtDo();
  43.         qt.setQustion("8");
  44.         qt.setAnwser("15");
  45.         qt = (QtDo) qtRepository.save(qt);
  46.         System.out.println(qt.getId()+"::"+qt.getQustion()+"::"+qt.getAnwser());
  47.     }
  48.     
  49.     //修改
  50.     @Override
  51.     public void updateOne() {
  52.         QtDo qt = new QtDo();
  53.         qt.setId("PKxkUXABp_H2y73Zm7i_");
  54.         qt.setQustion("你城市的房子买在那呀?7");
  55.         qt.setAnwser("江西省南昌市象湖新城幸福时光二期7");
  56.         qt = (QtDo) qtRepository.save(qt);
  57.         System.out.println(qt.getId()+"::"+qt.getQustion()+"::"+qt.getAnwser());
  58.     }
  59.     
  60.     //删除
  61.     @Override
  62.     public void deleteOne() {
  63.         qtRepository.deleteById("36xjUXABp_H2y73Z27fC");
  64.     }
  65.     
  66.     //聚合条件查询
  67.     @Override
  68.     public void searchCondition() {
  69.          int pageNum = 0;
  70.          int pageSize = 30;
  71.          Pageable pageable = PageRequest.of(pageNum, pageSize);
  72. //         QueryBuilder queryBuilder = QueryBuilders.fuzzyQuery("qustion", "房");//模湖词查询
  73. //         QueryBuilder queryBuilder = QueryBuilders.termQuery("qustion", "8");//没有分词的精确查询
  74. //         QueryBuilder queryBuilder = QueryBuilders.matchQuery("qustion", "疫情");//分词查询
  75. //         QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("qustion", "疫情");//精确分词短语查询
  76.          QueryBuilder queryBuilder = QueryBuilders
  77.                                      .boolQuery()
  78.                                      .must(QueryBuilders.termQuery("qustion", "8"))
  79.                                      .must(QueryBuilders.termQuery("anwser", "15"));
  80.         Page<QtDo> pageList  = qtRepository.search(queryBuilder, pageable);
  81.         Iterator<QtDo> iterator= pageList.iterator();
  82.         while(iterator.hasNext()){
  83.             QtDo qt = (QtDo) iterator.next();
  84.             System.out.println(qt.getId()+"::"+qt.getQustion()+"::"+qt.getAnwser());
  85.         }
  86.     }
  87. }

编写ElasticsearchRepository引用接口,不加这接口,springboot在启动时会注入异常:

  1. public interface QtRepository extends  ElasticsearchRepository {
  2. }

第六步:启动spring application即可读取到es的数据

完整的工程源码下载:https://download.csdn.net/download/shiquanlong/12166806

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值