public class EsUtil {
private static TransportClient client;
private static ResourceBundle resource = ResourceBundle.getBundle("es");
/** 索引库名称 */
private static String index = resource.getString("es.db");
/** 索引表名称 */
private static String type = resource.getString("es.table");
/** 集群分片数 */
private static String shards_str = resource.getString("es.shards");
private static Integer shards = Integer.parseInt(shards_str);
private static SearchRequestBuilder searchRequestBuilder;
// 获取集群名称
private static String clustername = resource.getString("es.cluster.name");
// 获取集群ip/域名
private static String hostname = resource.getString("es.hostname");
// 获取第一个节点端口号
private static String port1 = resource.getString("es.port.1");
// 获取第一个节点端口号
private static String port2 = resource.getString("es.port.2");
/**
* 创建索引 写入elasticsearch
*
* @param jsonlist
* 要创建索引的jsonlist数据
*/
public static void createIndex(List<JSONObject> jsonlist) {
Settings settings = ImmutableSettings.settingsBuilder()
// client.transport.sniff=true
// 客户端嗅探整个集群的状态,把集群中其它机器的ip地址自动添加到客户端中,并且自动发现新加入集群的机器
.put("client.transport.sniff", true).put("client", true)// 仅作为客户端连接
.put("data", false).put("cluster.name", clustername)// 集群名称
.build();
client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port1)))// TCP
// 连接地址
.addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port2)));
searchRequestBuilder = client.prepareSearch(index);
try {
// 创建索引
for (int i = 0; i < jsonlist.size(); i++) {
IndexResponse indexResponse = client.prepareIndex(index, type, jsonlist.get(i).getString("id")).setSource(jsonlist.get(i).toString())
.execute().actionGet();
if (indexResponse.isCreated()) {
System.out.println("创建成功!");
} else {
System.out.println("创建失败!");
}
}
client.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据索引id删除
*
* @param uids
* 索引id
*/
public static void deleteIndex(List<String> uids) {
Settings settings = ImmutableSettings.settingsBuilder()
// client.transport.sniff=true
// 客户端嗅探整个集群的状态,把集群中其它机器的ip地址自动添加到客户端中,并且自动发现新加入集群的机器
.put("client.transport.sniff", true).put("client", true)// 仅作为客户端连接
.put("data", false).put("cluster.name", clustername)// 集群名称
.build();
client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port1)))// TCP
// 连接地址
.addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port2)));
searchRequestBuilder = client.prepareSearch(index);
for (int i = 0; i < uids.size(); i++) {
DeleteResponse dResponse = client.prepareDelete(index, type, uids.get(i)).execute().actionGet();
if (dResponse.isContextEmpty()) {
System.out.println(uids.get(i) + "删除成功。");
} else {
System.out.println(uids.get(i) + "删除失败");
}
}
}
/**
* 根据索引名称删除
*
* @param indexName
* 索引库名称
*/
public static void deleteIndexLib(String indexName) {
Settings settings = ImmutableSettings.settingsBuilder()
// client.transport.sniff=true
// 客户端嗅探整个集群的状态,把集群中其它机器的ip地址自动添加到客户端中,并且自动发现新加入集群的机器
.put("client.transport.sniff", true).put("client", true)// 仅作为客户端连接
.put("data", false).put("cluster.name", clustername)// 集群名称
.build();
client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port1)))// TCP
// 连接地址
.addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port2)));
searchRequestBuilder = client.prepareSearch(index);
DeleteIndexResponse dResponse = client.admin().indices().prepareDelete(indexName).execute().actionGet();
if (dResponse.isContextEmpty()) {
System.out.println(indexName + "删除成功。");
} else {
System.out.println(indexName + "删除失败");
}
}
/**
* @param uid
* 要更新的索引id
* @param json
* 要更新的json数据
*/
public static void updateIndex(String uid, JSONObject json) {
Settings settings = ImmutableSettings.settingsBuilder()
// client.transport.sniff=true
// 客户端嗅探整个集群的状态,把集群中其它机器的ip地址自动添加到客户端中,并且自动发现新加入集群的机器
.put("client.transport.sniff", true).put("client", true)// 仅作为客户端连接
.put("data", false).put("cluster.name", clustername)// 集群名称
.build();
client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port1)))// TCP
// 连接地址
.addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port2)));
searchRequestBuilder = client.prepareSearch(index);
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(index);
updateRequest.type(type);
updateRequest.id(uid);
updateRequest.doc(json);
try {
UpdateResponse updateResponse = client.update(updateRequest).get();
if (!updateResponse.isCreated()) {
System.out.println(uid + "更新成功");
} else {
System.out.println(uid + "更新失败");
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 多字段查询
*
* @param pageSize
* 页面大小
* @param keyword
* 查询关键字
* @param columns
* 不确定多个索引字段
* @return map集合 map.put("dispage", disPage); map.put("jsonlist",
* resultlist);
*/
public static Map<String, Object> query(Integer pageSize, Integer currentNo, SearchParVo vo, String... columns) {
Settings settings = ImmutableSettings.settingsBuilder()
// client.transport.sniff=true
// 客户端嗅探整个集群的状态,把集群中其它机器的ip地址自动添加到客户端中,并且自动发现新加入集群的机器
.put("client.transport.sniff", true).put("client", true)// 仅作为客户端连接
.put("data", false).put("cluster.name", clustername)// 集群名称
.build();
client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port1)))// TCP
// 连接地址
.addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port2)));
searchRequestBuilder = client.prepareSearch(index);
HashMap<String, Object> map = new HashMap<String, Object>();
// 搜索结果集
List<JSONObject> resultlist = new ArrayList<JSONObject>();
QueryBuilder qb = null;
QueryBuilder qb_dept = null;
QueryBuilder qb_item = null;
QueryBuilder qb_subject = null;
QueryBuilder qb_regtype = null;
QueryBuilder qb_disway = null;
BoolQueryBuilder querybuilder = QueryBuilders.boolQuery();
if (StringUtils.isNotBlank(vo.getTitle())) {
qb = QueryBuilders.multiMatchQuery(vo.getTitle(), columns);
querybuilder.must(qb);
if (StringUtils.isNotBlank(vo.getDid())) {
qb_dept = QueryBuilders.matchPhraseQuery("d_id", vo.getDid());
querybuilder.must(qb_dept);
}
if (StringUtils.isNotBlank(vo.getIid())) {
qb_item = QueryBuilders.matchPhraseQuery("i_id", vo.getIid());
querybuilder.must(qb_item);
}
if (StringUtils.isNotBlank(vo.getSid())) {
qb_subject = QueryBuilders.matchPhraseQuery("s_id", vo.getSid());
querybuilder.must(qb_subject);
}
if (StringUtils.isNotBlank(vo.getRegtype())) {
qb_regtype = QueryBuilders.matchPhraseQuery("registration_type", vo.getRegtype());
querybuilder.must(qb_regtype);
}
if (StringUtils.isNotBlank(vo.getDisway())) {
qb_disway = QueryBuilders.matchPhraseQuery("discount_way", vo.getDisway());
querybuilder.must(qb_disway);
}
} else {
qb = QueryBuilders.matchAllQuery();
querybuilder.must(qb);
}
searchRequestBuilder.setQuery(querybuilder);
SearchResponse response = searchRequestBuilder.execute().actionGet();
SearchHits hits = response.getHits();
// 记录总数
long total = hits.totalHits();
// 计算总页数
int totalPages = totalPage(1, pageSize, (int) total);
// 每次开始的位置
int start = (currentNo - 1) * pageSize;
// 添加高亮字段
searchRequestBuilder.addHighlightedField("title");
searchRequestBuilder.setHighlighterPreTags("<span style=\"color:red\">");
searchRequestBuilder.setHighlighterPostTags("</span>");
response = searchRequestBuilder.setFrom(start).setSize(pageSize).execute().actionGet();
SearchHit[] searchHits = response.getHits().hits();
// 封装分页对象信息
PagedResult disPage = new PagedResult();
disPage.setTotal(total);
disPage.setPages(totalPages);
disPage.setPageNo(currentNo);
disPage.setPageSize(pageSize);
for (SearchHit searchHit : searchHits) {
Map<String, Object> dd = searchHit.getSource();
JSONObject json = (JSONObject) JSONObject.toJSON(dd);
// 从设定的高亮域中取得指定域
Map<String, HighlightField> result = searchHit.highlightFields();
HighlightField titleField = result.get("title");
if (titleField != null) {
// 取得定义的高亮标签
Text[] titleTexts = titleField.fragments();
// 为title串值增加自定义的高亮标签
String title = "";
for (Text text : titleTexts) {
title += text;
}
json.put("title", title);
}
resultlist.add(json);
}
map.put("dispage", disPage);
map.put("jsonlist", resultlist);
return map;
}
/**
* @param currentNo
* 当前页
* @param pageSize
* 一页显示多少条记录
* @param totalNum
* 总记录
* @return
*/
public static int totalPage(Integer currentNo, Integer pageSize, int totalNum) {
int totalPages = 0;
if (totalNum % pageSize == 0) {
totalPages = totalNum / pageSize;
} else {
totalPages = totalNum / pageSize + 1;
}
return totalPages;
}
}