package com.delete.node;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import com.es.allpeizhi.EsAll;
/**
* 文件名 : ElasticSearchBulkIn.java
* 包 名 :
* 描 述 : TODO(用一句话描述该文件做什么)
* 机能名称:
* 技能ID :
* 作 者 : smkj
* 版 本 : V1.0
*/
public class DeleteSearchCreate {
@SuppressWarnings("unused")
@Test
public static void main(String[] args) throws Exception {
Long nowTime = System.currentTimeMillis();
EsAll es = new EsAll();
// 配置节点
InetSocketTransportAddress node = new InetSocketTransportAddress(InetAddress.getByName(es.host), es.prot);
// 配置settiong
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(node);
System.out.println("ES--ip地址:" + node.getAddress());
// 判断索引是否存在,执行删除数据操作,不存在则停止
IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest().indices(new String[] { es.IndexName })).actionGet();
if (response.isExists() == true) {
final String DB_URL = es.mysqlurl;
final String USER = es.mysqluser;
final String PASS = es.mysqlpass;
Connection conn = null;
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement st = conn.createStatement();
// 创建链接
ResultSet rs1 = st.executeQuery(es.deletesql);
while (rs1.next()) {
String name = rs1.getString(es.deleteName);
System.out.println(name);
SearchResponse searchResponse = client.prepareSearch(es.IndexName).setTypes(es.TypeName).setQuery(QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery(es.deleteName, name)))// matchQuery
.setFrom(0).setSize(10)
// .setSearchType(SearchType.DFS_QUERY_AND_FETCH).setSize(250).setScroll(TimeValue.timeValueMinutes(1))
.setExplain(true)// 按查询匹配度排序
.execute().actionGet();
SearchHits hits = searchResponse.getHits();
// 循环删除
for (int i = 0; i < hits.getHits().length; i++) {
client.prepareDelete(es.IndexName, es.TypeName, hits.getHits()[i].getId()).execute().actionGet();
}
System.out.println("命中总数量:" + searchResponse.getHits().getTotalHits());
}
}
System.err.println("------------------------es删除完成------------------------");
System.out.println("耗时:" + (System.currentTimeMillis() - nowTime) / 1000 + "秒");
client.close();
}
}