编程 Java环境中使用Elasticsearch

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

以下是一个详细的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

推荐文章

使用Vue 3和Axios进行API数据交互
2024-11-18 22:31:21 +0800 CST
Vue3中如何处理路由和导航?
2024-11-18 16:56:14 +0800 CST
Go配置镜像源代理
2024-11-19 09:10:35 +0800 CST
20个超实用的CSS动画库
2024-11-18 07:23:12 +0800 CST
你可能不知道的 18 个前端技巧
2025-06-12 13:15:26 +0800 CST
为什么大厂也无法避免写出Bug?
2024-11-19 10:03:23 +0800 CST
CSS 特效与资源推荐
2024-11-19 00:43:31 +0800 CST
一键压缩图片代码
2024-11-19 00:41:25 +0800 CST
使用Python实现邮件自动化
2024-11-18 20:18:14 +0800 CST
html一些比较人使用的技巧和代码
2024-11-17 05:05:01 +0800 CST
PHP 压缩包脚本功能说明
2024-11-19 03:35:29 +0800 CST
地图标注管理系统
2024-11-19 09:14:52 +0800 CST
jQuery `$.extend()` 用法总结
2024-11-19 02:12:45 +0800 CST
php客服服务管理系统
2024-11-19 06:48:35 +0800 CST
MySQL 主从同步一致性详解
2024-11-19 02:49:19 +0800 CST
markdowns滚动事件
2024-11-19 10:07:32 +0800 CST
# 解决 MySQL 经常断开重连的问题
2024-11-19 04:50:20 +0800 CST
程序员茄子在线接单