Elasticsearch基础——常用API操作(SpringBoot整合ElasticSearch)

it2024-12-19  10

学完elasticsearch的API操作,为了防止遗忘,写篇博客记录下来,方便以后使用。

1.创建一个SpringBoot项目,添加elasticsearch的依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>

通过在pom.xml文件中加入下面配置,设置elasticsearch的版本

<properties> <elasticsearch.version>7.6.1</elasticsearch.version> </properties>

2.创建配置文件,来配置elasticsearch的ip和端口号以及使用的协议

配置代码如下:

@Configuration public class ElasticSearchClientConfig { @Bean public RestHighLevelClient restHighLevelClient(){ RestHighLevelClient client; client = new RestHighLevelClient( RestClient.builder(new HttpHost("127.0.0.1",9200,"http")) ); return client; } }

在bean包下创建一个实体类,用来测试上传数据

package com.hist.testesapi.bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data @AllArgsConstructor @NoArgsConstructor @Component @ConfigurationProperties(value = "user") public class User { private String name; private Integer id; private String sex; }

为了能够方便将对象转为json字符串,引入fastjson依赖

<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>

3.配置完成后,开始Elasticsearch的常用API的测试

API的测试在测试类中完成

注入客户端对象

@SpringBootTest class TestEsApiApplicationTests { @Autowired RestHighLevelClient restHighLevelClient; }

3.1测试获取索引,判断其是否存在

@Test void testExistsIndex() throws IOException { GetIndexRequest getIndexRequest = new GetIndexRequest("index"); boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT); System.out.println(exists); }

3.2测试创建索引

@Test void testCreateIndex() throws IOException { CreateIndexRequest createIndexRequest = new CreateIndexRequest("index"); AcknowledgedResponse response = restHighLevelClient.indices().create(createIndexRequest,RequestOptions.DEFAULT); System.out.println(response); }

3.3测试删除索引

@Test void testDeleteIndex(){ DeleteIndexRequest request = new DeleteIndexRequest("index"); AcknowledgedResponse delete = restHighLevelClient.indices().delete(request , RequestOptions.DEFAULT); System.out.println(delete.isAcknowledged()); }

3.4测试删除文档

@Test void testAddDoucment2() throws IOException { //创建对象 User user = new User("李四", 1, "男"); //创建请求 IndexRequest request = new IndexRequest("index"); //规划put request.id("1"); request.timeout("1s"); //超时时间 //将我们的数据放入请求中 request.source(JSON.toJSONString(user),XContentType.JSON); //客户端发送请求,获取响应结果 IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT); System.out.println(indexResponse.toString());//打印结果 System.out.println(indexResponse.status()); //打印状态 }

3.5获取文档,判断是否存在

@Test void testIsExistsDoucment() throws IOException { GetRequest getRequest = new GetRequest("index", "1"); //不获取返回的_source的上下文 getRequest.fetchSourceContext(new FetchSourceContext(false)); getRequest.storedFields("_none_"); boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT); System.out.println(exists); }

3.6获取文档的内容

@Test void testGetDocument() throws IOException { GetRequest getRequest = new GetRequest("index", "1"); GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT); //打印文档内容 System.out.println(getResponse.getSourceAsString()); //打印返回的对象 System.out.println(getResponse); }

3.7更新文档的信息

@Test void testUpdateRequest(){ UpdateRequest updateRequest = new UpdateRequest("index", "1"); updateRequest.timeout(new TimeValue(1,TimeUnit.MILLISECONDS)); //创建对象 User user = new User("aaa", 1, "女"); updateRequest.doc(JSON.toJSONString(user),XContentType.JSON); UpdateResponse updateResponse = restHighLevelClient.update(, RequestOptions.DEFAULT); //打印结果的状态 System.out.println(updateResponse.status()); }

3.8删除文档记录

@Test void testDeleteRequest() throws IOException { DeleteRequest deleteRequest = new DeleteRequest("index", "1"); deleteRequest.timeout(new TimeValue(10,TimeUnit.MILLISECONDS)); DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT); //删除状态 System.out.println(deleteResponse.status()); }

3.8批量插入数量——指定id

@Test void testBulkRequest() throws IOException { BulkRequest bulkRequest = new BulkRequest(); bulkRequest.timeout("10s"); ArrayList<User> userArrayList = new ArrayList<>(); userArrayList.add(new User("tom1",1,"man")); userArrayList.add(new User("tom2",2,"man")); userArrayList.add(new User("tom3",3,"man")); userArrayList.add(new User("tom4",4,"man")); userArrayList.add(new User("tom5",5,"man")); userArrayList.add(new User("tom6",6,"man")); //批处理请求 for (int i = 0; i > userArrayList.size(); i++){ bulkRequest.add( new IndexRequest("index").id(""+(i+1)).source( JSON.toJSONString(userArrayList.get(i)),XContentType.JSON)); } //执行插入 BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); //查看插入返回的状态值 System.out.println(bulkResponse.status()); }

3.9批量插入,不指定id

//批量插入 @Test void testBulkRequest() throws IOException { BulkRequest bulkRequest = new BulkRequest(); bulkRequest.timeout("10s"); ArrayList<User> userList = new ArrayList<>(); userList.add(new User("hist1",1,"man")); userList.add(new User("hist2",2,"man")); userList.add(new User("hist3",3,"man")); userList.add(new User("hist4",4,"man")); userList.add(new User("hist5",5,"man")); userList.add(new User("hist6",6,"man")); //不指定插入的id for (int i = 0; i < userList.size(); i++) { //批量更新和批量删除,就在这里修改对应的请求就可以了 bulkRequest.add( new IndexRequest("hudashuai").source(JSON.toJSONString(userList.get(i)),XContentType.JSON) ); } BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); System.out.println(bulk.status()); }

3.10查询

//查询 // SearchRequest 搜索请求 // SearchSourceBuilder 条件构造 // HighlightBuilder 构建高亮 // TermQueryBuilder 精确查询 // MatchAllQueryBuilder 匹配所有 // xxx QueryBuilder 对应我们刚刚看到的命令 @Test void testSearch() throws IOException { SearchRequest searchRequest = new SearchRequest("index"); //构建搜索条件 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // QueryBuilders.termQuery() 精确匹配 // QueryBuilders.matchAllQuery()匹配所有 //下面测试精确匹配 TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "tom1"); searchSourceBuilder.query(termQueryBuilder); //设置超时时间 searchSourceBuilder.timeout(new TimeValue(30,TimeUnit.MILLISECONDS)); searchRequest.source(searchSourceBuilder); //执行搜索 SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); System.out.println(JSON.toJSONString(searchResponse.getHits())); System.out.println("===================="); for (SearchHit hit : searchResponse.getHits().getHits()) { System.out.println(hit.getSourceAsMap()); //打印结果 } }

3.11高亮查询

//高亮 @Test void testHightLighter() throws IOException { //条件搜索 SearchRequest searchRequest = new SearchRequest("index"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //分页 searchSourceBuilder.from(1); searchSourceBuilder.size(10); //精确匹配 TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "tom"); searchSourceBuilder.query(termQueryBuilder); searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.MILLISECONDS)); //高亮 HighlightBuilder highlightBuilder = new HighlightBuilder(); //设置高亮字段 highlightBuilder.field("name"); //设置多个高亮显示为false,根据需求也可以设置为true highlightBuilder.requireFieldMatch(false); //字段前缀 highlightBuilder.preTags("<span style='color:red;'"); //后缀 highlightBuilder.postTags("</span>"); searchSourceBuilder.highlighter(highlightBuilder); //执行搜索 searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); //解析结果 ArrayList<Map<String,Object>> list = new ArrayList<>(); for (SearchHit hit : searchResponse.getHits()) { Map<String, HighlightField> highlightFields = hit.getHighlightFields(); HighlightField name = highlightFields.get("name"); //获取高亮后的字段 //获取原先的结果 Map<String, Object> sourceAsMap = hit.getSourceAsMap(); //解析高亮字段,将原来的字段换位我们高亮的字段即可 if(name != null){ Text[] fragments = name.fragments(); String newName = ""; for (Text fragment : fragments) { newName += fragment; } //将高亮字段替换掉原来的内容 sourceAsMap.put("name",newName); } list.add(sourceAsMap); } for (Map<String, Object> stringObjectMap : list) { System.out.println(stringObjectMap); //打印看一下结果 } }
最新回复(0)