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。

相关推荐
coderSong25682 小时前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
Mr_Air_Boy3 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
豆沙沙包?3 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
年老体衰按不动键盘3 小时前
快速部署和启动Vue3项目
java·javascript·vue
咖啡啡不加糖4 小时前
Redis大key产生、排查与优化实践
java·数据库·redis·后端·缓存
liuyang-neu4 小时前
java内存模型JMM
java·开发语言
UFIT4 小时前
NoSQL之redis哨兵
java·前端·算法
刘 大 望4 小时前
数据库-联合查询(内连接外连接),子查询,合并查询
java·数据库·sql·mysql
怀旧,4 小时前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法
大春儿的试验田5 小时前
Parameter ‘XXX‘ not found. Available parameters are [list, param1]
java