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。

相关推荐
野犬寒鸦29 分钟前
力扣hot100:相交链表与反转链表详细思路讲解(160,206)
java·数据结构·后端·算法·leetcode
ytadpole1 小时前
揭秘设计模式:工厂模式的五级进化之路
java·设计模式
计算机毕业设计木哥1 小时前
计算机毕设选题:基于Python+Django的B站数据分析系统的设计与实现【源码+文档+调试】
java·开发语言·后端·python·spark·django·课程设计
失散131 小时前
分布式专题——1.2 Redis7核心数据结构
java·数据结构·redis·分布式·架构
用户3721574261352 小时前
Python 实现 HTML 转 Word 和 PDF
java
a587692 小时前
Java核心概念精讲:TCP与UDP的区别、Java NIO的几个核心组件与HTTP和HTTPS的区别等(46-50)
java·面试·nio
渣哥2 小时前
ConcurrentHashMap 的 get 要不要加锁?一次“多此一举”的心路历程
java
愿你天黑有灯下雨有伞2 小时前
一种基于注解与AOP的Spring Boot接口限流防刷方案
java·spring boot·后端
MuMuMu#2 小时前
JAVA NIO学习笔记基础强化学习总结
java·学习·nio
拾忆,想起2 小时前
Redis复制延迟全解析:从毫秒到秒级的优化实战指南
java·开发语言·数据库·redis·后端·缓存·性能优化