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。

相关推荐
明天不下雨(牛客同名)2 小时前
为什么 ThreadLocalMap 的 key 是弱引用 value是强引用
java·jvm·算法
多多*2 小时前
Java设计模式 简单工厂模式 工厂方法模式 抽象工厂模式 模版工厂模式 模式对比
java·linux·运维·服务器·stm32·单片机·嵌入式硬件
胡图蛋.4 小时前
Spring Boot 支持哪些日志框架?推荐和默认的日志框架是哪个?
java·spring boot·后端
牛马baby4 小时前
Java高频面试之并发编程-01
java·开发语言·面试
小小大侠客4 小时前
将eclipse中的web项目导入idea
java·eclipse·intellij-idea
不再幻想,脚踏实地4 小时前
MySQL(一)
java·数据库·mysql
吃海鲜的骆驼4 小时前
SpringBoot详细教程(持续更新中...)
java·spring boot·后端
迷雾骑士5 小时前
SpringBoot中WebMvcConfigurer注册多个拦截器(addInterceptors)时的顺序问题(二)
java·spring boot·后端·interceptor
别来无恙✲5 小时前
Mybatis源码分析
java·源码分析
68岁扶墙肾透5 小时前
Java安全-FastJson反序列化分析
java·安全·web安全·网络安全·网络攻击模型·安全架构·fastjson