Springboot整合ElasticSearch

文章目录

      • 介绍
      • ElasticSearch环境搭建
        • 拉取elasticsearch镜像
        • 启动单个节点的
          • 为ElasticSearch创建docker网络
        • 启动ElasticSearch
        • 初次启动生成密码重置
        • 从docker镜像容器中复制安全证书到本地机器
        • 连接测试
        • 设置虚拟机参数
        • postman测试
          • 创建索引
          • 查看所有的索引
          • 查看单个索引
          • 删除索引
          • 添加数据
      • 查询所有的文档
        • springboot整合data-elasticsearch
          • 依赖
          • yml配置
          • config配置类
          • dao层
          • 服务类
          • 服务实现类
          • controller类

介绍

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

ElasticSearch环境搭建

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

拉取elasticsearch镜像

docker pull docker.elastic.co/elasticsearch/elasticsearch:8.4.1

Springboot整合ElasticSearch_第1张图片

启动单个节点的

为ElasticSearch创建docker网络
docker network create elastic
## bddc04060de42a369112000bec26954c1404c1c163af163620eb949af5f254e9

启动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

初次启动生成密码重置

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

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

Springboot整合ElasticSearch_第2张图片

改成功之后,启动成功,可以浏览器端进行访问,输入用户名和密码
Springboot整合ElasticSearch_第3张图片

从docker镜像容器中复制安全证书到本地机器

docker cp elasticsearch:/usr/share/elasticsearch/config/certs/http_ca.crt .

连接测试

curl --cacert http_ca.crt -u elastic https://localhost:9200

设置虚拟机参数

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

postman测试

创建索引

Put请求

http://192.168.5.130:9200/city

成功返回结果

{
    "acknowledged": true,
    "shards_acknowledged": true,
    "index": "product"
}
查看所有的索引

Get请求

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

返回所有的索引

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

查看单个索引

地址后边加上索引的名字

http://192.168.5.130:9200/product
{
    "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"
                }
            }
        }
    }
}
删除索引

delete 请求

http://192.168.5.130:9200/city
{
    "acknowledged": true
}

删除再次查看会

{
    "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
}
添加数据

post请求

http://192.168.5.130:9200/product/_doc

body中存放json

{
		"title": "联想拯救者",
		"category": "电脑",
		"desc": "拯救者带你起飞",
		"price": 8999.0
	}

返回结果:

	{
    "_index": "product",
    "_id": "DcVT_YIBztDygxIIGOjO",
    "_version": 1,
    "result": "created",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 0,
    "_primary_term": 1
}

查询所有的文档

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

{
	"query":{
		"match_all":{}
	}
}
{
    "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
                }
            }
        ]
    }
}

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

springboot整合data-elasticsearch

依赖
    
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-data-elasticsearchartifactId>
    dependency>

yml配置
##配置es ip和端口
elasticsearch:
  host: 192.168.5.130
  port: 9200
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;
    }
}
dao层
/**
 * 持久化类
 * 操作文档
 */
public interface ProductDao extends ElasticsearchRepository<Product,Long> {
}

服务类
/**
 * 服务接口类
 */
public interface IProductService {
    //保存
    void saveProduct(Product product);

    //更新
    void updateProduct(Product product);

    //根据
     Product getProductById(Long id);

    //获取商品列表
     List<Product> getProductList();

    //删除商品
     void deleteProductById(Long id);
}

服务实现类
/**
 * 接口服务实现类
 */
@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);
    }
}
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";
    }
}

你可能感兴趣的:(springboot,elasticsearch,spring,boot,大数据)