我是靠谱客的博主 暴躁橘子,最近开发中收集的这篇文章主要介绍elassearch(一)----java api操作elassearch---简单的增删改查根据id 进行简单的 增删改查简单查询新增一条数据删除apibulk批量操作,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
根据id 进行简单的 增删改查
1.添加依赖
// 下面的依赖是错误的写法 当你调用异步查询的时候会报错 ,所以你应该使用第二种方法
// java.lang.NoSuchMethodError: org.elasticsearch.client.Request.addParameters(Ljava/util/Map;)V...
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
</exclusions>
</dependency>
<properties>
<elasticsearch.version>7.4.2</elasticsearch.version>
</properties>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
# 外国网址查看需要vpn
https://discuss.elastic.co/t/issue-with-high-level-rest-client-api/195853/3
2.编写yml
spring:
elasticsearch:
uris: http://********:9200
简单查询
索引+id + 需要查询的字段+不需要查询的字段+
// 查询索引
@Test
void addTest() throws IOException {
//构建索引 index + id
GetRequest getRequest = new GetRequest("book","1");
//设置索引参数 指定自己想要的参数
String[] includes = {"name", "price"};
String[] exclude = {};
FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, exclude);
// 获取结果
getRequest.fetchSourceContext(fetchSourceContext);
GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getId());
System.out.println(getResponse.getIndex());
System.out.println(getResponse.getSourceAsString());
}
异步查询
@Test
void checkTest() throws IOException, InterruptedException {
//构建索引 index + id
GetRequest getRequest = new GetRequest("book","1");
//设置索引参数 指定自己想要的参数
String[] includes = {"name", "price"};
String[] exclude = {};
FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, exclude);
// 获取结果
getRequest.fetchSourceContext(fetchSourceContext);
// 同步查询 GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
new ActionListener<GetResponse>() {
//执行成功的方法
@Override
public void onResponse(GetResponse getResponse) {
System.out.println(getResponse.getId());
System.out.println(getResponse.getIndex());
System.out.println(getResponse.getSourceAsString());
}
// 执行失败的方法
@Override
public void onFailure(Exception e) {
e.printStackTrace();
}
} ;
Thread.sleep(3000);
}
获取结果
新增一条数据
新增的四种方法
@Test
public void testAdd() throws IOException {
// 1构建请求
IndexRequest request=new IndexRequest("test_posts");
request.id("3");
// =======================构建文档============================
// 构建方法1
String jsonString="{n" +
" "user":"tomas J",n" +
" "postDate":"2019-07-18",n" +
" "message":"trying out es3"n" +
"}";
request.source(jsonString, XContentType.JSON);
// 构建方法2
// Map<String,Object> jsonMap=new HashMap<>();
// jsonMap.put("user", "tomas");
// jsonMap.put("postDate", "2019-07-18");
// jsonMap.put("message", "trying out es2");
// request.source(jsonMap);
// 构建方法3
// XContentBuilder builder= XContentFactory.jsonBuilder();
// builder.startObject();
// {
// builder.field("user", "tomas");
// builder.timeField("postDate", new Date());
// builder.field("message", "trying out es2");
// }
// builder.endObject();
// request.source(builder);
// 构建方法4
// request.source("user","tomas",
// "postDate",new Date(),
// "message","trying out es2");
//
// ========================可选参数===================================
//设置超时时间
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
//自己维护版本号
// request.version(2);
// request.versionType(VersionType.EXTERNAL);
// 2执行
//同步
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
//异步
// ActionListener<IndexResponse> listener=new ActionListener<IndexResponse>() {
// @Override
// public void onResponse(IndexResponse indexResponse) {
//
// }
//
// @Override
// public void onFailure(Exception e) {
//
// }
// };
// client.indexAsync(request,RequestOptions.DEFAULT, listener );
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// 3获取结果
String index = indexResponse.getIndex();
String id = indexResponse.getId();
//获取插入的类型
if(indexResponse.getResult()== DocWriteResponse.Result.CREATED){
DocWriteResponse.Result result=indexResponse.getResult();
System.out.println("CREATED:"+result);
}else if(indexResponse.getResult()== DocWriteResponse.Result.UPDATED){
DocWriteResponse.Result result=indexResponse.getResult();
System.out.println("UPDATED:"+result);
}
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if(shardInfo.getTotal()!=shardInfo.getSuccessful()){
System.out.println("处理成功的分片数少于总分片!");
}
if(shardInfo.getFailed()>0){
for (ReplicationResponse.ShardInfo.Failure failure:shardInfo.getFailures()) {
String reason = failure.reason();//处理潜在的失败原因
System.out.println(reason);
}
}
}
但是上面的新增方法都不够优雅 ,new 对象新增的才是最优雅的
手动维护版本号 ,版本号 必须必须 高于当前版本号 不然报错!!!!
者相当于是一个 PUT 请求
# 既可以创建对象 ,也可以更新(更新是全量更新)
@Test
void aaddTest() throws IOException {
IndexRequest request = new IndexRequest("test_posts");
request.id("2");
// 插入的时间格式是 2022-08-17 10:59:43 实际显示的格式是 Aug 17, 2022 @ 10:58:59.038
Person person = new Person("cunk001", DateUtil.date() , "只是一条用户信息");
String perString = JSON.toJSONString(person);
request.source(perString, XContentType.JSON) ;
// 设置参数
request.timeout(TimeValue.timeValueSeconds(3));
IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
//获取插入后的结果
log.debug("index:{}",indexResponse.getIndex());
log.debug("id:{}",indexResponse.getId());
log.debug("res:{}",indexResponse.getResult());
}
异步新增
@Test
void aaddAsTest() throws IOException {
IndexRequest request = new IndexRequest("test_posts");
request.id("3");
// 插入的时间格式是 2022-08-17 10:59:43 实际显示的格式是 Aug 17, 2022 @ 10:58:59.038
Person person = new Person("shuang",DateUtil.date(),"这是爽爽");
String perString = JSON.toJSONString(person);
request.source(perString, XContentType.JSON) ;
// 设置参数
request.timeout(TimeValue.timeValueSeconds(3));
//创建异步回调方法
ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse indexResponse) {
log.info("index:{}",indexResponse.getIndex());
log.info("id:{}",indexResponse.getId());
log.info("res:{}",indexResponse.getResult());
}
@Override
public void onFailure(Exception e) {
}
};
restHighLevelClient.indexAsync(request,RequestOptions.DEFAULT, listener );
// 防止主线程先挂掉
while (true){
}
}
删除api
@Test
void deleteTest() throws IOException {
// 1.创建请求
DeleteRequest indexRequest = new DeleteRequest("test_posts", "3");
//2.执行
DeleteResponse deleteResponse = restHighLevelClient.delete(indexRequest, RequestOptions.DEFAULT);
// 3.获取结果
log.info(deleteResponse.getId());
log.info(":{}",deleteResponse.getResult());
}
bulk批量操作
我觉得并不优雅
@Test
public void testBulk() throws IOException {
// 1创建请求
BulkRequest request = new BulkRequest();
// request.add(new IndexRequest("post").id("1").source(XContentType.JSON, "field", "1"));
// request.add(new IndexRequest("post").id("2").source(XContentType.JSON, "field", "2"));
request.add(new UpdateRequest("post","2").doc(XContentType.JSON, "field", "3"));
request.add(new DeleteRequest("post").id("1"));
// 2执行
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
for (BulkItemResponse itemResponse : bulkResponse) {
DocWriteResponse itemResponseResponse = itemResponse.getResponse();
switch (itemResponse.getOpType()) {
case INDEX:
case CREATE:
IndexResponse indexResponse = (IndexResponse) itemResponseResponse;
indexResponse.getId();
System.out.println(indexResponse.getResult());
break;
case UPDATE:
UpdateResponse updateResponse = (UpdateResponse) itemResponseResponse;
updateResponse.getIndex();
System.out.println(updateResponse.getResult());
break;
case DELETE:
DeleteResponse deleteResponse = (DeleteResponse) itemResponseResponse;
System.out.println(deleteResponse.getResult());
break;
}
}
}
最后
以上就是暴躁橘子为你收集整理的elassearch(一)----java api操作elassearch---简单的增删改查根据id 进行简单的 增删改查简单查询新增一条数据删除apibulk批量操作的全部内容,希望文章能够帮你解决elassearch(一)----java api操作elassearch---简单的增删改查根据id 进行简单的 增删改查简单查询新增一条数据删除apibulk批量操作所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复