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

springboot初试elasticsearch

引入依赖

 elasticsearch的依赖版本与你elasticsearch要一致

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

索引库的操作 

创建索引库

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;import java.io.IOException;public class HotelIndexTest {// 创建索引语句public 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" +"        \"copy_to\": \"all\"\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" +"        \"copy_to\": \"all\"\n" +"      },\n" +"      \"city\":{\n" +"        \"type\": \"keyword\",\n" +"        \"copy_to\": \"all\"\n" +"      },\n" +"      \"starName\":{\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" +"      \"all\":{\n" +"        \"type\": \"text\",\n" +"        \"analyzer\": \"ik_max_word\"\n" +"      }\n" +"    }\n" +"  }\n" +"}";private RestHighLevelClient client;// 创建索引库@Testvoid createHotelIndex() throws IOException {// 1.创建Request对象CreateIndexRequest request = new CreateIndexRequest("hotel");// 2.准备请求的参数:DSL语句request.source(MAPPING_TEMPLATE, XContentType.JSON);// 3.发送请求client.indices().create(request, RequestOptions.DEFAULT);}// 初始化连接@BeforeEachvoid setUp() {this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://43.139.59.28:9200")));}// 关闭连接@AfterEachvoid tearDown() throws IOException {this.client.close();}
}

查看索引库

删除索引库

@Testvoid testDeleteHotelIndex() throws IOException {// 1.创建Request对象DeleteIndexRequest request = new DeleteIndexRequest("hotel");// 2.发送请求client.indices().delete(request, RequestOptions.DEFAULT);}

 查看索引库

文档的操作 

数据库实体类

数据库查询后的结果是一个Hotel类型的对象  

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;@Data
@TableName("tb_hotel")
public class Hotel {@TableId(type = IdType.INPUT)private Long id;private String name;private String address;private Integer price;private Integer score;private String brand;private String city;private String starName;private String business;private String longitude;private String latitude;private String pic;
}

 文档实体类

索引库查询后的结果是一个HotelDoc类型的对象,与Hotel不同在于横纵坐标的处理.

import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
public class HotelDoc {private Long id;private String name;private String address;private Integer price;private Integer score;private String brand;private String city;private String starName;private String business;private String location;private String pic;public HotelDoc(Hotel hotel) {this.id = hotel.getId();this.name = hotel.getName();this.address = hotel.getAddress();this.price = hotel.getPrice();this.score = hotel.getScore();this.brand = hotel.getBrand();this.city = hotel.getCity();this.starName = hotel.getStarName();this.business = hotel.getBusiness();// 合并横纵坐标this.location = hotel.getLatitude() + ", " + hotel.getLongitude();this.pic = hotel.getPic();}
}

新增文档

 @Resourceprivate HotelService hotelService;@Testvoid testAddDocument() throws IOException {// 1.根据id查询酒店数据Hotel hotel = hotelService.getById(61083L);// 2.转换为文档类型HotelDoc hotelDoc = new HotelDoc(hotel);// 3.将HotelDoc转jsonString json = JSON.toJSONString(hotelDoc);// 1.准备Request对象IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());// 2.准备Json文档request.source(json, XContentType.JSON);// 3.发送请求client.index(request, RequestOptions.DEFAULT);}

查询文档

@Testvoid testGetDocumentById() throws IOException {// 1.准备RequestGetRequest request = new GetRequest("hotel", "61083");// 2.发送请求,得到响应GetResponse response = client.get(request, RequestOptions.DEFAULT);// 3.解析响应结果String json = response.getSourceAsString();HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);System.out.println(hotelDoc);}

 结果

修改文档

修改我们讲过两种方式:

  • 全量修改:本质是先根据id删除,再新增

  • 增量修改:修改文档中的指定字段值  

在RestClient的API中,全量修改与新增的API完全一致,这里不再赘述,我们主要关注增量修改  

@Testvoid testUpdateDocument() throws IOException {// 1.准备RequestUpdateRequest request = new UpdateRequest("hotel", "61083");// 2.准备请求参数request.doc("price", "952","starName", "四钻");// 3.发送请求client.update(request, RequestOptions.DEFAULT);}

查看文档

删除文档

@Testvoid testDeleteDocument() throws IOException {// 1.准备RequestDeleteRequest request = new DeleteRequest("hotel", "61083");// 2.发送请求client.delete(request, RequestOptions.DEFAULT);}

 查询61083文档

批量导入文档

利用BulkRequest批量将数据库数据导入到索引库中

@Testvoid testBulkRequest() throws IOException {// 批量查询酒店数据List<Hotel> hotels = hotelService.list();// 1.创建RequestBulkRequest request = new BulkRequest();// 2.准备参数,添加多个新增的Requestfor (Hotel hotel : hotels) {// 2.1.转换为文档类型HotelDocHotelDoc hotelDoc = new HotelDoc(hotel);// 2.2.创建新增文档的Request对象request.add(new IndexRequest("hotel").id(hotelDoc.getId().toString()).source(JSON.toJSONString(hotelDoc), XContentType.JSON));}// 3.发送请求client.bulk(request, RequestOptions.DEFAULT);}

查看所有文档

 @Testvoid testMatchAll() throws IOException {// 1.准备RequestSearchRequest request = new SearchRequest("hotel");// 2.准备DSLrequest.source().query(QueryBuilders.matchAllQuery());// 3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析响应System.out.println(response);}

结果

http://www.lryc.cn/news/159249.html

相关文章:

  • Node.js安装教程图文详解
  • laragon 为 php 安装 Xdebug 扩展
  • 华为云 存在不支持迁移的外键解决方法
  • Linux 中的 cd 命令及示例
  • 【VUE】
  • 详解初阶数据结构之顺序表(SeqList)——单文件文件实现SeqList的增删查改
  • JavaScript中的深拷贝和浅拷贝
  • 树形结构的节点作为查询参数业务
  • sql:SQL优化知识点记录(十二)
  • 一.使用qt creator 设计显示GUI
  • sql:SQL优化知识点记录(八)
  • java笔试题,寻找多出来的元素
  • docker笔记3 Docker常规安装
  • 阻止 NTLM后无法登录远程桌面的原因
  • Docker网络功能
  • 如何入门 AI----如何确定学习目标
  • ABAP中加前导零和去前导零方法
  • 聊聊ShardingSphere是怎么进行sql重写的
  • 软件设计模式系列之二——抽象工厂模式
  • P2719 搞笑世界杯 (期望dp
  • spring cloud新版本使用loadbalancer替代Ribbon
  • 【Git-Exception】Git报错:fatal: unable to auto-detect email address
  • JVM性能优化 —— 类加载器,手动实现类的热加载
  • SSH连接MobaXterm
  • 本地虚机Jumpserver使用域名访问报错 使用IP+端口没有错误
  • 备战计算机二级公共基础知识(五)----数据库设计基础
  • 【excel密码】excel文件加密方法总结:
  • MySQL之用户管理
  • 伪静态web.config常见规则写法与参数介绍说明
  • 使用kubasz快速搭建Kubernetes集群