如何在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小编出品,必属精品!

相关推荐
华农第一蒟蒻19 小时前
一次服务器CPU飙升的排查与解决
java·运维·服务器·spring boot·arthas
m0_7482299919 小时前
帝国CMS后台搭建全攻略
java·c语言·开发语言·学习
码农娟20 小时前
Hutool XML工具-XmlUtil的使用
xml·java
草青工作室20 小时前
java-FreeMarker3.4自定义异常处理
java·前端·python
java1234_小锋20 小时前
Java中读写锁的应用场景是什么?
java·开发语言
闻哥20 小时前
从 AJAX 到浏览器渲染:前端底层原理与性能指标全解析
java·前端·spring boot·ajax·okhttp·面试
「QT(C++)开发工程师」20 小时前
C++ 多种单例模式
java·c++·单例模式
短剑重铸之日20 小时前
《SpringCloud实用版》统一认证授权:Spring Authorization Server + OAuth2 + JWT 生产级方案
java·后端·spring·jwt·oauth2
哲-哲20 小时前
WVP+ZLM搭建碰到问题
java
编程彩机20 小时前
互联网大厂Java面试:从Spring Cloud到分布式事务的技术场景解析
java·spring cloud·微服务·消息队列·分布式事务