1、配置
/**
* 连接池
*/
private static String POOL_SIZE = "5";
TransportClient client;
//es 客户端名称 例如my-application
private static final String ES_CLUSTER_NAME = "es.cluster.name";
//服务地址
private static final String ES_HOST_NAME = "es.host.name";
//端口号 例如 默认是 9300
private static final String ES_PORT = "es.port";
//es搜索历史索引名称
private static final String SEARCH_HISTORY = "myFirstIndex";
2、初始化
public void init() {
// 配置信息
Settings esSetting = Settings.builder()
.put("cluster.name", AppContext.current().getConfig().getProperty(ES_CLUSTER_NAME))
.put("thread_pool.search.size", Integer.parseInt(POOL_SIZE))//增加线程池个数,暂时设为5
.build();
//配置信息Settings自定义
client = new PreBuiltTransportClient(esSetting);
TransportAddress transportAddress = null;
try {
transportAddress = new TransportAddress
(InetAddress.getByName(AppContext.current().getConfig().getProperty(ES_HOST_NAME))
, Integer.valueOf(AppContext.current().getConfig().getProperty(ES_PORT)));
} catch (UnknownHostException e) {
e.printStackTrace();
}
client.addTransportAddresses(transportAddress);
}
3、使用方法 - 增删改查(封装好的)
新增 prepareIndex
/**
*根据id,新增实体数据,如果id存在会默认更新实体数据。参数 jsonObject 是json格式
**/
public IndexResponse getDocHistoryIndex(JSONObject jsonObject, String id) {
IndexResponse response = getClient().prepareIndex(SEARCH_HISTORY, "_doc", id)
.setSource(jsonObject.toString(), XContentType.JSON).get();
return response;
}
更新 prepareUpdate
/**
*根据id,和实体数据更新
* @param jsonObject
* @param id
* @return
*/
public UpdateResponse updateDocHistoryIndex(JSONObject jsonObject, String id) {
UpdateResponse updateResponse = getClient().prepareUpdate(SEARCH_HISTORY, "_doc", id)
.setDoc(jsonObject.toString(), XContentType.JSON).execute().actionGet();
return updateResponse;
}
查询 获取 SearchRequestBuilder对象
/**
*获取 SearchRequestBuilder对象
**/
public SearchRequestBuilder prepareHistorySearch() {
SearchRequestBuilder searchRequestBuilder = getClient().prepareSearch(SEARCH_HISTORY).
setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
return searchRequestBuilder;
}
删除 prepareDelete
/**
*根据id删除
**/
public DeleteResponse prepareHistoryDelete(String documentId) {
DeleteResponse deleteResponse = getClient().prepareDelete(SEARCH_HISTORY, "_doc", documentId).get();
return deleteResponse;
}
根据id查询 prepareGet
public GetResponse getHistoryById(String id) {
GetRequestBuilder getRequestBuilder = getClient().prepareGet(SEARCH_HISTORY, "_doc", id);
GetResponse response = getRequestBuilder.get();
return response;
}
批量更新某个字段 UpdateByQueryRequestBuilder(查询并更新)
/**
*先查询结果集--然后 批量更新某个字段
*/
public UpdateByQueryRequestBuilder updateByQueryRequestBuilder() {
UpdateByQueryRequestBuilder updateByQuery = new UpdateByQueryRequestBuilder(client, UpdateByQueryAction.INSTANCE)
.source(SEARCH_HISTORY);
return updateByQuery;
}
//例子:
/**
* 批量更新某个字段值 业务是:根据条件查出结果然后.script脚本对要更新的字段操作,如把结果集字段isDelete 状态改成1 批量逻辑删除操作。
*/
public Result clearAllHistory() {
Result result = new Result();
try {
UpdateByQueryRequestBuilder updateByQuery = clientUtil.updateByQueryRequestBuilder()
//查询要修改的结果集
.filter(QueryBuilders.termQuery("isDelete", 0))
//修改操作
.script(new Script("ctx._source['isDelete'] = '1'"));
//响应结果集
BulkByScrollResponse response = updateByQuery.get();
long updated = response.getUpdated();
result.setMessage("删除" + updated + "个");
} catch (Exception e) {
e.printStackTrace();
result.setSuccess(false);
result.setMessage(TipMessage.DELETE_FAIL);
}
return result;
}
高亮字段处理 HighlightField
/**
* 高亮结果集 特殊处理
*
* @param esDocForm 查出来的对象
* @SearchHit
* @param highlightField 要高亮的字段
*@content 要处理的字段内容
例如:查出来一篇文档,我只要匹配到的关键字那一小段内容,供前端显示使用(百度文档形式)
*/
private void setSearchResponse(EsDocForm esDocForm, SearchHit next, String highlightField, String content) {
StringBuffer stringBuffer = new StringBuffer();
HighlightField highlightDocNameField = next.getHighlightFields().get(highlightField);
Map highlightFields = next.getHighlightFields();
HighlightField highlightContent = highlightFields.get(content);
//处理文档内容
if (highlightContent != null) {
Text[] contentText = highlightContent.getFragments();
//出来文档内容里关键字提取
if (contentText != null) {
//只取一段
esDocForm.setContent(contentText[0].string() + "...");
}
}
if (highlightDocNameField != null) {
Text[] docNameText = highlightDocNameField.getFragments();
if (docNameText != null) {
for (Text str : docNameText) {
stringBuffer.append(str.string());
}
esDocForm.setDocName(stringBuffer.toString());
}
}
}
统计AggregationBuilder
/**
* 统计查询 根据时间段 统计不同类型的总数
*例:要查询出7天内,不同文件类型文件有多少,如pdf、doc类型有多少个
*/
//部分代码
boolQueryBuilder 是你的查询条件 searchFiled 是你的分类字段
AggregationBuilder oneAgg
= AggregationBuilders.terms(searchFiled).field(searchFiled);
SearchRequestBuilder searchRequestBuilder = clientUtil.prepareDocSearch().setQuery(boolQueryBuilder).addAggregation(oneAgg);
SearchResponse searchResponse = searchRequestBuilder.get();
关闭资源
/**
* 关闭
*/
public void close() {
if (client != null) {
client.close();
}
}
5.6版本之后可使用高级客户端Java High Level REST Client初始化需要Java 1.8,并依赖于Elasticsearch核心项目,客户端版本与客户端开发的Elasticsearch版本相同,它接受与TransportClient相同的请求参数,并返回相同的响应对象