QQ个性网:专注于分享免费的QQ个性内容

关于我们| 网站公告| 广告服务| 联系我们| 网站地图

搜索
编程 JavaScript Java C++ Python SQL C Io ML COBOL Racket APL OCaml ABC Sed Bash Visual Basic Modula-2 Logo Delphi IDL Groovy Julia REXX Chapel X10 Forth Eiffel C# Go Rust PHP Swift Kotlin R Dart Perl Ruby TypeScript MATLAB Shell Lua Scala Objective-C F# Haskell Elixir Lisp Prolog Ada Fortran Erlang Scheme Smalltalk ABAP D ActionScript Tcl AWK IDL J PostScript IDL PL/SQL PowerShell

「微服务」java 操作elasticsearch详细总结

日期:2025/04/05 09:07来源:未知 人气:51

导读:一、前言上一篇我们通过kibana的可视化界面,对es的索引以及文档的常用操作做了毕竟详细的总结,本篇将介绍如何使用java完成对es的操作,这也是实际开发中将要涉及到的。二、java操作es的常用模式目前,开发中使用java操作es,不管是框架集成,还是纯粹的使用es的api,主要通过下面两种方式:rest-api,主流的像RestHighLevelClient;与sprin......

一、前言

上一篇我们通过kibana的可视化界面,对es的索引以及文档的常用操作做了毕竟详细的总结,本篇将介绍如何使用java完成对es的操作,这也是实际开发中将要涉及到的。

二、java操作es的常用模式

目前,开发中使用java操作es,不管是框架集成,还是纯粹的使用es的api,主要通过下面两种方式:

rest-api,主流的像RestHighLevelClient;

与springboot集成时的jpa操作,主要是ElasticsearchRepository相关的api;

上面两种模式的api在开发中都可以方便的使用,相比之下,RestHighLevelClient相关的api灵活性更高,而ElasticsearchRepository底层做了较多的封装,学习和使用的成本更低,上手更快。

接下来将对上面的两种操作模式做一个详细的总结,本篇所述的es基于7.6.2版本,配合的kibana也为7.6.2版本。

三、rest-api操作

1、前置准备

导入依赖

导入核心依赖,主要是es的rest依赖,其他的可以根据自己的需要导入;

org.apache.logging.log4j log4j-api 2.11.2 org.apache.logging.log4j log4j-core 2.11.2 org.apache.logging.log4j log4j-core 2.8.2 org.apache.logging.log4j log4j-jcl 2.11.2 commons-logging commons-logging 1.2 org.elasticsearch elasticsearch 7.6.2 org.elasticsearch.client elasticsearch-rest-high-level-client 7.6.2 com.fasterxml.jackson.core jackson-databind 2.9.9 junit junit 4.12

es连接测试

为了确保后续的所有实验能够正常进行,建议先通过下面的程序测试下是否能够连接es服务;

importorg.apache.http.HttpHost;

importorg.elasticsearch.client.RestClient;

importorg.elasticsearch.client.RestHighLevelClient;

importjava.io.IOException;

publicclassEsClientTest{

publicstaticvoidmain(String[]args)throwsIOException{

RestHighLevelClientesClient=newRestHighLevelClient(

RestClient.builder(newHttpHost("IP",9200,"http"))

);

System.out.println("success");

esClient.close();

}

}

运行上面的代码,出现下面的效果说明连接成功

2、索引相关操作api的使用

为了减少连接相关的编码,我们将es的client提出到全局的静态变量中,其他方法中就可以直接引用了

publicstaticRestHighLevelClientesClient;

static{

esClient=newRestHighLevelClient(

RestClient.builder(newHttpHost("IP",9200,"http"))

);

}

2.1创建索引

/**

*创建索引

*@throwsIOException

*/

publicstaticvoidcreateIndex()throwsIOException{

CreateIndexRequestcreateIndexRequest=newCreateIndexRequest("user");

CreateIndexResponseindexResponse=esClient.indices().create(createIndexRequest,RequestOptions.DEFAULT);

booleanacknowledged=indexResponse.isAcknowledged();

System.out.println("索引创建状态:"+acknowledged);

}

main方法中调用方法即可

publicstaticvoidmain(String[]args)throwsIOException{

System.out.println("connectsuccess");

createIndex();

esClient.close();

}

运行main创建索引

通过kibana查询确认索引是否创建成功

2.2获取索引

/**

*索引信息查询

*@throwsIOException

*/

publicstaticvoidgetIndex()throwsIOException{

GetIndexRequestgetIndexRequest=newGetIndexRequest("user");

GetIndexResponsegetIndexResponse=esClient.indices().get(getIndexRequest,RequestOptions.DEFAULT);

System.out.println(getIndexResponse.getAliases());

System.out.println(getIndexResponse.getMappings());

System.out.println(getIndexResponse.getSettings());

}

2.3删除索引

/**

*删除索引

*@throwsIOException

*/

publicstaticvoiddeleteIndex()throwsIOException{

DeleteIndexRequestgetIndexRequest=newDeleteIndexRequest("user");

AcknowledgedResponsedelete=esClient.indices().delete(getIndexRequest,RequestOptions.DEFAULT);

System.out.println("索引删除状态:"+delete.isAcknowledged());

}

3、文档常用操作api的使用

在实际开发过程中,对于文档的操作更为的频繁,接下来演示与es文档相关的操作api。

前置准备

publicstaticObjectMapperobjectMapper=newObjectMapper();

publicstaticRestHighLevelClientesClient;

static{

esClient=newRestHighLevelClient(

RestClient.builder(newHttpHost("IP",9200,"http"))

);

}

用于测试使用的对象

publicclassUser{

privateStringname;

privateStringsex;

privateIntegerage;

privateIntegersalary;

publicUser(){

}

publicUser(Stringname,Stringsex,Integerage,Integersalary){

this.name=name;

this.sex=sex;

this.age=age;

this.salary=salary;

}

publicIntegergetSalary(){

returnsalary;

}

publicvoidsetSalary(Integersalary){

this.salary=salary;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

}

publicStringgetSex(){

returnsex;

}

publicvoidsetSex(Stringsex){

this.sex=sex;

}

publicIntegergetAge(){

returnage;

}

publicvoidsetAge(Integerage){

this.age=age;

}

}

3.1索引添加文档

注意:实际开发中,user对象应该作为参数传入【可以基于此做进一步的封装】

/**

*添加数据

*@throwsException

*/

publicstaticvoidadd()throwsException{

IndexRequestindexRequest=newIndexRequest();

indexRequest.index("user").id("1008");

Useruser=newUser();

user.setName("孙二娘");

user.setAge(23);

user.setSex("女");

user.setSalary(7000);

StringuserData=objectMapper.writeValueAsString(user);

indexRequest.source(userData,XContentType.JSON);

//插入数据

IndexResponseresponse=esClient.index(indexRequest,RequestOptions.DEFAULT);

System.out.println(response.status());

System.out.println(response.getResult());

}

在main方法调用执行下该方法

publicstaticvoidmain(String[]args)throwsException{

add();

esClient.close();

}

可以通过kibana查询检查下数据是否添加成功

3.2修改文档

/**

*修改数据

*@throwsException

*/

publicstaticvoidupdate()throwsException{

UpdateRequestrequest=newUpdateRequest();

request.index("user").id("1008");

request.doc(XContentType.JSON,"name","母夜叉");

//插入数据

UpdateResponseresponse=esClient.update(request,RequestOptions.DEFAULT);

System.out.println(response.getResult());

}

3.3删除文档

/**

*删除

*@throwsException

*/

publicstaticvoiddelete()throwsException{

DeleteRequestrequest=newDeleteRequest();

request.index("user").id("1008");

//插入数据

DeleteResponsedelete=esClient.delete(request,RequestOptions.DEFAULT);

System.out.println(delete.getResult());

}

3.4批量添加文档

有些情况下,单条插入效率太低,可以使用es的批量插入功能一次性添加多条数据

/**

*批量添加

*@throwsException

*/

publicstaticvoidbatchInsert()throwsException{

BulkRequestbulkRequest=newBulkRequest();

Useruser1=newUser("关羽","男",33,5500);

StringuserData1=objectMapper.writeValueAsString(user1);

IndexRequestindexRequest1=newIndexRequest().index("user").id("1002").source(userData1,XContentType.JSON);

bulkRequest.add(indexRequest1);

Useruser2=newUser("黄忠","男",50,8000);

StringuserData2=objectMapper.writeValueAsString(user2);

IndexRequestindexRequest2=newIndexRequest().index("user").id("1003").source(userData2,XContentType.JSON);

bulkRequest.add(indexRequest2);

Useruser3=newUser("黄忠2","男",49,10000);

StringuserData3=objectMapper.writeValueAsString(user3);

IndexRequestindexRequest3=newIndexRequest().index("user").id("1004").source(userData3,XContentType.JSON);

bulkRequest.add(indexRequest3);

Useruser4=newUser("赵云","男",33,12000);

StringuserData4=objectMapper.writeValueAsString(user4);

IndexRequestindexRequest4=newIndexRequest().index("user").id("1005").source(userData4,XContentType.JSON);

bulkRequest.add(indexRequest4);

Useruser5=newUser("马超","男",38,20000);

StringuserData5=objectMapper.writeValueAsString(user5);

IndexRequestindexRequest5=newIndexRequest().index("user").id("1006").source(userData5,XContentType.JSON);

bulkRequest.add(indexRequest5);

Useruser6=newUser("关羽","男",41,27000);

StringuserData6=objectMapper.writeValueAsString(user6);

IndexRequestindexRequest6=newIndexRequest().index("user").id("1007").source(userData6,XContentType.JSON);

bulkRequest.add(indexRequest6);

BulkResponsebulkResponse=esClient.bulk(bulkRequest,RequestOptions.DEFAULT);

System.out.println(bulkResponse.status());

System.out.println(bulkResponse.getItems());

}

3.5批量删除

可以通过批量操作一次性删除多条数据

/**

*批量删除

*@throwsException

*/

publicstaticvoidbatchDelete()throwsException{

BulkRequestbulkRequest=newBulkRequest();

DeleteRequestindexRequest1=newDeleteRequest().index("user").id("1002");

DeleteRequestindexRequest2=newDeleteRequest().index("user").id("1003");

DeleteRequestindexRequest3=newDeleteRequest().index("user").id("1004");

DeleteRequestindexRequest4=newDeleteRequest().index("user").id("1005");

DeleteRequestindexRequest5=newDeleteRequest().index("user").id("1006");

DeleteRequestindexRequest6=newDeleteRequest().index("user").id("1007");

bulkRequest.add(indexRequest1);

bulkRequest.add(indexRequest2);

bulkRequest.add(indexRequest3);

bulkRequest.add(indexRequest4);

bulkRequest.add(indexRequest5);

bulkRequest.add(indexRequest6);

BulkResponsebulkResponse=esClient.bulk(bulkRequest,RequestOptions.DEFAULT);

System.out.println(bulkResponse.status());

System.out.println(bulkResponse.getItems());

}

4、文档搜索相关api的使用

我们知道es最强大的功能就是文档检索了,接下来演示下与es文档查询相关的常用API的操作;

4.1查询某个索引下的所有数据

/**

*查询某个索引下的所有数据

*@throwsException

*/

publicstaticvoidsearchIndexAll()throwsException{

SearchRequestrequest=newSearchRequest();

request.indices("user");

//索引中的全部数据查询

SearchSourceBuilderquery=newSearchSourceBuilder().query(QueryBuilders.matchAllQuery());

request.source(query);

SearchResponseresponse=esClient.search(request,RequestOptions.DEFAULT);

SearchHitshits=response.getHits();

for(SearchHitsearchHit:hits){

System.out.println(searchHit.getSourceAsString());

}

}

————————————————

版权声明:本文为CSDN博主「逆风飞翔的小叔」的原创文章,遵循CC4.0BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/congge_study/article/details/128194887

关于我们|网站公告|广告服务|联系我们| 网站地图

Copyright © 2002-2023 某某QQ个性网 版权所有 | 备案号:粤ICP备xxxxxxxx号

声明: 本站非腾讯QQ官方网站 所有软件和文章来自互联网 如有异议 请与本站联系 本站为非赢利性网站 不接受任何赞助和广告