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

相关推荐
allnlei2 小时前
s6-overlay - 装在 Docker 容器里的轻量级管家
java·docker·容器
IT_Octopus7 小时前
IntelliJ 本地日志路径自定义:`-DLOG_PATH=./logs` 为什么总“不听话“
java·log4j·intellij-idea
长征coder8 小时前
【无标题】
java·性能优化
浅念-8 小时前
一文吃透Git:本地操作|冲突处理|远程协作|GitFlow工作流详解
大数据·git·elasticsearch·搜索引擎·gitflow
新时代牛马9 小时前
PCI与PCIe 硬件原理、配置空间/BAR 与 Linux 驱动完整篇:从 LTSSM、TLP 到 ECAM 与probe
java·linux·服务器
Bs_MoneyMagnet9 小时前
基于springboot+vue的医疗健康便民服务平台的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring
sunshine22 girl10 小时前
Java学习一 环境配置2 Idea的入门使用和maven配置,项目启动脚本配置
java·maven
有点。10 小时前
*C++哈夫曼树与哈夫曼编码
java·c++·servlet
CRMEB系统商城11 小时前
CRMEB标准版系统(Java)v3.1正式发布
java·spring·微信小程序·php·教育电商
写后端的胖头鱼11 小时前
【高频面试题】Java 基础类型 + 包装类 + String 互相转换
java·开发语言