听说微信搜索《Java鱼仔》会变更强!
本文收录于JavaStarter ,里面有我完整的Java系列文章,学习或面试都可以看看!
(一)概述
有人说学习一项技术最好的资料是官方文档,对大部分技术来说确实是这样的。但是官方文档不一定适合每个人去看,比如一个初学者,直接让他看Spring的官方文档,其实是不合适的。今天我会结合ElasticSearch的一个客户端官方文档介绍ES在Java中的API应用。
官方文档不一定好找,这里直接给出地址:
你可以选择自己对应版本的文档来参考,我这里选择的是7.6版本,选用的是Java High Level REST Client。
(二)项目搭建
2.1 引入依赖
首先需要创建一个项目,创建项目就不介绍了,引入ES核心依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency>
为了防止版本问题导致服务器客户端冲突,尽量将ES的版本设置的和自己安装的服务器端版本一致:
<properties><java.version>1.8</java.version><elasticsearch.version>7.6.1</elasticsearch.version></properties>
后续还会用一些json和web以及测试的操作,引入这些依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency>
2.2 项目基本配置
编写个配置类注入restHighLevelClient对象:
publicclassElasticSearchConfig { publicRestHighLevelClientrestHighLevelClient(){ RestHighLevelClientclient=newRestHighLevelClient( RestClient.builder( newHttpHost("192.168.78.128",9200,"http") ) ); returnclient; } }
后续会用到实体类,这里先提供了:
publicclassUser { privateStringname; privateStringaddress; }
接下来的操作都在SpringBootTest中进行,首先通过@Autowired注入
RestHighLevelClient对象classElasticsearchdemoApplicationTests { privateRestHighLevelClientrestHighLevelClient; }
(三)索引API
还是按照学习ES语法的顺序学习语法,找到索引API ,API中的操作很多,我主要选一些重要的讲一下
3.1 创建索引
创建索引的主要对象是CreateIndexRequest
publicvoidtestCreateIndex() throwsIOException { //创建索引CreateIndexRequestrequest=newCreateIndexRequest("test_index"); CreateIndexResponsecreateIndexResponse=restHighLevelClient.indices().create(request, RequestOptions.DEFAULT); System.out.println(createIndexResponse.isAcknowledged()); }
创建CreateIndexRequest对象,设置相关属性,比如切片数,副本数,超时时间等等,然后通过restHighLevelClient创建索引,获得一个结果响应。
//设置分片和副本request.settings(Settings.builder() .put("index.number_of_shards", 3) .put("index.number_of_replicas", 2) );
3.2 获取索引
获取一个索引,主要对象是GetIndexRequest
publicvoidtestGetIndex() throwsIOException { //获取索引GetIndexRequestrequest=newGetIndexRequest("test_index"); GetIndexResponsegetIndexResponse=restHighLevelClient.indices().get(request, RequestOptions.DEFAULT); System.out.println(getIndexResponse); }
3.3 判断索引是否存在
用的也是GetIndexRequest
publicvoidtestExistsIndex() throwsIOException { //获取索引GetIndexRequestrequest=newGetIndexRequest("test_index"); booleanexists=restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT); System.out.println(exists); }
3.4 删除索引
删除索引的请求对象是DeleteIndexRequest
publicvoidtestDeleteIndex() throwsIOException { DeleteIndexRequestrequest=newDeleteIndexRequest("test_index"); AcknowledgedResponsedelete=restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT); System.out.println(delete.isAcknowledged()); }
对索引的操作可以通过图形化界面来实现,了解增删改即可。
(四)文档API
文档的API分为单个文档处理和批量文档处理,我会介绍单个文档的增删改查和一个批量文档API
4.1 创建文档
在用语法创建文档的时候,是这样的:
PUThttp://ip:port/索引名/类型名/文档id{ "name":"javayz", "address":"hz"}
使用代码是这样的:请求对象为IndexRequest
publicvoidtestCreateDoc() throwsIOException { // PUT http://ip:port/索引名/类型名/文档idUseruser=newUser("javayz","hz"); IndexRequestrequest=newIndexRequest("text_index"); request.id("1"); request.source(JSON.toJSONString(user), XContentType.JSON); IndexResponseindex=restHighLevelClient.index(request, RequestOptions.DEFAULT); System.out.println(index.status()); }
其实两者十分相似,这也是学技术要先学基础的原因。有了基础一看就懂。
4.2 获取文档
获取文档和判断是否存在这里放在一起写,请求对象都是GetRequest :
publicvoidtestGetDoc() throwsIOException{ GetRequestrequest=newGetRequest("text_index"); request.id("1"); booleanexists=restHighLevelClient.exists(request, RequestOptions.DEFAULT); if (exists){ GetResponsedocumentFields=restHighLevelClient.get(request, RequestOptions.DEFAULT); StringsourceAsString=documentFields.getSourceAsString(); System.out.println(sourceAsString); }else{ System.out.println(exists); } }
4.3 更新文档
更新文档的请求对象是UpdateRequest
publicvoidtestUpdateDoc() throwsIOException{ UpdateRequestrequest=newUpdateRequest("text_index","1"); Useruser=newUser("javayz2","hz"); request.doc(JSON.toJSONString(user),XContentType.JSON); UpdateResponseresponse=restHighLevelClient.update(request, RequestOptions.DEFAULT); System.out.println(response.status()); }
4.4 删除文档
删除文档的请求对象是DeleteRequest
publicvoidtestDeleteDoc() throwsIOException{ DeleteRequestrequest=newDeleteRequest("text_index","1"); DeleteResponsedeleteResponse=restHighLevelClient.delete(request, RequestOptions.DEFAULT); System.out.println(deleteResponse.status()); }
4.5 批量创建文档
批量创建文档用到了BulkRequest ,具体的使用方式和单体很相似,只不过是把多个请求聚合到一个bulk中一起提交。
publicvoidtestBulkRequest() throwsIOException{ BulkRequestrequest=newBulkRequest(); request.timeout("10s"); ArrayList<User>list=newArrayList<>(); list.add(newUser("javayz1","hz")); list.add(newUser("javayz2","hz")); //往BulkRequest对象中add文档list.stream().forEach(x->{ request.add(newIndexRequest("text_index").source(JSON.toJSONString(x),XContentType.JSON)); }); BulkResponsebulk=restHighLevelClient.bulk(request, RequestOptions.DEFAULT); System.out.println(bulk.status()); }
(五)查询API
查询操作用最常用的就是match(模糊查询)和term(精确查询),介绍最常用的查询方式:
(六)总结
从上面的用法中可以看出,ES对API的封装使用还算是比较容易,并且官方文档写的也比较清除。下一篇文章我会用上面的这些API实现一个博客系统的搜索功能,我是鱼仔,我们下期再见!