当前位置: 首页 > news >正文

如何在Java中使用Elasticsearch

如何在Java中使用Elasticsearch

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

概述

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

连接到Elasticsearch

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

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

建立连接

使用 RestClient 建立与 Elasticsearch 的连接:

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 中索引文档:

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 中搜索文档:

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

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • uniapp + vite中 uni.scss 使用 /deep/ 不生效(踩坑记录三)
  • Java面试题:sql优化
  • PHP框架Symfony详解
  • mxd的地图文件 像百度地图那样在vue页面上展示出来
  • JS滚动时显示元素
  • Vuetify3:隐藏超出的文字
  • Python正则表达式的入门用法(上)
  • 快速上手文心一言指令:解锁AI交互新体验
  • 【linux/shell】shell中使用for循环读取数据
  • three.js利用着色器实现波浪效果
  • 新手教学系列——慎用Flask-SQLAlchemy慢日志记录
  • C++_STL---list
  • 构建现代医疗:互联网医院系统源码与电子处方小程序开发教学
  • 身边的故事(十三):阿文的故事:出现
  • js 复制文本带样式
  • 【附node操作实例】redis简明入门系列—字符串类型
  • 2017届校招提前批面试回顾
  • canvas绘制圆角头像
  • egg(89)--egg之redis的发布和订阅
  • FastReport在线报表设计器工作原理
  • laravel5.5 视图共享数据
  • magento2项目上线注意事项
  • python大佬养成计划----difflib模块
  • springMvc学习笔记(2)
  • VuePress 静态网站生成
  • 复杂数据处理
  • 开发基于以太坊智能合约的DApp
  • 前端临床手札——文件上传
  • 实战:基于Spring Boot快速开发RESTful风格API接口
  • 微信公众号开发小记——5.python微信红包
  • 小程序button引导用户授权
  • 正则学习笔记
  • Java性能优化之JVM GC(垃圾回收机制)
  • ​决定德拉瓦州地区版图的关键历史事件
  • ​软考-高级-系统架构设计师教程(清华第2版)【第1章-绪论-思维导图】​
  • ​油烟净化器电源安全,保障健康餐饮生活
  • # C++之functional库用法整理
  • # include “ “ 和 # include < >两者的区别
  • #《AI中文版》V3 第 1 章 概述
  • #我与Java虚拟机的故事#连载07:我放弃了对JVM的进一步学习
  • $jQuery 重写Alert样式方法
  • (14)学习笔记:动手深度学习(Pytorch神经网络基础)
  • (C语言)fread与fwrite详解
  • (html5)在移动端input输入搜索项后 输入法下面为什么不想百度那样出现前往? 而我的出现的是换行...
  • (NSDate) 时间 (time )比较
  • (二十五)admin-boot项目之集成消息队列Rabbitmq
  • (附源码)SSM环卫人员管理平台 计算机毕设36412
  • (一)使用Mybatis实现在student数据库中插入一个学生信息
  • **PHP分步表单提交思路(分页表单提交)
  • .net core使用RPC方式进行高效的HTTP服务访问
  • .NET Framework 3.5中序列化成JSON数据及JSON数据的反序列化,以及jQuery的调用JSON
  • .NET Project Open Day(2011.11.13)
  • .net和jar包windows服务部署
  • .NET使用HttpClient以multipart/form-data形式post上传文件及其相关参数
  • .NET应用架构设计:原则、模式与实践 目录预览