Elasticsearch 在 Java 中的使用教程

2025-04-04 03:50

本文主要是介绍Elasticsearch 在 Java 中的使用教程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文...

1. Elasticsearch 简介

Elasticsearch 是一个分布式搜索和分析引擎,基于 Apache Lucene 构建,能够实现实时数据的存储、搜索、和分析。它广泛应用于全文搜索、日志分析、性能监控等领域。Elasticsearch 的核心概念包括文档(document)、索引(index)、和分片(shard)。

2. 环境准备

2.1 安装 Elasticsearch

从 Elasticsearch 官方网站 下载并安装适合你操作系统的版本。

安装完成后,通过以下命令启动 Elasticsearch 服务:

./bin/elasticsearch

默认情况下,Elasticsearch 运行在 http://localhost:9200

2.2 Java 开发环境配置

  • 安装 Java SDK(JDK 11 或更高版本)。
  • 安装 Maven 或 Gradle。
  • 创建一个 Maven 项目,添加 Elasticsearch Java 客户端的依赖。

2.3 添加 Elasticsearch 客户端依赖

在 Maven 项目的 pom.XML 文件中添加以下依赖:

<dependencies>
    <!-- Elasticsearch Java Client -->
    <dependency>
        <groupId>co.elastic.clients</groupId>
        <artifactId>elasticsearch-java</artifactId>
        <version>8.10.0</version>
    </dependency>
</dependencies>

如果你使用 Gradle,可以在 build.gradle 文件中添加以下依赖:

dependencies {
    implementation 'co.elastic.clients:elasticsearch-java:8.10.0'
}

添加依赖后,确保项目能够正常编译。

3. 使用 Java 连接 Elasticsearch

接下来,我们将编写一个简单的 Java 程序来连接 Elasticsearch。

3.1 编写连接代码

创建一个 Java 类,例如 ElasticsearchConnection.java,并编写以下代码:

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.InfoResponse;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
public class ElasticsearchConnection {
    public static void main(String[] args) throws Exception {
        // 创建 REST 客户端
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();
        // 创建传输层
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        // 创建 Elasticsearch 客户端
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 获取集群信息
        InfoResponse info = client.info();
        System.out.println("Connected to Elasticsearch cluster: " + info.clusterName());
        // 关闭客户端
        transport.close();
    }
}

3.2 运行代码

编译并运行这个程序,如果成功,你将看到类似如下的输出:

Connected to Elasticsearch cluster: elasticsearch

这表明你已经成功连接到了 Elasticsearch。

4. 基本 CRUD 操作

Elasticsearch 的 CRUD 操作主要涉及对索引中的文档进行增(Create)、查(Read)、改(Update)、删(Delete)操作。

4.1 创建索引和插入文档

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import co.elastic.clients.elasticsearch.core.IndexRequest;
public class ElasticsearchCRUD {
    public static void main(String[] args) throws Exception {
        // 创建 REST 客户端
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();
        // 创建传输层
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        // 创建 Elasticsearch 客户端
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 创建文档
        String json = "{ \"name\": \"John Doe\", \"age\": 30, \"city\": \"New York\" }";
        // 插入文档到索引
        IndexRequest<Object> request = new IndexRequest.Builder<>()
            .index("users")
            .id("1")
            .document(json)
            .build();
        IndexResponse response = client.index(request);
        System.out.println("Document inserted with ID: " + response.id());
        // 关闭客户端
        transport.close();
    }
}

4.2 查询文档

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.GetResponse;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import co.elastic.clients.elasticsearch.core.GetRequest;
public class ElasticsearchRead {
    public static void main(String[] args) throws Exception {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 查询文档
        GetRequest getRequest = new GetRequest.Builder()
                .index("users")
                .id("1")
                .build();
        GetResponse<Object> response = client.get(getRequest, Object.class);
        if (response.found()) {
            System.out.println("Document found: " + response.source());
        } else {
            System.out.println("Document not found");
        }
        transport.close();
    }
}

4.3 更新文档

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.UpdateResponse;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import co.elastic.clients.elasticsearch.core.UpdateRequest;
import java.util.Map;
public class ElasticsearchUpdate {
    public static void main(String[] args) throws Exception {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 更新文档
        Map<String, Object> updateJson = Map.of(
                "age", 31,php
                "city", "San Francisco"
        );
        UpdateRequest<Object, Map<String, Object>> updateRequest = new UpdateRequest.Builder<>()
                .index("users")
                .id("1")
                .doc(updateJson)
                .build();
        UpdateResponse<Object> updateResponse = client.update(updateRequest, Object.class);
        System.out.println("Document updated: " + updateResponse.result());
        transport.close();
    }
}

4.4 删除文档

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.DeleteResponse;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import co.elastic.clients.elasticsearch.core.DeleteRequest;
public class ElasticsearchDelete {
    public static void main(String[] args) throws Exception {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 删除文档
        DeleteRequest deleteRequest = new DeleteRequest.Builder()
                .index("users")
                .id("1")
                .build();
        DeleteResponse deleteResponse = client.delete(deleteRequest);
        System.out.println("Document deleted: " + deleteResponse.result());
        transport.close();
    }
}

5. 复杂查询操作

Elasticsearch 提供了强大的查询 DSLChina编程(Domain Specific Language),支持布尔查询、范围查询、聚合查询等。

5.1 布尔查询

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.search.Query;
public class ElasticsearchBooleanQuery {
    public static void main(String[] args) throws Exception {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 布尔查询
        SearchRequest searchRequest = new SearchRequest.Builder()
                .index("users")
                .query(Query
                .bool(b -> b
                    .must(m -> m.match(match -> match.field("name").query("John Doe")))
                    .filter(f -> f.range(r -> r.field("age").gte(30)))
                ))
                .build();
        SearchResponse<Object> searchResponse = client.search(searchRequest, Object.class);
        for (Hit<Object> hit : searchResponse.hits().hits()) {
            System.out.println("Document found: " + hit.source());
        }
        transport.close();
    }
}

5.2 范围查询

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.search.Query;
public class ElasticsearchRangeQuery {
    public static void main(String[] args) throws Exception {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTranwww.chinasem.cnsport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 范围查询:查询 age 在 25 到 35 之间的文档
        SearchRequest searchRequest = new SearchRequest.Builder()
                .index("users")
                .query(Query.range(r -> r.field("age").gte(25).lte(35)))
                .build();
        SearchResponse<Object> searchResponse = client.search(searchRequest, Object.class);
        for (Hit<Object> hit : searchResponse.hits().hits()) {
            System.out.println("Document found: " + hit.source());
        }
        transport.close();
    }
}

6. 索引管理与优化

在 Elasticsearch 中,索引管理是非常重要的操作,合理的索引设置和优化可以大幅提升查询性能。

6.1 创建索引并设置映射

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
public class ElasticsearchCreateIndex {
    public static void main(String[] args) throws Exception {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 创建索引并设置映射
        CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                .index("users")
                .mappings(m -> m
                    .properties("name", p -> p.text(t -> t))
                    .properties("age", p -> p.integer(i -> i))
                    .properties("city", p -> p.text(t -> t))
                )
                .build();
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest);
        if (createIndexResponse.acknowledged()) {
            System.out.println("Index created successfully!");
        }
        transport.close();
    }
}

6.2 删除索引

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import co.elastic.clients.elasticsearch.indices.DeleteIndexRequest;
public class ElasticsearchDeleteIndex {
    public static void main(String[] args) throws Exception {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 删除索引
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder()
                .index("users")
                .build();
        DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest);
        if (deleteIndexResponse.acknowledged()) {
            System.out.println("Index deleted successfully!");
        }
        transport.close();
    }
}

7. 聚合操作

Elasticsearch 的聚合功能非常强大,能够对数据进行分组统计、计算平均值、最大值、最小值等操作。

7.1 聚合查询:计算年龄的平均值

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.Aggregation;
import co.elastic.clients.elasticsearch.core.search.Bucket;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
public class ElasticsearchAggregation {
    public static void main(String[] args) throws Exception {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
 js       // 聚合查询:计算年龄的平均值
        SearchRequest searchRequest = new SearchRequeChina编程st.Builder()
                .index("users")
                .size(0)  // 不返回文档,只返回聚合结果
                .aggregations("average_age", a -> a.avg(avg -> avg.field("age")))
                .build();
        SearchResponse<Object> searchResponse = client.search(searchRequest, Object.class);
        double averageAge = searchResponse.aggregations().get("average_age").avg().value();
        System.out.println("Average age: " + averageAge);
        transport.close();
    }
}

8. 总结

本教程详细介绍了如何在 Java 中使用 Elasticsearch,涵盖了连接、基本 CRUD 操作、复杂查询、索引管理和聚合操作等方面的内容。通过这些示例,开发者可以一步步地掌握如何在 Java 项目中集成 Elasticsearch,并利用其强大的搜索和分析功能来构建高效的应用程序。

到此这篇关于Elasticsearch 在 Java 中的使用教程的文章就介绍到这了,更多相关Elasticsearch 在 Java使用内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于Elasticsearch 在 Java 中的使用教程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154085

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置