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。

相关推荐
Seven9717 分钟前
剑指offer-80、⼆叉树中和为某⼀值的路径(二)
java
怒放吧德德12 小时前
Netty 4.2 入门指南:从概念到第一个程序
java·后端·netty
雨中飘荡的记忆13 小时前
大流量下库存扣减的数据库瓶颈:Redis分片缓存解决方案
java·redis·后端
心之语歌16 小时前
基于注解+拦截器的API动态路由实现方案
java·后端
洛森唛16 小时前
Elasticsearch DSL 查询语法大全:从入门到精通
后端·elasticsearch
华仔啊17 小时前
Stream 代码越写越难看?JDFrame 让 Java 逻辑回归优雅
java·后端
ray_liang17 小时前
用六边形架构与整洁架构对比是伪命题?
java·架构
Ray Liang18 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Java水解19 小时前
Java 中间件:Dubbo 服务降级(Mock 机制)
java·后端
SimonKing1 天前
OpenCode AI辅助编程,不一样的编程思路,不写一行代码
java·后端·程序员