Java操作ElasticSearch的实例详解

2025-01-21 16:50

本文主要是介绍Java操作ElasticSearch的实例详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Java操作ElasticSearch的实例详解》Elasticsearch是一个分布式的搜索和分析引擎,广泛用于全文搜索、日志分析等场景,本文将介绍如何在Java应用中使用Elastics...

简介

Elasticsearch 是一个分布式的搜索和分析引擎,广泛用于全文搜索、日志分析等场景。本文将介绍如何在 Java 应用中使用 Elasticsearch 客户端来连接和操作 Elasticsearch 集群。

环境准备

1. 安装 Elasticsearch

首先,确保你的www.chinasem.cn环境中已经安装了 Elasticsearch。可以从 ​​Elasticsearch 官方网站​​下载最新版本的 Elasticsearch,并按照官方文档进行安装和启动。

2. 添加依赖

在你的 Java 项目中,需要添加 Elasticsearch 的客户端依赖。如果你使用的是 Maven,可以在 ​​pom.XML​​ 文件中添加以下依赖:

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.10.2</version>
</dependency>

连接 Elasticsearch

1. 创建客户端

使用 ​​RestHighLevelClient​​ 类来创建一个连接到 Elasticsearch 集群的客户端。

import org.elasticsearch.client.RestHighLevelClient;
import org.apache.http.HttpHost;
 
public class ElasticsearchClient {
    public static RestHighLevelClient createClient() {
        return new RestHighLevelClient(
            RestClient.builder(
                new HttpHost("localhost", 9200, "http")
            )
        );
    }
}

2. 关闭客户端

在完成所有操作后,记得关闭客户端以释放资源。

try {
    client.close();
} catch (IOException e) {
    e.printStackTrace();
}

基本操作

1. 创建索引

创建一个新的索引,并指定一些设置和映射。

import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
 
public claChina编程ss IndexOperations {
    public static void createIndex(RestHighLevelClient client) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("test_index");
        request.mapping("{\n" +
                "  \"properties\": {\n" +
                "    \"title\": {\n" +
                "      \"type\": \"text\"\n" +
                "    },\n" +
                "    \"content\": {\n" +
                "      \"type\": \"text\"\n" +
                "    }\n" +
                "  }\n" +
                "}", XContentType.jsON);
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("Index created: " + response.isAcknowledged());
    }
}

2. 插入数据

向索引中插入一条文档。

import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
 
public class DocumentOperations {
    public static void indexDocument(RestHighLevelClient client) throws IOException {
        String jsonString = "{" +
                "\"title\":\"Elasticsearch基础教程\"," +
                "\"content\":\"Elasticsearch是一个分布式搜索和分析引擎\"}";
        IndexRequest request = new IndexRequest("test_index").source(jsonString, XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println("Document indexed with ID: " + response.getId());
    }
}

3. 查询数据

从索引中查询文档。

import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
 
public class SearchOperations {
    public static void getDocument(RestHighLevelClient client) throws IOExceptionandroid {
        GetRequest request = new GetRequest("test_index", "1");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        if (response.isExists()) {
            System.out.println("Document found: " + response.getSourceAsString());
        } else {
            System.out.println("Document not found.");
        }
    }
}

通过上述步骤,你可以在 Java 应js用中轻松地连接和操作 Elasticsearch 集群。本文介绍了如何创建客户端、创建索引、插入文档和查询文档。这些基本操作为更复杂的使用场景奠定了基础。

以上就是使用 Java 操作 Elasticsearch 的一个简单示例。希望对你有帮助!当然可以!Elasticsearch 是一个分布式的搜索和分析引擎,广泛用于全文搜索、日志分析、实时应用监控等场景。

下面是一个使用 Java 操作 Elasticsearch 的示例代码,包括连接到 ES 集群、创建索引、插入文档、查询文档等基本操作。

环境准备

添加依赖:在你的 Maven 项目的 ​​pom.xml​​ 文件中添加 Elasticsearch 客户端依赖。

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.10.2</version>
</dependency>

配置 Elasticsearch:确保你有一个运行中的 Elasticsearch 实例。你可以使用 docker 快速启动一个:

docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.10.2

示例代码

以下是一个完整的 Java 示例代码,展示了如何连接到 Elasticsearch 集群、创建索引、插入文档和查询文档。

import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
public class ElasticsearchExample {
 
    public static void main(String[] args) {
        // 创建 RestHighLevelClient 客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")
                )
        );
 
        try {
            // 创建索引
            createIndex(client);
 
            // 插入文档
            insertDocument(client);
 
            // 查询文档
            searchDocument(client);
 
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    private static void createIndex(RestHighLevelClient client) throws IOException {
        // 创建索引请求
        Map<String, Object> mappings = new HashMap<>();
        mappings.put("properties", Map.of(
                "title", Map.of("type", "text"),
                "content", Map.of("type", "text")
        ));
 
        String mappingJson = XContentType.JSON.toString(mappings);
        IndexRequest indexRequest = new IndexRequest("my_index")
                .source(mappingJson, XContentType.JSON);
 
        // 执行请求
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("Index created: " + indexResponse.getResult());
    }
 
    private static void insertDocument(RestHighLevelClient client) throws IOException {
        // 创建文档
        Map<String, Object> document = new HashMap<>();
        document.put("title", "Elasticsearch Example");
        document.put("content", "This is an example of using Elasticsearch with Java.");
 
        // 创建索引请求
        IndexRequest indexRequest = new IndexRequest("my_index")
                .id("1")
                .source(document);
 
        // 执行请求
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("Document inserted: " + indexResponse.getResult());
    }
 
    private static void searchDocument(RestHighLevelClient client) throws IOException {
        // 创建搜索请求
        SearchRequest searchRequest = new SearchRequest("my_index");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("title", "Elasticsearch"));
        searchRequest.source(searchSourceBuilder);
 
        // 执行请求
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
 
        // 处理响应
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            System.out.println("Document found: " + hit.getSourceAsString());
        }
    }
}

代码说明

  • 创建客户端:使用 ​​RestHighLevelClient​​ 连接到 Elasticsearch 集群。
  • 创建索引:定义索引的映射并创建索引。
  • 插入文档:创建一个文档并将其插入到指定的索引中。
  • 查询文档:使用匹配查询(​​matchQuery​​)来搜索包含特定关键字的文档。

运行代码

确保你的 Elasticsearch 实例正在运行,然后运行上述 Java 程序。你应该会看到索引创建、文档插入和查询结果的输出。

希望这个示例对你有帮助!如果有任何问题或需要进一步的帮助,请随时告诉我。当然可以!Elasticsearch 是一个分布式的搜索和分析引擎,广泛用于全文搜索、日志分析、实时应用监控等场景。在 Java 应用中操作 Elasticsearch 通常需要使用官方提供的客户端库,如 ​​elasticsearch-rest-high-level-client​​(现已停止更新)或更现代的 ​​elasticsearch-java​​ 客户端。

以下是一个详细的步骤和示例代码,展示如何在 Java 中使用 ​​elasticsearch-java​​ 客户端来操作 Elasticsearch 实例:

1. 添加依赖

首先,在你的 ​​pom.xml​​ 文件中添加 Elasticsearch 客户端的依赖。这里以 Maven 为例:

<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.6.2</version> <!-- 请根据实际情况选择合适的版本 -->
</dependency>

2. 创建客户端

创建一个 Elasticsearch 客户端实例,用于与 Elasticsearch 集群进行通信。

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;
 
public class ElasticsearchClientExample {
 
    public static ElasticsearchClient createClient() {
        // 创建 Rest 客户端
        RestClient restClient = RestClient.builder(
            new HttpHost("localhost", 9200, "http")
        ).build();
 
        // 创建 Elasticsearch 客户端
        ElasticsearchTransport transport = new RestClientTransport(
            restClient, new JacksonJsonpMapper()
        );
 
        return new ElasticsearchClient(transport);
    }
}

3. 索引文档

接下来,我们演示如何索引(插入)一个文档到 Elasticsearch 中。

import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.IndexResponse.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class IndexDocumentExample {
 
    public static void main(String[] args) throws Exception {
        ElasticsearchClient client = ElasticsearchClientExample.createClient();
 
        // 创建一个文档对象
        MyDocument document = new MyDocument();
        document.setId(1);
        document.setTitle("Elasticsearch Java Client Example");
        document.setContent("This is an example of using the Elasticsearch Java client.");
 
        // 使用 ObjectMapper 将对象转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(document);
 
        // 创建索引请求
        IndexRequest<MyDocument> request = new IndexRequest.Builder<MyDocument>()
            .index("my_index")
            .id(String.valueOf(document.getId()))
            .document(document)
            .build();
 
        // 执行索引请求
        IndexResponse response = client.index(request);
 
        // 检查响应结果
        if (response.result() == Result.Created) {
            System.out.println("Document indexed successfully.");
        } else {
            System.out.println("Failed to index document.");
        }
 
        // 关闭客户端
        client.close();
    }
}
 
class MyDocument {
    private int id;
    private String title;
    private String content;
 
    // Getters and Setters
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    publandroidic String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
}

4. 查询文档

接下来,我们演示如何查询 Elasticsearch 中的文档。

import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
 
public class SearchDocumentExample {
 
    public static void main(String[] args) throws Exception {
        ElasticsearchClient client = ElasticsearchClientExample.createClient();
 
        // 创建查询请求
        SearchRequest request = new SearchRequest.Builder()
            .index("my_index")
            .query(q -> q.match(m -> m.field("title").query("Elasticsearch")))
            .build();
 
        // 执行查询请求
        SearchResponse<MyDocument> response = client.search(request, MyDocument.class);
 
        // 处理查询结果
        for (Hit<MyDocument> hit : response.hits().hits()) {
            MyDocument document = hit.source();
            System.out.println("Found document: " + document.getTitle());
        }
 
        // 关闭客户端
        client.close();
    }
}

5. 删除文档

最后,我们演示如何删除 Elasticsearch 中的文档。

import co.elastic.clients.elasticsearch.core.DeleteRequest;
import co.elastic.clients.elasticsearch.core.DeleteResponse;
import co.elastic.clients.elasticsearch.core.DeleteResponse.Result;
 
public class DeleteDocumentExample {
 
    public static void main(String[] args) throws Exception {
        ElasticsearchClient client = ElasticsearchClientExample.createClient();
 
        // 创建删除请求
        DeleteRequest request = new DeleteRequest.Builder()
            .index("my_index")
            .id("1")
            .build();
 
        // 执行删除请求
        DeleteResponse response = client.delete(request);
 
        // 检查响应结果
        if (response.result() == Result.Deleted) {
            System.out.println("Document deleted successfully.");
        } else {
            System.out.println("Failed to delete document.");
        }
 
        // 关闭客户端
        client.close();
    }
}

总结

本文代码展示了如何在 Java 中使用 ​​elasticsearch-java​​ 客户端进行基本的 CRUD 操作。你可以根据实际需求扩展这些示例,例如处理更复杂的查询、批量操作等

以上就是Java操作ElasticSearch的实例详解的详细内容,更多关于Java操作ElasticSearch的资料请关注编程China编程(www.chinasem.cn)其它相关文章!

这篇关于Java操作ElasticSearch的实例详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

前端原生js实现拖拽排课效果实例

《前端原生js实现拖拽排课效果实例》:本文主要介绍如何实现一个简单的课程表拖拽功能,通过HTML、CSS和JavaScript的配合,我们实现了课程项的拖拽、放置和显示功能,文中通过实例代码介绍的... 目录1. 效果展示2. 效果分析2.1 关键点2.2 实现方法3. 代码实现3.1 html部分3.2

如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解

《如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解》:本文主要介绍如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别的相关资料,描述了如何使用海康威视设备网络SD... 目录前言开发流程问题和解决方案dll库加载不到的问题老旧版本sdk不兼容的问题关键实现流程总结前言作为

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

SQL 中多表查询的常见连接方式详解

《SQL中多表查询的常见连接方式详解》本文介绍SQL中多表查询的常见连接方式,包括内连接(INNERJOIN)、左连接(LEFTJOIN)、右连接(RIGHTJOIN)、全外连接(FULLOUTER... 目录一、连接类型图表(ASCII 形式)二、前置代码(创建示例表)三、连接方式代码示例1. 内连接(I

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2

Go路由注册方法详解

《Go路由注册方法详解》Go语言中,http.NewServeMux()和http.HandleFunc()是两种不同的路由注册方式,前者创建独立的ServeMux实例,适合模块化和分层路由,灵活性高... 目录Go路由注册方法1. 路由注册的方式2. 路由器的独立性3. 灵活性4. 启动服务器的方式5.

springboot将lib和jar分离的操作方法

《springboot将lib和jar分离的操作方法》本文介绍了如何通过优化pom.xml配置来减小SpringBoot项目的jar包大小,主要通过使用spring-boot-maven-plugin... 遇到一个问题,就是每次maven package或者maven install后target中的ja

Java中八大包装类举例详解(通俗易懂)

《Java中八大包装类举例详解(通俗易懂)》:本文主要介绍Java中的包装类,包括它们的作用、特点、用途以及如何进行装箱和拆箱,包装类还提供了许多实用方法,如转换、获取基本类型值、比较和类型检测,... 目录一、包装类(Wrapper Class)1、简要介绍2、包装类特点3、包装类用途二、装箱和拆箱1、装

如何利用Java获取当天的开始和结束时间

《如何利用Java获取当天的开始和结束时间》:本文主要介绍如何使用Java8的LocalDate和LocalDateTime类获取指定日期的开始和结束时间,展示了如何通过这些类进行日期和时间的处... 目录前言1. Java日期时间API概述2. 获取当天的开始和结束时间代码解析运行结果3. 总结前言在J

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操