ElasticSearch Java API
2022/1/15 1:05:15
本文主要是介绍ElasticSearch Java API,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
目录- SpringBoot 整合 ES
- 操作索引
- 创建索引
- 查询索引
- 删除索引
- 操作文档
- 添加文档
- 修改文档
- 查询文档
- 删除文档
- bulk 批量操作
SpringBoot 整合 ES
1)引入 ElasticSearch 相关坐标:
<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>
2)ElasticSearchConfig.java(ES 配置类):
package com.example.es_demo.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix = "elasticsearch") public class EsConfig { 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; } @Bean public RestHighLevelClient client(){ return new RestHighLevelClient(RestClient.builder( new HttpHost(host, port, "http") )); } }
3)测试类:
- 注意:使用 @Autowired 注入 RestHighLevelClient 时如果报红线,则是因为配置类所在的包和测试类所在的包,两者包名不一致造成的。
package com.example.es_demo; import org.elasticsearch.client.RestHighLevelClient; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class EsDemoApplicationTests { @Autowired RestHighLevelClient client; @Test void contextLoads() { System.out.println(client); } }
操作索引
创建索引
/** * 添加索引 */ @Test public void addIndex() throws IOException { // 1.使用client获取操作索引对象 IndicesClient indices = client.indices(); // 2.创建索引 CreateIndexRequest createIndexRequest = new CreateIndexRequest("index1"); CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT); // 3.根据返回值判断结果 System.out.println(createIndexResponse.isAcknowledged()); } /** * 添加索引,并添加映射 */ @Test public void addIndexAndMapping() throws IOException { // 1.使用client获取操作索引对象 IndicesClient indices = client.indices(); // 2.添加索引 CreateIndexRequest createIndexRequest = new CreateIndexRequest("index2"); // 3.添加mappings String 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" + " }"; createIndexRequest.mapping(mapping, XContentType.JSON); CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT); // 4.根据返回值判断结果 System.out.println(createIndexResponse.isAcknowledged()); }
查询索引
/** * 查询索引 */ @Test public void queryIndex() throws IOException { IndicesClient indices = client.indices(); GetIndexRequest getRequest=new GetIndexRequest("index2"); GetIndexResponse response = indices.get(getRequest, RequestOptions.DEFAULT); Map<String, MappingMetaData> mappings = response.getMappings(); for (String key : mappings.keySet()) { System.out.println(key+"==="+mappings.get(key).getSourceAsMap()); // index2==={properties={address={analyzer=ik_max_word, type=text}, name={type=keyword}, age={type=long}}} } } /** * 判断索引是否存在 */ @Test public void existIndex() throws IOException { IndicesClient indices = client.indices(); GetIndexRequest getIndexRequest=new GetIndexRequest("index1"); boolean exists = indices.exists(getIndexRequest, RequestOptions.DEFAULT); System.out.println(exists); }
删除索引
/** * 删除索引 */ @Test public void deleteIndex() throws IOException { IndicesClient indices = client.indices(); DeleteIndexRequest deleteRequest=new DeleteIndexRequest("index2"); AcknowledgedResponse delete = indices.delete(deleteRequest, RequestOptions.DEFAULT); // 返回是否删除成功 System.out.println(delete.isAcknowledged()); }
操作文档
引入阿里巴巴的 JSON 格式转换库:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.4</version> </dependency>
添加文档
注意:在仅有索引的情况下也可以添加文档,且在有映射的情况下也可以新增字段,两者操作均会自动添加默认类型。
/** * 添加文档,使用map作为数据 */ @Test public void addDoc() throws IOException { // map数据 Map data = new HashMap(); data.put("address", "北京昌平"); data.put("name", "大胖"); data.put("age", 20); // 获取操作文档的对象 IndexRequest request = new IndexRequest("index2").id("1").source(data); // 添加数据,获取结果 IndexResponse response = client.index(request, RequestOptions.DEFAULT); //打印响应结果 System.out.println(response.getId()); } /** * 添加文档,使用对象作为数据 */ @Test public void addDoc2() throws IOException { // 对象数据 Person p = new Person(); p.setId("3"); p.setName("小胖3333"); p.setAge(30); p.setAddress("广东深圳"); p.setHobby("basketball"); // 将对象转为json String data = JSON.toJSONString(p); // 获取操作文档的对象 IndexRequest request = new IndexRequest("index2").id(p.getId()).source(data, XContentType.JSON); // 添加数据,获取结果 IndexResponse response = client.index(request, RequestOptions.DEFAULT); // 打印响应结果 System.out.println(response.getId());
修改文档
/** * 修改文档:添加文档时,如果id存在则修改,id不存在则添加 */ @Test public 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查询文档 */ @Test public void getDoc() throws IOException { //设置查询的索引、文档 GetRequest indexRequest=new GetRequest("itcast","2"); GetResponse response = client.get(indexRequest, RequestOptions.DEFAULT); System.out.println(response.getSourceAsString()); }
删除文档
/** * 根据id删除文档 */ @Test public void delDoc() throws IOException { //设置要删除的索引、文档 DeleteRequest deleteRequest=new DeleteRequest("itcast","1"); DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT); System.out.println(response.getId()); }
bulk 批量操作
/** * Bulk 批量操作 */ @Test public void test2() throws IOException { // 创建bulkrequest对象,整合所有操作 BulkRequest bulkRequest =new BulkRequest(); // 1. 删除5号记录 DeleteRequest deleteRequest=new DeleteRequest("person1", "5"); bulkRequest.add(deleteRequest); // 2. 添加6号记录 Map<String, Object> map=new HashMap<>(); map.put("name", "六号"); IndexRequest indexRequest=new IndexRequest("person1").id("6").source(map); bulkRequest.add(indexRequest); // 3. 修改3号记录 名称为 “三号” Map<String, Object> mapUpdate=new HashMap<>(); mapUpdate.put("name", "三号"); UpdateRequest updateRequest=new UpdateRequest("person1", "3").doc(mapUpdate); bulkRequest.add(updateRequest); // 执行批量操作 BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT); System.out.println(response.status()); }
这篇关于ElasticSearch Java API的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-12百万架构师第十五课:源码分析:Spring 源码分析:SpringMVC核心原理及源码分析|JavaGuide
- 2025-01-11有哪些好用的家政团队管理工具?
- 2025-01-11营销人必看的GTM五个指标
- 2025-01-11办公软件在直播电商前期筹划中的应用与推荐
- 2025-01-11提升组织效率:上级管理者如何优化跨部门任务分配
- 2025-01-11酒店精细化运营背后的协同工具支持
- 2025-01-11跨境电商选品全攻略:工具使用、市场数据与选品策略
- 2025-01-11数据驱动酒店管理:在线工具的核心价值解析
- 2025-01-11cursor试用出现:Too many free trial accounts used on this machine 的解决方法
- 2025-01-11百万架构师第十四课:源码分析:Spring 源码分析:深入分析IOC那些鲜为人知的细节|JavaGuide