如何在Java中使用Elasticsearch

如何在Java中使用Elasticsearch

大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!

概述

Elasticsearch 是一个开源的分布式搜索引擎,用于全文搜索、结构化搜索和分析。本文将介绍如何在Java应用程序中使用Elasticsearch,包括连接、索引文档、搜索以及一些最佳实践。

连接到Elasticsearch

要在Java中使用Elasticsearch,首先需要添加 Elasticsearch Java 客户端库的依赖。推荐使用官方提供的 High Level REST Client。

Gradle 依赖配置示例
groovy 复制代码
dependencies {
    implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.17.0'
}
Maven 依赖配置示例
xml 复制代码
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.17.0</version>
</dependency>

建立连接

使用 RestClient 建立与 Elasticsearch 的连接:

java 复制代码
package cn.juwatech.elasticsearch;

import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

public class ElasticsearchClient {

    private static final String ELASTICSEARCH_HOST = "localhost";
    private static final int ELASTICSEARCH_PORT = 9200;

    public RestHighLevelClient createClient() {
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(ELASTICSEARCH_HOST, ELASTICSEARCH_PORT, "http")));
    }

    public static void main(String[] args) {
        ElasticsearchClient client = new ElasticsearchClient();
        RestHighLevelClient restClient = client.createClient();
        
        // 使用 restClient 进行后续操作,如索引文档、搜索等
    }
}

索引文档

向 Elasticsearch 中索引文档:

java 复制代码
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;

public class IndexDocumentExample {

    public void indexDocument(RestHighLevelClient client) throws IOException {
        IndexRequest request = new IndexRequest("posts");
        request.id("1");
        String jsonString = "{" +
                "\"user\":\"juwatech\"," +
                "\"postDate\":\"2024-07-01\"," +
                "\"message\":\"trying out Elasticsearch\"" +
                "}";
        request.source(jsonString, XContentType.JSON);

        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        System.out.println("Indexed document with ID: " + indexResponse.getId());
    }

    public static void main(String[] args) throws IOException {
        ElasticsearchClient client = new ElasticsearchClient();
        RestHighLevelClient restClient = client.createClient();

        IndexDocumentExample example = new IndexDocumentExample();
        example.indexDocument(restClient);

        restClient.close();
    }
}

搜索文档

从 Elasticsearch 中搜索文档:

java 复制代码
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

public class SearchDocumentExample {

    public void searchDocument(RestHighLevelClient client) throws IOException {
        SearchRequest searchRequest = new SearchRequest("posts");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.termQuery("user", "juwatech"));
        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println("Search hits: " + searchResponse.getHits().getTotalHits().value);
    }

    public static void main(String[] args) throws IOException {
        ElasticsearchClient client = new ElasticsearchClient();
        RestHighLevelClient restClient = client.createClient();

        SearchDocumentExample example = new SearchDocumentExample();
        example.searchDocument(restClient);

        restClient.close();
    }
}

最佳实践

  • 连接池管理:使用连接池管理 RestClient,提高资源利用率和性能。
  • 异常处理:合理处理连接、请求过程中的异常,保证代码的健壮性。
  • 索引设计:根据应用需求设计合理的索引结构,优化搜索和存储效率。

总结

通过本文的介绍,你学习了如何在Java应用程序中使用Elasticsearch,包括建立连接、索引文档、搜索以及一些最佳实践。这些技能可以帮助你更好地利用Elasticsearch的强大功能来支持你的应用需求。

微赚淘客系统3.0小编出品,必属精品!

相关推荐
callJJ44 分钟前
从零开始的图论讲解(1)——图的概念,图的存储,图的遍历与图的拓扑排序
java·数据结构·算法·深度优先·图论·广度优先·图搜索算法
喜欢便码3 小时前
JS小练习0.1——弹出姓名
java·前端·javascript
王磊鑫4 小时前
重返JAVA之路-初识JAVA
java·开发语言
半兽先生4 小时前
WebRtc 视频流卡顿黑屏解决方案
java·前端·webrtc
南星沐5 小时前
Spring Boot 常用依赖介绍
java·前端·spring boot
代码不停6 小时前
Java中的异常
java·开发语言
何似在人间5756 小时前
多级缓存模型设计
java·jvm·redis·缓存
多云的夏天6 小时前
ubuntu24.04-MyEclipse的项目导入到 IDEA中
java·intellij-idea·myeclipse
Fanxt_Ja7 小时前
【数据结构】红黑树超详解 ---一篇通关红黑树原理(含源码解析+动态构建红黑树)
java·数据结构·算法·红黑树
Aphelios3807 小时前
TaskFlow开发日记 #1 - 原生JS实现智能Todo组件
java·开发语言·前端·javascript·ecmascript·todo