编程 Java环境中使用Elasticsearch

2024-11-18 22:46:32 +0800 CST views 566

以下是一个详细的Java结合Elasticsearch的操作案例,涵盖了从环境准备到具体操作的多个方面,帮助你在Java环境中使用Elasticsearch进行索引的创建、文档的增删改查以及数据查询等操作。

一、环境准备

1. 安装 Elasticsearch

  • 下载 Elasticsearch:访问 Elasticsearch 官网 下载适合你操作系统的 Elasticsearch 7.x 版本。
  • 配置 Elasticsearch
    • 解压安装包,并进入配置文件 elasticsearch.yml
    • 配置集群名称、节点名称、网络地址和端口等。
    • 启动 Elasticsearch 服务,通过运行 ./bin/elasticsearch 启动服务。

2. 安装 Java 开发环境

  • Java 环境:确保已经安装了 JDK 1.8 或更高版本,并配置好 JAVA_HOME 环境变量。

3. 添加 Elasticsearch 客户端依赖

在你的 Java 项目中,添加 Elasticsearch High Level REST Client 依赖。

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.x.x</version> <!-- 替换为实际使用的版本号 -->
</dependency>

二、Java 操作 Elasticsearch 案例

1. 初始化 Elasticsearch 客户端

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

public class ElasticsearchClient {
    private static final String HOSTNAME = "localhost";
    private static final int PORT = 9200;
    private static final String SCHEME = "http";

    public static RestHighLevelClient createClient() {
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(HOSTNAME, PORT, SCHEME)));
    }
}

2. 创建索引

import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

public class IndexExample {
    public static void createIndex(RestHighLevelClient client) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("users");
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println("Index created: " + acknowledged);
    }

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = ElasticsearchClient.createClient();
        createIndex(client);
        client.close();
    }
}

3. 删除索引

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

public class DeleteIndex {
    public static void deleteIndex(RestHighLevelClient client) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("users");
        DeleteIndexResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println("Index deleted: " + deleteIndexResponse.isAcknowledged());
    }

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = ElasticsearchClient.createClient();
        deleteIndex(client);
        client.close();
    }
}

4. 插入文档

import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AddDocument {
    public static void addDocument(RestHighLevelClient client) throws IOException {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("name", "John Doe");
        jsonMap.put("age", 30);
        jsonMap.put("email", "john.doe@example.com");

        IndexRequest request = new IndexRequest("users")
                .id("1")
                .source(jsonMap, XContentType.JSON);

        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        System.out.println("Document added with ID: " + indexResponse.getId());
    }

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = ElasticsearchClient.createClient();
        addDocument(client);
        client.close();
    }
}

5. 搜索文档

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

public class SearchDocument {
    public static void searchDocument(RestHighLevelClient client) throws IOException {
        SearchRequest searchRequest = new SearchRequest("users");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("name", "John"));
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println("Search results: " + searchResponse.getHits().getTotalHits().value);
    }

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = ElasticsearchClient.createClient();
        searchDocument(client);
        client.close();
    }
}

6. 更新文档

import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class UpdateDocument {
    public static void updateDocument(RestHighLevelClient client) throws IOException {
        String jsonString = "{" +
                "\"name\":\"John Updated\"," +
                "\"age\":31," +
                "\"email\":\"john.updated@example.com\"" +
                "}";

        UpdateRequest request = new UpdateRequest("users", "1")
                .doc(jsonString, XContentType.JSON);

        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        System.out.println("Document updated with ID: " + updateResponse.getId());
    }

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = ElasticsearchClient.createClient();
        updateDocument(client);
        client.close();
    }
}

7. 删除文档

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import java.io.IOException;

public class DeleteDocumentExample {
    public static void deleteDocument(RestHighLevelClient client) throws IOException {
        DeleteRequest request = new DeleteRequest("users", "1");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println("Document deleted with ID: " + response.getId());
    }

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = ElasticsearchClient.createClient();
        deleteDocument(client);
        client.close();
    }
}

8. 关闭客户端

在操作完成后,确保关闭客户端以释放资源:

client.close();

9. 异常处理

在实际开发中,处理各种异常(如网络错误、Elasticsearch集群问题等)是必要的。在每个操作中,应使用 try-catch 块来捕获并处理异常。

结论

以上是一个基于Java的Elasticsearch操作案例,涵盖了从初始化客户端、创建和删除索引、文档的增删改查操作等内容。通过这些示例,你可以在实际项目中轻松集成Elasticsearch,并根据业务需求进行定制化开发。

复制全文 生成海报 编程 数据库 搜索引擎 Java Elasticsearch

推荐文章

实用MySQL函数
2024-11-19 03:00:12 +0800 CST
MySQL 主从同步一致性详解
2024-11-19 02:49:19 +0800 CST
底部导航栏
2024-11-19 01:12:32 +0800 CST
乐观锁和悲观锁,如何区分?
2024-11-19 09:36:53 +0800 CST
Vue3中怎样处理组件引用?
2024-11-18 23:17:15 +0800 CST
html5在客户端存储数据
2024-11-17 05:02:17 +0800 CST
Vue3 组件间通信的多种方式
2024-11-19 02:57:47 +0800 CST
什么是Vue实例(Vue Instance)?
2024-11-19 06:04:20 +0800 CST
Golang在整洁架构中优雅使用事务
2024-11-18 19:26:04 +0800 CST
Vue3中哪些API被废弃了?
2024-11-17 04:17:22 +0800 CST
php常用的正则表达式
2024-11-19 03:48:35 +0800 CST
Elasticsearch 条件查询
2024-11-19 06:50:24 +0800 CST
MySQL死锁 - 更新插入导致死锁
2024-11-19 05:53:50 +0800 CST
404错误页面的HTML代码
2024-11-19 06:55:51 +0800 CST
Roop是一款免费开源的AI换脸工具
2024-11-19 08:31:01 +0800 CST
MyLib5,一个Python中非常有用的库
2024-11-18 12:50:13 +0800 CST
程序员茄子在线接单