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

架构师系列-搜索引擎ElasticSearch(三)- Java API

SpringBoot整合ES
 

搭建SpringBoot工程,引入ElasticSearch相关坐标

 <!--引入es的坐标--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.4.0</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId><version>7.4.0</version></dependency><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.4.0</version></dependency>

测试
ElasticSearchConfig.java

@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticSearchConfig {private String host;private int port;public String getHost() {return host;}public void setHost(String host) {this.host = host;}public int getPort() {return port;}public void setPort(int port) {this.port = port;}@Beanpublic RestHighLevelClient client(){return new RestHighLevelClient(RestClient.builder(new HttpHost(host,port,"http")));}
}
@SpringBootTest
class ElasticsearchDemoApplicationTests {@Autowiredprivate RestHighLevelClient client;@Testvoid contextLoads() {/* //1.创建ES客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.149.135",9200,"http")));*/System.out.println(client);}

创建索引

添加索引

/*** 添加索引*/@Testpublic void addIndex() throws IOException {//1.使用client获取操作索引的对象IndicesClient indicesClient = client.indices();//2.具体操作,获取返回值CreateIndexRequest createRequest = new CreateIndexRequest("itheima");CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);//3.根据返回值判断结果System.out.println(response.isAcknowledged());}

 添加索引,并添加映射

/*** 添加索引*/@Testpublic void addIndexAndMapping() throws IOException {//1.使用client获取操作索引的对象IndicesClient indicesClient = client.indices();//2.具体操作,获取返回值CreateIndexRequest createRequest = new CreateIndexRequest("itcast");//2.1 设置mappingsString mapping = "{\n" +"      \"properties\" : {\n" +"        \"address\" : {\n" +"          \"type\" : \"text\",\n" +"          \"analyzer\" : \"ik_max_word\"\n" +"        },\n" +"        \"age\" : {\n" +"          \"type\" : \"long\"\n" +"        },\n" +"        \"name\" : {\n" +"          \"type\" : \"keyword\"\n" +"        }\n" +"      }\n" +"    }";createRequest.mapping(mapping,XContentType.JSON);CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);//3.根据返回值判断结果System.out.println(response.isAcknowledged());}

 查询、删除、判断索引

 /*** 查询索引*/@Testpublic void queryIndex() throws IOException {IndicesClient indices = client.indices();GetIndexRequest getReqeust = new GetIndexRequest("itcast");GetIndexResponse response = indices.get(getReqeust, RequestOptions.DEFAULT);//获取结果Map<String, MappingMetaData> mappings = response.getMappings();for (String key : mappings.keySet()) {System.out.println(key+":" + mappings.get(key).getSourceAsMap());}}/*** 删除索引*/@Testpublic void deleteIndex() throws IOException {IndicesClient indices = client.indices();DeleteIndexRequest deleteRequest = new DeleteIndexRequest("itheima");AcknowledgedResponse response = indices.delete(deleteRequest, RequestOptions.DEFAULT);System.out.println(response.isAcknowledged());}/*** 判断索引是否存在*/@Testpublic void existIndex() throws IOException {IndicesClient indices = client.indices();GetIndexRequest getRequest = new GetIndexRequest("itcast");boolean exists = indices.exists(getRequest, RequestOptions.DEFAULT);System.out.println(exists);}

添加文档

添加文档使用map作为数据

 /*** 添加文档,使用map作为数据*/@Testpublic void addDoc() throws IOException {//数据对象,mapMap data = new HashMap();data.put("address","北京昌平");data.put("name","大胖");data.put("age",20);//1.获取操作文档的对象IndexRequest request = new IndexRequest("itcast").id("1").source(data);//添加数据,获取结果IndexResponse response = client.index(request, RequestOptions.DEFAULT);//打印响应结果System.out.println(response.getId());}

添加文档使用对象作为数据

/*** 添加文档,使用对象作为数据*/@Testpublic void addDoc2() throws IOException {//数据对象,javaObjectPerson p = new Person();p.setId("2");p.setName("小胖2222");p.setAge(30);p.setAddress("陕西西安");//将对象转为jsonString data = JSON.toJSONString(p);//1.获取操作文档的对象IndexRequest request = new IndexRequest("itcast").id(p.getId()).source(data,XContentType.JSON);//添加数据,获取结果IndexResponse response = client.index(request, RequestOptions.DEFAULT);//打印响应结果System.out.println(response.getId());}public class Person {private String id;private String name;private int age;private String address;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "Person{" +"id='" + id + '\'' +", name='" + name + '\'' +", age=" + age +", address='" + address + '\'' +'}';}
}

修改、查询、删除文档
 

修改文档
 

  /*** 修改文档:添加文档时,如果id存在则修改,id不存在则添加*/@Testpublic void updateDoc() throws IOException {Person person=new Person();person.setId("2");person.setName("李四");person.setAge(20);person.setAddress("北京三环车王");String data = JSON.toJSONString(person);IndexRequest request = new IndexRequest("itcast").id(person.getId()).source(data,XContentType.JSON);IndexResponse response = client.index(request, RequestOptions.DEFAULT);System.out.println(response.getId());}

查询文档

/*** 根据id查询文档*/@Testpublic void findDocById() throws IOException {GetRequest getReqeust = new GetRequest("itcast","1");//getReqeust.id("1");GetResponse response = client.get(getReqeust, RequestOptions.DEFAULT);//获取数据对应的jsonSystem.out.println(response.getSourceAsString());}

删除文档

/*** 根据id删除文档*/@Testpublic void delDoc() throws IOException {DeleteRequest deleteRequest = new DeleteRequest("itcast","1");DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);System.out.println(response.getId());}

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

相关文章:

  • Ubuntu下配置Android NDK环境
  • 使用 vue3-sfc-loader 加载远程Vue文件, 在运行时动态加载 .vue 文件。无需 Node.js 环境,无需 (webpack) 构建步骤
  • stm32移植嵌入式数据库FlashDB
  • Ubuntu 安装Java、Git、maven、Jenkins等持续集成环境
  • 文件批量重命名并批量修改文件扩展名,支持随机大小写字母命名并修改扩展名字母
  • 【管理咨询宝藏70】MBB大型城投集团内外部环境分析报告
  • 服务器挖矿病毒解决ponscan,定时任务解决
  • 【鸿蒙开发】第二十一章 Media媒体服务(二)--- 音频播放和录制
  • 网络安全从入门到精通(特别篇I):Windows安全事件应急响应之Windows应急响应基础必备技能
  • 基于SpringBoot+Mybatis框架的私人影院预约系统(附源码,包含数据库文件)
  • 【SERVERLESS】AWS Lambda上实操
  • IDEA2023 开发环境配置
  • YOLOV5 + 双目相机实现三维测距(新版本)
  • 【计算机网络】(一)计算机网络概述
  • 前端npm常用命令总结
  • [尚硅谷flink] 检查点笔记
  • JVM虚拟机(五)强引用、软引用、弱引用、虚引用
  • (最新)itext7 freemarker动态模板转pdf
  • solidworks electrical 2D和3D有什么区别
  • 4.2、ipex-llm(原bigdl-llm)进行语音识别
  • 上海亚商投顾:创业板指低开低走 黄金、家电股逆势大涨
  • AIGC革新浪潮:大语言模型如何优化企业运营
  • Golang基础-12
  • python递归统计文件夹下pdf文件的数量
  • Kafka 硬件和操作系统
  • Kolla-ansible部署OpenStack集群
  • SHARE 203S PRO:倾斜摄影相机在地灾救援中的应用
  • MATLAB算法实战应用案例精讲-【数模应用】中介效应分析(补充篇)(附R语言和python代码实现)
  • Day96:云上攻防-云原生篇Docker安全系统内核版本漏洞CDK自动利用容器逃逸
  • python botos s3 aws