编程 Java环境中使用Elasticsearch

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

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

推荐文章

html流光登陆页面
2024-11-18 15:36:18 +0800 CST
PHP 压缩包脚本功能说明
2024-11-19 03:35:29 +0800 CST
2024年公司官方网站建设费用解析
2024-11-18 20:21:19 +0800 CST
imap_open绕过exec禁用的脚本
2024-11-17 05:01:58 +0800 CST
WebSQL数据库:HTML5的非标准伴侣
2024-11-18 22:44:20 +0800 CST
Mysql允许外网访问详细流程
2024-11-17 05:03:26 +0800 CST
goctl 技术系列 - Go 模板入门
2024-11-19 04:12:13 +0800 CST
Nginx 反向代理
2024-11-19 08:02:10 +0800 CST
MySQL用命令行复制表的方法
2024-11-17 05:03:46 +0800 CST
在 Docker 中部署 Vue 开发环境
2024-11-18 15:04:41 +0800 CST
服务器购买推荐
2024-11-18 23:48:02 +0800 CST
Web浏览器的定时器问题思考
2024-11-18 22:19:55 +0800 CST
markdowns滚动事件
2024-11-19 10:07:32 +0800 CST
Nginx负载均衡详解
2024-11-17 07:43:48 +0800 CST
PHP来做一个短网址(短链接)服务
2024-11-17 22:18:37 +0800 CST
联系我们
2024-11-19 02:17:12 +0800 CST
Gin 与 Layui 分页 HTML 生成工具
2024-11-19 09:20:21 +0800 CST
JavaScript中的常用浏览器API
2024-11-18 23:23:16 +0800 CST
解决python “No module named pip”
2024-11-18 11:49:18 +0800 CST
Shell 里给变量赋值为多行文本
2024-11-18 20:25:45 +0800 CST
Go 单元测试
2024-11-18 19:21:56 +0800 CST
ElasticSearch 结构
2024-11-18 10:05:24 +0800 CST
程序员茄子在线接单