Bootstrap

Spring Boot应用程序集成Elasticsearch

以下是一个Spring Boot应用程序集成Elasticsearch的示例,展示了如何存储和查询数据。我们将使用Spring Data Elasticsearch模块来实现这个示例。

添加依赖

首先,确保你在项目的pom.xml文件中添加了以下依赖:

    <dependencies>
        <!-- Spring Boot Starter Data Elasticsearch -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <version>2.3.12.RELEASE</version>
        </dependency>

        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.12.RELEASE</version>
        </dependency>
    </dependencies>

配置Elasticsearch

在项目的application.yml文件中添加Elasticsearch相关的配置:

spring:
  elasticsearch:
    rest:
      uris: http://127.0.0.1:9200
      username:
      password:

定义实体类

创建一个实体类,它将映射到Elasticsearch的文档结构:

package com.example.esdemo.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "products")
public class Product {

    @Id
    private String id;
    private String name;
    private String description;
    private double price;

    // Getters and setters
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

创建Repository接口

创建一个Spring Data Elasticsearch repository接口:

package com.example.esdemo.repository;

import com.example.esdemo.model.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ProductRepository extends ElasticsearchRepository<Product, String> {
    List<Product> findByName(String name);
}

创建服务层

创建一个服务层来封装业务逻辑:

package com.example.esdemo.service;

import com.example.esdemo.model.Product;
import com.example.esdemo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public Product save(Product product) {
        return productRepository.save(product);
    }

    public Optional<Product> findById(String id) {
        return productRepository.findById(id);
    }

    public Iterable<Product> findAll() {
        return productRepository.findAll();
    }

    public void deleteById(String id) {
        productRepository.deleteById(id);
    }

    public List<Product> findByName(String name) {
        return productRepository.findByName(name);
    }
}

创建控制器

创建一个控制器来处理HTTP请求:

package com.example.esdemo.controller;

import com.example.esdemo.model.Product;
import com.example.esdemo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping
    public Product saveProduct(@RequestBody Product product) {
        return productService.save(product);
    }

    @GetMapping("/{id}")
    public Optional<Product> getProductById(@PathVariable String id) {
        return productService.findById(id);
    }

    @GetMapping
    public Iterable<Product> getAllProducts() {
        return productService.findAll();
    }

    @DeleteMapping("/{id}")
    public void deleteProduct(@PathVariable String id) {
        productService.deleteById(id);
    }

    @GetMapping("/search")
    public List<Product> getProductsByName(@RequestParam String name) {
        return productService.findByName(name);
    }
}

Spring Boot 主类

创建Spring Boot应用程序的主类:

package com.example.esdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EsDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(EsDemoApplication.class, args);
    }
}

运行应用程序

启动Spring Boot应用程序,确保Elasticsearch服务器正在运行。然后,你可以使用Postman或其他HTTP客户端来测试API:

  • 存储数据

    POST http://localhost:8080/products
    Body: 
    {
      "name": "Laptop",
      "description": "A high-performance laptop",
      "price": 1000.0
    }
    
  • 查询数据

    GET http://localhost:8080/products/{id}
    
  • 查询所有数据

    GET http://localhost:8080/products
    
  • 根据名称查询数据

    GET http://localhost:8080/products/search?name=Laptop
    
  • 删除数据

    DELETE http://localhost:8080/products/{id}
    

解释

  1. 依赖管理

    • 使用Spring Boot Starter Data Elasticsearch简化Elasticsearch集成。
    • 使用Spring Boot Starter Web简化Web应用开发。
  2. 配置

    • application.yml中指定Elasticsearch服务器地址和其他相关配置。
  3. 定义实体类

    • 使用@Document注解将实体类映射到Elasticsearch索引。
  4. 创建Repository接口

    • 使用Spring Data Elasticsearch repository接口简化数据访问操作。
  5. 创建服务层

    • 封装业务逻辑,提供数据存储和查询的高层接口。
  6. 创建控制器

    • 处理HTTP请求,提供RESTful API进行数据存储和查询。

通过这个示例,你可以轻松地使用Spring Boot集成Elasticsearch来实现数据的存储和查询功能。

;