• Springboot整合ElasticSearch


    介绍

    很容易理解,search名字,顾名思义就是搜索的意思,搜索的场景很多,我们在填写表单的时候搜索地图地点,购买商品的时候筛选商品等。这种匹配需要模糊匹配,根据权重进行匹配达到我们搜索的目的,传统的访问关系型数据库没法满足,于是出现了新的技术ElasticSearch

    ElasticSearch环境搭建

    环境搭建的话,我们还是在docker中进行安装。
    根据官方的文档进行安装

    拉取elasticsearch镜像
    docker pull docker.elastic.co/elasticsearch/elasticsearch:8.4.1
    
    • 1

    拉取镜像

    启动单个节点的
    为ElasticSearch创建docker网络
    docker network create elastic
    ## bddc04060de42a369112000bec26954c1404c1c163af163620eb949af5f254e9
    
    • 1
    • 2
    启动ElasticSearch

    -e “discovery.type=single-node”

    docker run --name elasticsearch --net elastic -p 9200:9200 -p 9300:9300 -it  -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:8.4.1
    
    • 1
    初次启动生成密码重置

    -u表示需要修改的用户名
    -i 表示交互式,可以自己指定密码,默认的是系统自动分配。

    docker exec -it elasticsearch /usr/share/elasticsearch/bin/elasticsearch-reset-password -u -i
    
    • 1

    重置密码

    改成功之后,启动成功,可以浏览器端进行访问,输入用户名和密码
    返回成功

    docker镜像容器中复制安全证书到本地机器
    docker cp elasticsearch:/usr/share/elasticsearch/config/certs/http_ca.crt .
    
    • 1
    连接测试
    curl --cacert http_ca.crt -u elastic https://localhost:9200
    
    • 1
    设置虚拟机参数
    docker run -e CLI_JAVA_OPTS="-Xms1g -Xmx1g" -e ENROLLMENT_TOKEN="" --name es02 -p 9201:9200 --net elastic -it docker.elastic.co/elasticsearch/elasticsearch:docker.elastic.co/elasticsearch/elasticsearch:8.4.1
    
    • 1
    postman测试
    创建索引

    Put请求

    http://192.168.5.130:9200/city
    
    • 1

    成功返回结果

    {
        "acknowledged": true,
        "shards_acknowledged": true,
        "index": "product"
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    查看所有的索引

    Get请求

    http://192.168.5.130:9200/_cat/indices?v
    
    • 1

    返回所有的索引

    health status index   uuid                   pri rep docs.count docs.deleted store.size pri.store.size
    yellow open   product txt1I7pbQG2RkSV86kyfAQ   1   1          0            0       225b           225b
    yellow open   city    t6roDc9BQ2iG7Ls4Yuw-ZQ   1   1          0            0       225b           225b
    
    
    • 1
    • 2
    • 3
    • 4
    查看单个索引

    地址后边加上索引的名字

    http://192.168.5.130:9200/product
    
    • 1
    {
        "product": {
            "aliases": {},
            "mappings": {},
            "settings": {
                "index": {
                    "routing": {
                        "allocation": {
                            "include": {
                                "_tier_preference": "data_content"
                            }
                        }
                    },
                    "number_of_shards": "1",
                    "provided_name": "product",
                    "creation_date": "1662106626639",
                    "number_of_replicas": "1",
                    "uuid": "txt1I7pbQG2RkSV86kyfAQ",
                    "version": {
                        "created": "8040199"
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    删除索引

    delete 请求

    http://192.168.5.130:9200/city
    
    • 1
    {
        "acknowledged": true
    }
    
    • 1
    • 2
    • 3

    删除再次查看会

    {
        "error": {
            "root_cause": [
                {
                    "type": "index_not_found_exception",
                    "reason": "no such index [city]",
                    "resource.type": "index_or_alias",
                    "resource.id": "city",
                    "index_uuid": "_na_",
                    "index": "city"
                }
            ],
            "type": "index_not_found_exception",
            "reason": "no such index [city]",
            "resource.type": "index_or_alias",
            "resource.id": "city",
            "index_uuid": "_na_",
            "index": "city"
        },
        "status": 404
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    添加数据

    post请求

    http://192.168.5.130:9200/product/_doc
    
    • 1

    body中存放json

    {
    		"title": "联想拯救者",
    		"category": "电脑",
    		"desc": "拯救者带你起飞",
    		"price": 8999.0
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    返回结果:

    	{
        "_index": "product",
        "_id": "DcVT_YIBztDygxIIGOjO",
        "_version": 1,
        "result": "created",
        "_shards": {
            "total": 2,
            "successful": 1,
            "failed": 0
        },
        "_seq_no": 0,
        "_primary_term": 1
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    查询所有的文档

    Get请求:http://192.168.5.130:9200/product/_search
    输入参数:

    {
    	"query":{
    		"match_all":{}
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    {
        "took": 7,
        "timed_out": false,
        "_shards": {
            "total": 1,
            "successful": 1,
            "skipped": 0,
            "failed": 0
        },
        "hits": {
            "total": {
                "value": 2,
                "relation": "eq"
            },
            "max_score": 1,
            "hits": [
                {
                    "_index": "product",
                    "_id": "DcVT_YIBztDygxIIGOjO",
                    "_score": 1,
                    "_source": {
                        "title": "联想拯救者",
                        "category": "电脑",
                        "desc": "拯救者带你起飞",
                        "price": 8999
                    }
                },
                {
                    "_index": "product",
                    "_id": "DsVV_YIBztDygxIIleg1",
                    "_score": 1,
                    "_source": {
                        "title": "DELL",
                        "category": "电脑",
                        "desc": "DELL全新技术",
                        "price": 7999
                    }
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    其他操作在这里不在讲解,详细的可以看看官网的。

    springboot整合data-elasticsearch
    依赖
        
        <dependency>
          <groupId>org.springframework.bootgroupId>
          <artifactId>spring-boot-starter-data-elasticsearchartifactId>
        dependency>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    yml配置
    ##配置es ip和端口
    elasticsearch:
      host: 192.168.5.130
      port: 9200
    
    • 1
    • 2
    • 3
    • 4
    config配置类
    /**
     * 配置类
     */
    @ConfigurationProperties(prefix = "elasticsearch")
    @Configuration
    @Data
    public class EsConfig extends AbstractElasticsearchConfiguration {
        private String host;
        private Integer port;
    
        @Override
        public RestHighLevelClient elasticsearchClient() {
            RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(host,port));
            RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);
            return restHighLevelClient;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    dao层
    /**
     * 持久化类
     * 操作文档
     */
    public interface ProductDao extends ElasticsearchRepository<Product,Long> {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    服务类
    /**
     * 服务接口类
     */
    public interface IProductService {
        //保存
        void saveProduct(Product product);
    
        //更新
        void updateProduct(Product product);
    
        //根据
         Product getProductById(Long id);
    
        //获取商品列表
         List<Product> getProductList();
    
        //删除商品
         void deleteProductById(Long id);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    服务实现类
    /**
     * 接口服务实现类
     */
    @Service
    public class IProductServiceImpl implements IProductService {
    
        @Autowired
        ProductDao productDao;
    
        /**
         * 保存商品
         * @param product
         */
        @Override
        public void saveProduct(Product product) {
            productDao.save(product);
        }
    
        /**
         * 更新商品
         * @param product
         */
        @Override
        public void updateProduct(Product product) {
           productDao.save(product);
        }
    
        /**
         * 根据ID获取
         * @param id
         * @return
         */
        @Override
        public Product getProductById(Long id) {
            return productDao.findById(id).get();
        }
    
        /**
         * 获取商品列表
         * @return
         */
        @Override
        public List<Product> getProductList() {
            Iterable<Product> products = productDao.findAll();
            List<Product> productList = new ArrayList<>();
            for(Product product:products){
                productList.add(product);
            }
            return productList;
        }
    
        /**
         * 删除商品
         * @param id
         */
        @Override
        public void deleteProductById(Long id) {
             productDao.deleteById(id);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    controller类
    /**
     * es 控制类
     */
    @RestController
    public class ESController {
    
        @Autowired
        IProductService productService;
    
        @GetMapping("/welcome")
        public String test(){
            return "hello,welcome to es world!";
        }
    
        /**
         * 保存
         * @param product
         * @return
         */
        @PostMapping("/saveProduct")
        public String saveProduct(@RequestBody  Product product){
            productService.saveProduct(product);
            return "save success";
        }
        /**
         * 更新商品
         * @param product
         * @return
         */
        @PutMapping("/updateProduct")
        public String updateProduct(@RequestBody  Product product){
            productService.saveProduct(product);
            return "update success";
        }
        /**
         * 获取单个商品
         * @param id
         * @return
         */
        @GetMapping("/getProductById/{ProductId}")
        public Product getProductById(@PathVariable("ProductId")  Long id){
            Product product = productService.getProductById(id);
            return product;
        }
    
        /**
         * 获取商品列表
         * @return
         */
        @GetMapping("/getProductList")
        public List<Product> getProductList(){
            return productService.getProductList();
        }
        /**
         * 删除商品
         */
        @DeleteMapping("/deleteProductById/{productId}")
        public String  deleteProductById(@PathVariable("productId")  Long id){
            productService.deleteProductById(id);
            return "delete success";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
  • 相关阅读:
    独立站选品和欧美市场前瞻
    北大肖臻老师《区块链技术与应用》系列课程学习笔记[27]以太坊-反思
    网络代理工具软件Proxyman mac中文版功能特点
    设计模式-单例模式(最全总结)
    MindSpore编译构建后Vmap模块的RuntimeError问题
    我们距离“裸眼3D自由”,还有多远?
    性能测试基础
    《计算机网络》考研:2024/3/9 2.1.7-数据交换方式;2.2-物理层传输介质;2.3-物理层设备
    Impala数据类型转换cast(可解决小数后长串数字问题)
    后端防接口被刷
  • 原文地址:https://blog.csdn.net/qq_37400096/article/details/126654688