elasticsearch的官方文档的链接在此
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html
如果不想看这文章, 请出门左转直接去看官方的api, 写的非常详细, 也写的很多
简单介绍下两种api
Java REST Client 有两种风格:Java Low Level REST Client :用于Elasticsearch的官方低级客户端。它允许通过http与Elasticsearch集群通信。将请求编排和响应反编排留给用户自己处理。它兼容所有的Elasticsearch版本。(PS:学过WebService的话,对编排与反编排这个概念应该不陌生。可以理解为对请求参数的封装,以及对响应结果的解析)Java High Level REST Client :用于Elasticsearch的官方高级客户端。它是基于低级客户端的,它提供很多API,并负责请求的编排与响应的反编排。(PS:就好比是,一个是传自己拼接好的字符串,并且自己解析返回的结果;而另一个是传对象,返回的结果也已经封装好了,直接是对象,更加规范了参数的名称以及格式,更加面对对象一点)(PS:所谓低级与高级,我觉得一个很形象的比喻是,面向过程编程与面向对象编程)使用需与ES版本保持一致在 Elasticsearch 7.0 中不建议使用TransportClient,并且在8.0中会完全删除TransportClient。因此,官方更建议我们用Java High Level REST Client,它执行HTTP请求,而不是序列号的Java请求。既然如此,这里就直接用高级了。
所以我就直接使用了es的最新版本7.3.1 , 这个es的启动需要jdk11, java的代码环境需要jdk8 以上.
当然了, 你可以和我一样装了jdk8 和11 ,然后在es的配置文件中加上这么一句
修改es的elasticsearch.bat 文件, 再最前面加上一个
set JAVA_HOME=C:\soft\jdk11 就不会使用window配置的默认的jdk 了,使用11.
使用的maven坐标
<dependencies><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.3.1</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>2.5</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.5</version></dependency></dependencies>
新建log4j2.xml, 一定要有这个, 不然启动报错.
<?xml version="1.0" encoding="UTF-8"?><Configuration status="WARN"><Appenders><Console name="Console" target="SYSTEM_OUT"><PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /></Console></Appenders><Loggers><Root level="error"><AppenderRef ref="Console" /></Root></Loggers></Configuration>
其实High Level REST Client 都有两种编程风格, 一种是同步的, 一种是异步的操作, 异步的操作添加一个监听器, 监听返回的结果即可.
在案例中了, 全部使用同步的进行操作.
package com.onyx;import org.apache.http.HttpHost;import org.elasticsearch.action.delete.DeleteRequest;import org.elasticsearch.action.delete.DeleteResponse;import org.elasticsearch.action.get.GetRequest;import org.elasticsearch.action.get.GetResponse;import org.elasticsearch.action.index.IndexRequest;import org.elasticsearch.action.index.IndexResponse;import org.elasticsearch.action.update.UpdateRequest;import org.elasticsearch.action.update.UpdateResponse;import org.elasticsearch.client.RequestOptions;import org.elasticsearch.client.RestClient;import org.elasticsearch.client.RestHighLevelClient;import mon.xcontent.XContentBuilder;import mon.xcontent.XContentFactory;import org.elasticsearch.search.fetch.subphase.FetchSourceContext;import java.io.IOException;import java.util.Date;import java.util.HashMap;import java.util.Map;/*** @author zk* @Description: es的api crud的练习* @date -09-12 8:50*/public class UserCRUD {public static void main(String[] args) throws IOException, InterruptedException {RestHighLevelClient client = new RestHighLevelClient(//因为使用的是http, 所以这里是9200 ,不是对应的9300,这是个大坑!RestClient.builder(new HttpHost("localhost", 9200, "http")));//createDoc(client);//TimeUnit.SECONDS.sleep(2);//getDoc(client);//existsDoc(client);//deleteDoc(client);//updateDoc(client);client.close();}/*** 更新doc* @param client* @throws IOException*/private static void updateDoc(RestHighLevelClient client) throws IOException {//不存在的更新会报错Map<String, Object> jsonMap = new HashMap<String, Object>();jsonMap.put("postDate", new Date());jsonMap.put("message", "daily update");UpdateRequest updateRequest = new UpdateRequest("posts", "3").doc(jsonMap);UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);System.out.println(updateResponse.status());}/*** 删除文档* @param client* @throws IOException*/private static void deleteDoc(RestHighLevelClient client) throws IOException {DeleteRequest request = new DeleteRequest("posts", "1");DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);System.out.println(delete.status() + "~" + delete.getResult());}/*** 文档是否存在* @param client* @throws IOException*/private static void existsDoc(RestHighLevelClient client) throws IOException {for (int i = 1; i <5; i++) {GetRequest request = new GetRequest("posts", String.valueOf(i));request.fetchSourceContext(new FetchSourceContext(false));request.storedFields("_none_");boolean exists = client.exists(request, RequestOptions.DEFAULT);System.out.println(exists);}/*GetRequest request2 = new GetRequest("posts", "5");request.fetchSourceContext(new FetchSourceContext(false));request.storedFields("_none_");boolean exists2 = client.exists(request2, RequestOptions.DEFAULT);System.out.println(exists2);*/}/*** 获取一个文档* @param client* @throws IOException*/private static void getDoc(RestHighLevelClient client) throws IOException {//没有posts 会报错的GetRequest posts = new GetRequest("posts", "1");GetResponse response = client.get(posts, RequestOptions.DEFAULT);System.out.println(response.getId());System.out.println(response.getIndex());System.out.println(response.getSourceAsString());System.out.println(response.getSourceAsMap());}/*** 创建一个文档* @param client* @throws IOException*/private static void createDoc(RestHighLevelClient client) throws IOException {IndexRequest request = new IndexRequest("posts");request.id("1");String jsonString = "{" +"\"user\":\"zk\"," +"\"postDate\":\"-01-30\"," +"\"message\":\"trying out java\"" +"}";String jsonString2 = "{" +"\"user\":\"zk2\"," +"\"postDate\":\"-10-01\"," +"\"message\":\"trying out javascript\"" +"}";//为什么这里要有个jsonString2 ,因为这个request.source(jsonString, jsonString2);// 的参数数量必须是偶数, 不然会报错的.request.source(jsonString, jsonString2);IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);System.out.println(indexResponse.getResult());Map<String, Object> jsonMap = new HashMap<String, Object>();jsonMap.put("user", "ting");jsonMap.put("postDate", new Date());jsonMap.put("message", "trying out hadoop");IndexRequest post = new IndexRequest("post").id("2").source(jsonMap);client.index(post, RequestOptions.DEFAULT);XContentBuilder builder = XContentFactory.jsonBuilder();builder.startObject();{builder.field("user", "wang");builder.timeField("postDate", new Date());builder.field("message", "trying out scala");}builder.endObject();IndexRequest posts = new IndexRequest("posts").id("3").source(builder);client.index(posts, RequestOptions.DEFAULT);IndexRequest source = new IndexRequest("posts").id("4").source("user", "peng","postDate", new Date(),"message", "trying out golang");client.index(source, RequestOptions.DEFAULT);}}
Java Framework,欢迎各位前来交流java相关
QQ群:965125360