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

elasticsearch--RestClient操作索引库(java)

参考:https://blog.csdn.net/CYK_byte/article/details/133255773

https://blog.csdn.net/weixin_45404884/article/details/137402463

java pom依赖:

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

测试案例:

测试类,开始是创建restClient。结束是关闭client

private RestHighLevelClient client;@BeforeEach
public void setUp() {client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http//127.0.0.1:9200")//将来如果是集群,这里还可以通过 HttpHost.create 继续连接多个节点));
}@AfterEach
public void tearDown() throws IOException {client.close();
}
这里我们创建一个测试类 HotelIndexTest ,用来演示 RestClient 操作的相关方法.
package com.gen.test.elc;import com.gen.test.elasticsearch.ElcTestApplication;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import java.io.IOException;
import java.util.Date;@SpringBootTest(classes = ElcTestApplication.class)
public class HotelIndexTest {private RestHighLevelClient client;@BeforeEachpublic void setUp() {client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http//127.0.0.1:9200")//将来如果是集群,这里还可以通过 HttpHost.create 继续连接多个节点));}@AfterEachpublic void tearDown() throws IOException {client.close();}/*** 创建索引库* */private static final String MAPPING_TEMPLATE = "{\n" +"  \"mappings\": {\n" +"    \"properties\": {\n" +"      \"id\":{\n" +"        \"type\": \"keyword\"\n" +"      },\n" +"      \"name\":{\n" +"        \"type\": \"text\",\n" +"        \"analyzer\": \"ik_max_word\"\n" +"      },\n" +"      \"address\":{\n" +"        \"type\": \"keyword\",\n" +"        \"index\": false\n" +"      },\n" +"      \"price\":{\n" +"        \"type\": \"integer\"\n" +"      },\n" +"      \"score\":{\n" +"        \"type\": \"integer\"\n" +"      },\n" +"      \"brand\":{\n" +"        \"type\": \"keyword\"\n" +"      },\n" +"      \"city\":{\n" +"        \"type\": \"keyword\"\n" +"      },\n" +"      \"star_name\":{\n" +"        \"type\": \"keyword\"\n" +"      },\n" +"      \"business\":{\n" +"        \"type\": \"keyword\"\n" +"      },\n" +"      \"location\":{\n" +"        \"type\": \"geo_point\"\n" +"      },\n" +"      \"pic\":{\n" +"        \"type\": \"keyword\",\n" +"        \"index\": false\n" +"      }\n" +"    }\n" +"  }\n" +"}";@Testpublic void testCreateHotelIndex() throws IOException {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://localhost:9200")));// 1.创建 Request 对象CreateIndexRequest request = new CreateIndexRequest("hotel");// 2.请求参数, MAPPING_TEMPLATE是静态常量字符串,内容是创建索引库的 DSL语句request.source(MAPPING_TEMPLATE, XContentType.JSON);// 3.发起请求CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);System.out.println(response);}/*** 删除索引库* */@Testpublic void testDeleteHotelIndex() throws IOException {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://localhost:9200")));// 1.创建 Request对象DeleteIndexRequest request = new DeleteIndexRequest("hotel");// 2.发起请求AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);System.out.println(delete);}/*** 判断索引库是否存在* */@Testpublic void testExistsHotelIndex() throws IOException {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://localhost:9200")));// 1.创建 Request对象GetIndexRequest request = new GetIndexRequest("hotel");// 2.发起请求boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);System.out.println(exists);}/*-----------------------------------文档操作----------------------------------------*//*** 添加酒店数据到索引库* */@Testpublic void testIndexDocument() throws IOException {// 创建Elasticsearch客户端RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));try {// 构建请求Request request = new Request("POST", "/hotel/_doc/1"); // 自定义请求URLString template = "{\n" +"  \"name\": \"张三\",\n" +"  \"email\": \"zy@itcast.cn\"\n" +"}";request.setJsonEntity(template); // 设置请求体// 发送请求并处理响应Response response = client.getLowLevelClient().performRequest(request);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == 200) { // 成功创建的状态码System.out.println("Document created successfully.");} else {System.err.println("Failed to create document. Status code: " + statusCode);}} finally {// 关闭客户端client.close();}}/***根据 id 查询酒店数据* */@Testpublic void testGetDocumentById() throws IOException {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://localhost:9200")));// 1.创建 request对象GetRequest request = new GetRequest("hotel", "1");// 2.发送请求,得到结果GetResponse response = client.get(request, RequestOptions.DEFAULT);// 3.解析结果String json = response.getSourceAsString();System.out.println(json);client.close();}/*** 根据 id 修改酒店数据* */@Testpublic void testUpdateDocumentById() throws IOException {// 创建Elasticsearch客户端RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));try {// 构建请求Request request = new Request("POST", "/hotel/_doc/1"); // 自定义请求URLString template = "{\n" +"  \"name\": \"张三\",\n" +"  \"email\": \"2312123@163.com\"\n" +"}";request.setJsonEntity(template); // 设置请求体// 发送请求并处理响应Response response = client.getLowLevelClient().performRequest(request);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == 200) { // 成功创建的状态码System.out.println("Document created successfully.");} else {System.err.println("Failed to create document. Status code: " + statusCode);}} finally {// 关闭客户端client.close();}}/*** 根据 id 删除文档数据* */@Testpublic void testDeleteDocumentById() throws IOException {// 创建Elasticsearch客户端RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));try {// 构建请求Request request = new Request("DELETE", "/hotel/_doc/1"); // 自定义请求URL// 发送请求并处理响应Response response = client.getLowLevelClient().performRequest(request);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == 200) { // 成功创建的状态码System.out.println("Document created successfully.");} else {System.err.println("Failed to create document. Status code: " + statusCode);}} finally {// 关闭客户端client.close();}}}

二、springboot-data结合

参考:https://blog.csdn.net/m0_64210833/article/details/135274603

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • linux查询占用端口 杀死占用端口进程
  • 基于OpenCV+MFC的视频读取与对象跟踪平台
  • MathType7.4中文版本功能详解!你的数学公式编辑神器
  • Conda Shell初始化指南:激活你的开发环境
  • RK3568平台开发系列讲解(文件系统篇)文件描述符 fd(File Descriptor)是什么?
  • 电脑自动重启是什么原因?重启原因排查和解决办法!
  • C++_sizeof的相关知识点
  • C++模板元一生之友之:std::enable_if
  • 若依vue版前端白名单处理
  • php之 进行签名公钥、私钥(SHA1withRSA签名)
  • oracle(19c)用户管理
  • pytorch学习笔记3 tensor索引和切片
  • 如何使用哔哩哔哩下载与缓存视频?
  • 【无标题】图像增强技术:直方图均衡化、拉普拉斯算子、对数变换与伽马变换
  • Markdown语法学习
  • [rust! #004] [译] Rust 的内置 Traits, 使用场景, 方式, 和原因
  • 2018以太坊智能合约编程语言solidity的最佳IDEs
  • Git的一些常用操作
  • Leetcode 27 Remove Element
  • LeetCode刷题——29. Divide Two Integers(Part 1靠自己)
  • PAT A1050
  • SSH 免密登录
  • 对象管理器(defineProperty)学习笔记
  • 和 || 运算
  • 前端知识点整理(待续)
  • 浅谈JavaScript的面向对象和它的封装、继承、多态
  • 数组大概知多少
  • 一个完整Java Web项目背后的密码
  • 原生Ajax
  • 第二十章:异步和文件I/O.(二十三)
  • ​一、什么是射频识别?二、射频识别系统组成及工作原理三、射频识别系统分类四、RFID与物联网​
  • ###C语言程序设计-----C语言学习(3)#
  • #php的pecl工具#
  • #我与Java虚拟机的故事#连载12:一本书带我深入Java领域
  • (android 地图实战开发)3 在地图上显示当前位置和自定义银行位置
  • (k8s中)docker netty OOM问题记录
  • (二)基于wpr_simulation 的Ros机器人运动控制,gazebo仿真
  • (非本人原创)史记·柴静列传(r4笔记第65天)
  • (附源码)springboot 个人网页的网站 毕业设计031623
  • (三)Honghu Cloud云架构一定时调度平台
  • (学习日记)2024.04.04:UCOSIII第三十二节:计数信号量实验
  • (一)Mocha源码阅读: 项目结构及命令行启动
  • (原)Matlab的svmtrain和svmclassify
  • (原創) 人會胖會瘦,都是自我要求的結果 (日記)
  • (转)ObjectiveC 深浅拷贝学习
  • (转)视频码率,帧率和分辨率的联系与区别
  • (转载)虚幻引擎3--【UnrealScript教程】章节一:20.location和rotation
  • ***php进行支付宝开发中return_url和notify_url的区别分析
  • .NET Core 中的路径问题
  • .NET 的程序集加载上下文
  • .NET 设计模式—适配器模式(Adapter Pattern)
  • .NET 中让 Task 支持带超时的异步等待
  • .net遍历html中全部的中文,ASP.NET中遍历页面的所有button控件
  • .NET的微型Web框架 Nancy
  • .net流程开发平台的一些难点(1)