elasticsearch 索引的基本操作
简介
本次操作以TransportClient的Java API操作
private TransportClient client = TransportClientFactory.getInstance().getTransportClient();
/**
*判断索引是否存在
* @param index
* @return
*/
public boolean isIndexExist(String index) {
return client.admin().indices().prepareExists(index).execute().actionGet().isExists();
}
/**
* 新增索引
* @param index
* @return
*/
public boolean addIndex(String index) {
return isIndexExist(index)
? false
: client.admin().indices().prepareCreate(index).execute().actionGet().isAcknowledged();
}
/**
*
* 删除索引
* @param index
* @return
*/
public boolean deleteIndex(String index) {
return isIndexExist(index)
? client.admin().indices().prepareDelete(index).execute().actionGet().isAcknowledged()
: false;
}
/**
* 判断inde下指定type是否存在
* @param index
* @param type
* @return
*/
public boolean isTypeExist(String index, String type) {
return isIndexExist(index)
? client.admin().indices().prepareTypesExists(index).setTypes(type).execute().actionGet().isExists()
: false;
}
/**
* 获取索引的所有数据,返回前size条
* @param index 索引
* @param size 返回多少条明细
* @return SearchHits
*/
public SearchHits matchAllQuery(String index, int size) {
QueryBuilder query = QueryBuilders.matchAllQuery();
SearchResponse response = client.prepareSearch(index).setQuery(query).setSize(size).execute().actionGet();
// for (SearchHit searchHit : response.getHits()) {
// String jsonStr = searchHit.getSourceAsString();
// System.out.println(jsonStr);
// }
return response.getHits();
}
欢迎关注我公众号:
