首页 > Java > java教程 > 正文

java怎么连接Elasticsearch 连接并操作Elasticsearch搜索引擎数据

煙雲
发布: 2025-12-13 23:02:02
原创
315人浏览过
使用Java API Client连接Elasticsearch需添加elasticsearch-java依赖并创建RestClient实例,通过ElasticsearchClient执行索引、查询、更新和删除操作,推荐用于8.x版本,替代已弃用的旧客户端。

java怎么连接elasticsearch 连接并操作elasticsearch搜索引擎数据

Java 连接并操作 Elasticsearch 主要有两种方式:使用官方的 Java REST 客户端(已弃用)或推荐的 Java API Client(新版,基于 Elasticsearch 7.15+)。下面以目前主流且官方推荐的方式进行说明。

1. 添加 Maven 依赖

在你的 pom.xml 中添加 Elasticsearch 的 Java API Client 依赖:

<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.14.0</version>
</dependency>
<p><!-- Jackson 数据绑定 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
</code></p>
登录后复制

2. 创建客户端连接

使用 TransportClient 已被弃用,现在推荐使用基于 HTTP 的 Java API Client。以下是一个创建连接的示例:

立即学习Java免费学习笔记(深入)”;

Mistral AI
Mistral AI

Mistral AI被称为“欧洲版的OpenAI”,也是目前欧洲最强的 LLM 大模型平台

Mistral AI 182
查看详情 Mistral AI
<pre class="brush:php;toolbar:false;">import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
<p>public class EsClient {
private static ElasticsearchClient client;</p><pre class="brush:php;toolbar:false;"><code>public static ElasticsearchClient getClient() {
    if (client == null) {
        // 创建低级别客户端(Apache HttpClient)
        RestClient restClient = RestClient.builder(
            new HttpHost("localhost", 9200)
        ).build();

        // 创建传输层
        ElasticsearchTransport transport = new RestClientTransport(
            restClient, new JacksonJsonpMapper()
        );

        // 创建高级客户端
        client = new ElasticsearchClient(transport);
    }
    return client;
}

public static void close() throws IOException {
    if (client != null) {
        client._transport().close();
    }
}
登录后复制

}

3. 索引文档(插入数据)

向 Elasticsearch 插入一条 JSON 文档:

import co.elastic.clients.elasticsearch.core.IndexResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
<p>public class IndexExample {
public static void indexDocument() throws Exception {
var objectMapper = new ObjectMapper();
var client = EsClient.getClient();</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">    // 要插入的数据(Map 或 POJO)
    User user = new User("1", "张三", 25);

    IndexResponse response = client.index(i -> i
        .index("users")           // 索引名
        .id(user.getId())         // 文档 ID
        .document(user)
    );

    System.out.println("Indexed with version: " + response.version());
}
登录后复制

}

// 用户类示例 class User { private String id; private String name; private int age;

// 构造函数、getter 和 setter 省略
登录后复制

}

4. 查询文档

根据 ID 获取文档或执行搜索查询:

  • 根据 ID 获取文档
  • var response = client.get(g -> g
        .index("users")
        .id("1"),
        User.class
    );
    <p>if (response.found()) {
    System.out.println("Name: " + response.source().getName());
    } else {
    System.out.println("Not found");
    }
    </code></p>
    登录后复制
  • 执行全文搜索
  • <pre class="brush:php;toolbar:false;">var searchResponse = client.search(s -> s
        .index("users")
        .query(q -> q
            .match(t -> t
                .field("name")
                .query("张三")
            )
        ),
        User.class
    );
    <p>for (var hit : searchResponse.hits().hits()) {
    System.out.println("User: " + hit.source());
    }
    
    登录后复制

5. 更新和删除文档

  • 更新文档
  • <pre class="brush:php;toolbar:false;">client.update(u -> u
        .index("users")
        .id("1")
        .doc(new User("1", "李四", 26)),
        User.class
    );
    
    登录后复制
  • 删除文档
  • client.delete(d -> d
        .index("users")
        .id("1")
    );
    
    登录后复制

注意事项

  • Elasticsearch 8.x 推荐使用新的 Java API Client,旧的 TransportClient 和 <code>RestHighLevelClient 已废弃。
  • 确保 Elasticsearch 服务正在运行,默认端口是 9200。
  • 如果启用了安全认证(如用户名密码),需要在 RestClient 中配置凭据。
  • POJO 类需有 getter/setter,否则 Jackson 可能无法序列化。

基本上就这些。只要依赖正确、网络通、代码结构清晰,Java 操作 Elasticsearch 并不复杂。

以上就是java怎么连接Elasticsearch 连接并操作Elasticsearch搜索引擎数据的详细内容,更多请关注php中文网其它相关文章!

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号