Elasticsearch(ES)有兩種鏈接方式:transport、rest。transport經過TCP方式訪問ES(只支持java),rest方式經過http API 訪問ES(沒有語言限制)。ES官方建議使用rest方式, transport 將計劃在後面的版本中廢棄。java
官方提供low-level rest client(支持5.0及之後版本) 和high-level rest client(支持版本爲 5.6及之後版本)。須要java版本爲1.8。 High level rest client 接受和Transport Client相同的請求參數,並返回相同的響應對象。本文主要介紹High level rest client 經常使用的 Java api。json
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.1.4</version>
</dependency>
複製代碼
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
複製代碼
client.close();
複製代碼
ES容許咱們存儲一個JSON格式的文檔,能夠經過如下幾種不一樣方式產生JSON格式的文檔。api
String json = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
複製代碼
Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate",new Date());
json.put("message","trying out Elasticsearch");
複製代碼
ObjectMapper mapper = new ObjectMapper();
byte[] json = mapper.writeValueAsBytes(yourbean);
複製代碼
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("user", "ccse")
.field("postDate", new Date())
.field("message", "this is Elasticsearch")
.endObject();
複製代碼
新建文檔,若文檔已經存在,會覆蓋以前的文檔bash
IndexRequest request = new IndexRequest(
"posts",
"doc",
"1");
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
request.source(jsonString, XContentType.JSON);
複製代碼
更新文檔,文檔不存在時,返回document missingapp
UpdateRequest request = new UpdateRequest("posts", "doc", "1")
.doc(builder);
複製代碼
文檔存在則進行更新,不存在則新建less
UpdateRequest request = new UpdateRequest("posts", "doc", "1")
.doc(builder);
UpdateRequest updateRequest = new UpdateRequest(posts", "doc", "1") .doc(builder).upsert(indexRequest); 複製代碼
也能夠根據腳本進行更新elasticsearch
Map<String, Object> parameters = singletonMap("count", 4);
Script inline = new Script(ScriptType.INLINE, "painless", "ctx._source.field += params.count", parameters);
request.script(inline);
複製代碼
批量api能夠一次執行多個請求,包括 index,update,upsert,delete等請求。maven
BulkRequest request = new BulkRequest();
request.add(new IndexRequest("posts", "doc", "1")
.source(XContentType.JSON,"field", "foo"));
request.add(new IndexRequest("posts", "doc", "2")
.source(XContentType.JSON,"field", "bar"));
request.add(new IndexRequest("posts", "doc", "3")
.source(XContentType.JSON,"field", "baz"));
複製代碼