java es index_Java Elasticsearch Index Api

Java Elasticsearch Index API 主要用于插入或者更新文档数据。

创建Index Request

// 创建Index Request,设置索引名为: posts

IndexRequest request = new IndexRequest("posts");

// 设置文档ID

request.id("1");

设置文档内容

支持以JSON字符串形式或者map形式设置文档内容。

Json字符串形式:

String jsonString = "{" +

"\"user\":\"kimchy\"," +

"\"postDate\":\"2013-01-30\"," +

"\"message\":\"trying out Elasticsearch\"" +

"}";

request.source(jsonString, XContentType.JSON);

Map形式:

// 创建map

Map jsonMap = new HashMap<>();

jsonMap.put("user", "kimchy");

jsonMap.put("postDate", new Date());

jsonMap.put("message", "trying out Elasticsearch");

// 设置文档内容

request.source(jsonMap);

其他可选参数

routing

设置路由字段

request.routing("routing");

timeout

设置单个请求超时参数

request.timeout(TimeValue.timeValueSeconds(1));

request.timeout("1s");

Version

设置文档版本

request.version(2);

操作类型

Index api支持两类操作:create 或者 index (默认)

request.opType("create");

执行请求

以同步的方式执行ES请求

IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

以异步的方式执行请求

client.indexAsync(request, RequestOptions.DEFAULT, new ActionListener() {

@Override

public void onResponse(IndexResponse indexResponse) {

// 请求成功回调函数

}

@Override

public void onFailure(Exception e) {

// 请求失败回调函数

}

});

处理请求结果

// 获取索引名

String index = indexResponse.getIndex();

// 获取文档ID

String id = indexResponse.getId();

if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {

// 成功创建文档

} else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {

// 成功更新文档

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值