之前的更新文档操作
PUT /website/blog/123 { "title": "My first blog entry2", "text": "I am starting to get the hang of this...", "date": "2014/01/02" } POST /website/pageviews/1/_update { "script" : "ctx._source.view+=1", "upsert": { "views": 2 } }
1:方式1
/** * UpdateRequest * //TODO // 对没有的字段添加, 对已有的字段替换 * */ @Test public void UpdateRequestDocument(){ try { UpdateRequest updateRequest = new UpdateRequest(); updateRequest.index("twitter4"); updateRequest.type("tweet"); updateRequest.id("1"); updateRequest.doc(jsonBuilder() .startObject() .field("gender", "male") .field("title", "ElasticSearch是一个基于Lucene的搜索服务器") .field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。" + "Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布," + "是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索," + "稳定,可靠,快速,安装使用方便。") .endObject()); UpdateResponse response = client.update(updateRequest).get(); // 索引名称 String _index = response.getIndex(); // 类型 String _type = response.getType(); // 文档ID String _id = response.getId(); // 版本 long _version = response.getVersion(); // 返回的操作状态 RestStatus status = response.status(); System.out.println("索引名称:"+_index+" "+"类型 :" + _type + " 文档ID:"+_id+" 版本 :"+_version+" 返回的操作状态:"+status); } catch (Exception e) { e.printStackTrace(); } }
/** * XContentFactory */ @Test public void XContentFactoryDocument() throws Exception { // 使用updateRequest对象进行更新 final UpdateRequest updateRequest = new UpdateRequest(); updateRequest.index("twitter"); updateRequest.type("tweet"); updateRequest.id("1"); UpdateResponse response = transportClient .update(updateRequest.doc(XContentFactory.jsonBuilder() .startObject() .field("title", "什么是Elasticsearch,ElasticSearch是一个基于Lucene的搜索服务器") .endObject())) .get(); // 打印 String index = response.getIndex(); String type = response.getType(); String id = response.getId(); long version = response.getVersion(); System.out.println(index + " : " + type + ": " + id + ": " + version); }
3:方式3
/** * upsert * */ @Test public void upsertDocument() throws Exception { // 设置查询条件, 查找不到则添加 IndexRequest indexRequest = new IndexRequest("twitter4", "tweet", "3") .source(XContentFactory.jsonBuilder() .startObject() .field("title", "666") .field("content", "传智大数据") .endObject()); // 设置更新, 查找到更新下面的设置 UpdateRequest upsert = new UpdateRequest("twitter4", "tweet", "3") .doc(XContentFactory.jsonBuilder() .startObject() .field("user", "tom") .endObject()) .upsert(indexRequest); client.update(upsert).get(); }