Java添加索引&删除索引
create
添加索引使用IndexResponse
public class EsAddIndex{
public void addIndex(TransportClient client){
Date time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse("2016-7-21 00:00:00");
IndexResponse response = client.prepareIndex("pointdata", "pointdata")
.setSource(XContentFactory.jsonBuilder().startObject()
.field("pointid","W3.UNIT1.10LBG01CP302")
.field("pointvalue","0.8029")
.field("inputtime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time))
.endObject())
.get();
}
}
//返回状态为create表示创建索引成功
System.out.println(response.status());
delete
删除索引使用DeleteIndexResponse
删除索引可以支持批量的动作,prepareDelete内的参数可以传入索引数组。
public class EsAddIndex{
public void deleteIndex(TransportClient client){
DeleteIndexResponse dResponse = (DeleteIndexResponse)client.admin()
.indices().prepareDelete(new String[] {
"pointdata" }).execute().actionGet();
//返回状态为ok表示删除索引成功
System.out.println(response.status());
}
}
delete-to-query
通过DeleteByQueryRequestBuilder 构建条件删除请求;
DeleteByQueryAction.INSTANCE 是 DeleteByQueryAction 类的一个静态属性,返回的是 DeleteByQueryAction 构造实例,返回的是 indices:data/write/delete/byquery 字符串,代表对查询过滤出来的数据进行删除。
/**
* 根据条件删除索引
*
* @param indexName
* 索引
* @param startTime
* 开始时间
* @param endTime
* 结束时间
* @param deviceId
* 设备Id
* @param metric
* 测点
*/
public void dropPhyTableByCondition(final String indexName,
final String startTime, final String endTime,
final String deviceId, final String metric) {
try {
// 组装删除过滤条件
final BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
final QueryBuilder rangeQueryBuilder = QueryBuilders
.rangeQuery(TIMESTAMP).from(startTime).to(endTime);
boolQueryBuilder.filter(rangeQueryBuilder);
final QueryBuilder tagTermQuery = QueryBuilders.termQuery("tag", 1);
boolQueryBuilder.filter(tagTermQuery);
final QueryBuilder deviceIdTermQuery = QueryBuilders.termQuery(
"deviceid", deviceId);
boolQueryBuilder.filter(deviceIdTermQuery);
final QueryBuilder metricTermQuery = QueryBuilders.termQuery(
"metric", metric);
boolQueryBuilder.filter(metricTermQuery);
// 删除请求
BulkIndexByScrollResponse dResponse = new DeleteByQueryRequestBuilder(
client, DeleteByQueryAction.INSTANCE).filter(
boolQueryBuilder).source(indexName).get();
long deleted = dResponse.getDeleted();
if (deleted >= 0) {
LOGGER.info("delete index " + indexName + " successfully!");
} else {
LOGGER.error("dropPhyTable(): Fail to delete index " + indexName);
// throw new RuntimeException(msg);
}
} catch (Exception e) {
LOGGER.error("dropPhyTable(): Fail to delete index " + indexName);
throw new RuntimeException("删除索引数据失败: " + indexName, e);
}
}
版权声明:本文不是「本站」原创文章,版权归原作者所有 | 原文地址: