Java集成Elasticsearch实战商品表增删改查全解析java操作ElasticSearch增删改查

在电商等众多业务场景中,Elasticsearch(简称ES)常被用于存储商品信息,以实现快速搜索和高效查询。本文将通过具体代码示例,详细介绍如何使用Java对ES中的商品表索引数据进行增删改查操作。

一、环境准备

1. 添加依赖

pom.xml中添加Elasticsearch的依赖:

XML 复制代码
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.12.1</version>
</dependency>

2. 配置Elasticsearch客户端

application.properties中配置ES的连接信息:

elasticsearch.host=localhost
elasticsearch.port=9200

创建ElasticsearchConfig类来配置RestHighLevelClient

java 复制代码
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private int port;

    @Bean
    public RestHighLevelClient client() {
        return new RestHighLevelClient(RestClient.builder(new HttpHost(host, port, "http")));
    }
}

二、商品表实体类

创建Product实体类,用于映射商品表的索引数据:

java 复制代码
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 double price;
    private String description;

    // 构造函数、getter和setter省略
}

三、增删改查操作

1. 创建索引

java 复制代码
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

public void createIndex(RestHighLevelClient client) throws IOException {
    CreateIndexRequest request = new CreateIndexRequest("products");
    client.indices().create(request, RequestOptions.DEFAULT);
}

2. 添加商品数据

java 复制代码
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;

public void addProduct(RestHighLevelClient client, Product product) throws IOException {
    IndexRequest request = new IndexRequest("products").id(product.getId()).source(product);
    client.index(request, RequestOptions.DEFAULT);
}

3. 查询商品数据

java 复制代码
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;

public Product getProduct(RestHighLevelClient client, String id) throws IOException {
    GetRequest request = new GetRequest("products", id);
    GetResponse response = client.get(request, RequestOptions.DEFAULT);
    return new Product(response.getId(), response.getSourceAsMap());
}

4. 更新商品数据

java 复制代码
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;

public void updateProduct(RestHighLevelClient client, Product product) throws IOException {
    UpdateRequest request = new UpdateRequest("products", product.getId()).doc(product);
    client.update(request, RequestOptions.DEFAULT);
}

5. 删除商品数据

java 复制代码
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.client.RequestOptions;

public void deleteProduct(RestHighLevelClient client, String id) throws IOException {
    DeleteRequest request = new DeleteRequest("products", id);
    client.delete(request, RequestOptions.DEFAULT);
}

6. 删除索引

java 复制代码
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;

public void deleteIndex(RestHighLevelClient client) throws IOException {
    DeleteIndexRequest request = new DeleteIndexRequest("products");
    client.indices().delete(request, RequestOptions.DEFAULT);
}

四、完整代码示例

java 复制代码
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;

public class ElasticsearchService {

    @Autowired
    private RestHighLevelClient client;

    public void createIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("products");
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    public void addProduct(Product product) throws IOException {
        IndexRequest request = new IndexRequest("products").id(product.getId()).source(product);
        client.index(request, RequestOptions.DEFAULT);
    }

    public Product getProduct(String id) throws IOException {
        GetRequest request = new GetRequest("products", id);
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        return new Product(response.getId(), response.getSourceAsMap());
    }

    public void updateProduct(Product product) throws IOException {
        UpdateRequest request = new UpdateRequest("products", product.getId()).doc(product);
        client.update(request, RequestOptions.DEFAULT);
    }

    public void deleteProduct(String id) throws IOException {
        DeleteRequest request = new DeleteRequest("products", id);
        client.delete(request, RequestOptions.DEFAULT);
    }

    public void deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("products");
        client.indices().delete(request, RequestOptions.DEFAULT);
    }
}

五、总结

通过上述代码示例,我们详细介绍了如何使用Java对Elasticsearch中的商品表索引数据进行增删改查操作。这些操作是实现商品搜索、商品管理等功能的基础。在实际应用中,可以根据业务需求对这些基本操作进行组合和扩展,以满足更复杂的功能需求。希望本文的示例代码和解释能够帮助你更好地理解和使用Elasticsearch。

相关推荐
程序员林北北44 分钟前
【Golang学习之旅】gRPC 与 REST API 的对比及应用
java·开发语言·后端·学习·云原生·golang
一川晚照人闲立1 小时前
JEECGBOOT前端VUE3版本浏览器兼容支持chrome>=76版本方法
java·前端·vue.js·chrome·anti-design-vue·jeecgboot·jeecg
m0_748250031 小时前
重学SpringBoot3-整合 Elasticsearch 8.x (二)使用Repository
大数据·elasticsearch·jenkins
0wioiw02 小时前
Python基础(SQLAlchemy)
java·开发语言·数据库
Luo_LA2 小时前
【Java 面试 八股文】Redis篇
java·redis·面试
ChinaRainbowSea2 小时前
十四. Redis 新功能
java·数据库·redis·缓存·bootstrap
小胖子——鑫2 小时前
对“云原生”的初印象
java·开发语言·云原生
归宿乐瑶3 小时前
六.logback记录日志文件并按大小日期分割文件
java·spring boot·logback
码蜂窝编程官方3 小时前
【含开题报告+文档+PPT+源码】基于SpringBoot+Vue旅游管理网站
java·vue.js·spring boot·旅游
牛马baby3 小时前
Java高频面试之SE-21
java·开发语言·面试