使用put方式,并自己提供id
类似于下面的格式
PUT /{index}/{type}/{id}
{
“field”: “value”,
…
}
请求
PUT /website/blog/123
{
“title”: “My first blog entry”,
“text”: “Just trying this out…”,
“date”: “2014/01/01”
}
响应
{
“_index”: “website”,
“_type”: “blog”,
“_id”: “123”,
“_version”: 1,
“created”: true
}
自动生成的 ID 是 URL-safe、 基于 Base64 编码且长度为20个字符的 GUID 字符串。 这些 GUID 字符串由可修改的 FlakeID 模式生成,这种模式允许多个节点并行生成唯一 ID ,且互相之间的冲突概率几乎为零。
1.2.2.更改操作
Java示例代码:
private static void update() throws IOException {
String type = “_doc”;
String index = “test1”;
// 唯一编号
String id = “1”;
UpdateRequest upateRequest = new UpdateRequest();
upateRequest.id(id);
upateRequest.index(index);
upateRequest.type(type);
// 依旧可以使用Map这种集合作为更新条件
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put(“uid”, 12345);
jsonMap.put(“phone”, 123456789019L);
jsonMap.put(“msgcode”, 2);
jsonMap.put(“sendtime”, “2019-03-14 01:57:04”);
jsonMap.put(“message”, “xuwujing study Elasticsearch”);
upateRequest.doc(jsonMap);
// upsert 方法表示如果数据不存在,那么就新增一条
upateRequest.docAsUpsert(true);
client.update(upateRequest, RequestOptions.DEFAULT);
System.out.println(“更新成功!”);
}
控制台输入
PUT /website/blog/123
{
“title”: “My first blog entry”,
“text”: “Just trying this out…”,
“date”: “2014/01/01”
}
在响应体中,我们能看到 Elasticsearch 已经增加了 _version 字段值,created 标志设置成 false ,是因为相同的索引、类型和 ID 的文档已经存在。
{
“_index”: “website”,
“_type”: “blog”,
“_id”: “123”,
“_version”: 2,
“created”: false
}
1.2.3.删除操作
Java示例代码:
示例一(正常根据ID删除):
private static void delete() throws IOException {
String type = “_doc”;
String index = “test1”;
// 唯一编号
String id = “1”;
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.id(id);
deleteRequest.index(index);
deleteRequest.type(type);
// 设置超时时间
deleteRequest.timeout(TimeValue.timeValueMinutes(2));
// 设置刷新策略"wait_for"
// 保持此请求打开,直到刷新使此请求的内容可以搜索为止。此刷新策略与高索引和搜索吞吐量兼容,但它会导致请求等待响应,直到发生刷新
deleteRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
// 同步删除
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
}
示例二(条件删除):
private static void deleteByQuery() throws IOException {
String type = “_doc”;
String index = “test1”;
DeleteByQueryRequest request = new DeleteByQueryRequest(index,type);
// 设置查询条件
request.setQuery(QueryBuilders.termsQuery(“uid”,1234));
// 同步执行
BulkByScrollResponse bulkResponse = client.deleteByQuery(request, RequestOptions.DEFAULT);
}
DELETE /website/blog/123
如果找到该文档,Elasticsearch 将要返回一个 200 ok 的 HTTP 响应码,和一个类似以下结构的响应体。注意,字段 _version 值已经增加:
{
“found” : true,
“_index” : “website”,
“_type” : “blog”,
“_id” : “123”,
“_version” : 3
}
如果文档没有 找到,我们将得到 404 Not Found 的响应码和类似这样的响应体:
{
“found” : false,
“_index” : “website”,
“_type” : “blog”,
“_id” : “123”,
“_version” : 4
}
1.2.4.查询操作
查询API
等值(term查询:QueryBuilders.termQuery(name,value);
多值(terms)查询:QueryBuilders.termsQuery(name,value,value2,value3…);
范围(range)查询:QueryBuilders.rangeQuery(name).gte(value).lte(value);
存在(exists)查询:QueryBuilders.ex