使用wES-client
wES-client使用gradle构建为一个jar工程,所以可以支持Maven和Gradle项目使用,也可以下载jar后直接加入classpath使用.
通过Maven使用wES-client
在你的pom.xml文件中的dependencies部分增加wES-client类库依赖:
<dependency>
<groupId>io.github.datasays</groupId>
<artifactId>wES-client</artifactId>
<version>1.0</version>
<scope>compile</scope>
</dependency>
通过Gradle使用wES-client
在你的build.gradle文件中的dependencies部分增加wES-client类库依赖:
compile 'io.github.datasays:wES-client:1.0'
实现org.datasays.wes.core.IConvert
为了保持最小依赖,所以wES-client不包含任何Json实现,使用前需要自行实现一个或者使用wES-toolkit中的org.datasays.wes.toolkit.WGsonConvert
. WGsonConvert
是Gson版本的实现.
创建并初始化org.datasays.wes.client.EsHelper
实例
EsHelper esHelper = new EsHelper("http://127.0.0.1:9200");
//set base auth info for all action
esHelper.baseAuth(user, password);
//set log config
esHelper.setLogFlag(LOG.isDebugEnabled(), LOG.isDebugEnabled(), LOG.isDebugEnabled());
//init
esHelper.init(new OkHttpClient.Builder().build(), new WGsonConvert());
索引一个文档
Index action = esHelper.index(index, type, id);
action.setBody(body);
return esHelper.post(action, Object.class);
搜索一个文档
Search action = esHelper.search(index, type, id);
action.setBody(queryDsl);
return esHelper.post(action, WSearchResult.class, TestDoc.class);
特殊用法
设置全局HTTP缓存(只读场景使用)
OkHttpClient.Builder cBuilder = new OkHttpClient.Builder();
cBuilder.cache(new Cache(new File("./tmp"), 10000));
esHelper.init(cBuilder.build(), new WGsonConvert());
HTTP认证
所有action统一认证
esHelper.baseAuth(user, password);
单独为一个action进行认证
action.baseAuth(user, password);
wES-client核心类
org.datasays.wes.client.EsHelper
使用okhttp3
样式的API访问ElasticSearch. 她支持所有ElasticSearch REST API:org.datasays.wes.actions
和枚举类型:org.datasays.wes.types
. 你可以设置URL的query parameter或者使用GET/POST/PUT/HEAD/DELETE请求带着一个Json的request body. 源代码中包含相关的文档和参数说明,就像这样:
org.datasays.wes.core.IConvert
通用的Request Body和Response Body序列化和反序列化接口,实现方式可以参见:wES-toolkit的org.datasays.wes.toolkit.WGsonConvert
org.datasays.wes.client.EsService
使用retrofit2
样式的API访问ElasticSearch. 她只支持转化Json Response Body到Object, 并且不能传递URL query parameter.所以不能在复杂场景中使用. 我们将尽快修复这个问题.
代码生成器
org.datasays.wes.toolkit.codegen.EsRestSpecGen
这是一个Java代码生成程序生成okhttp3样式的API:org.datasays.wes.client.EsHelper
. 并且生成所有包org.datasays.wes.actions
和org.datasays.wes.types
下的代码. 这些代码很简单,你能按照你的方式修改她们.
你可以像一个常规java程序运行她或者在wES-toolkit
目录下运行shell命令:
gradle EsRestSpecGen
org.datasays.wes.toolkit.codegen.EsRestSpecGen4Retrofit
类似EsRestSpecGen, 她是生成retrofit2样式的API org.datasays.wes.client.EsService
.
gradle EsRestSpecGen4Retrofit
ElasticSearch版本兼容
当前版本支持最新版本的v5.x. 如果需要兼容以前版本,可以从https://github.com/elastic/elasticsearch/tree/master/rest-api-spec获取不同Git分支的特定版本的ES Rest API定义文件, 复制他们覆盖所有目录/wES-toolkit/api/下的Json文件,再重新生成代码.