package cn.xdf.wlyy.solr.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.highlight.HighlightField;
import com.alibaba.fastjson.JSONObject;
import cn.xdf.wlyy.bbyh.vo.SearchParVo;
import cn.xdf.wlyy.utils.PagedResult;
/**
* Title. <br>
* ElasticSearch工具类.
* <p>
* Copyright: Copyright (c) 2017年7月7日 下午1:09:36
* <p>
* <p>
* Author: jinxudong@xdf.cn
* <p>
* Version: 1.0
* <p>
*/
/**
* Title. <br>
* ElasticSearch 工具类.
* <p>
* Copyright: Copyright (c) 2017年7月10日 上午9:05:30
* <p>
* 2016-3-21 Company: 北京新东方学校
* <p>
* Author: jinxudong@xdf.cn
* <p>
* Version: 1.0
* <p>
*/
public class EsUtil {
/** 启用日志 */
private static Logger logger = Logger.getLogger(EsUtil.class);
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.one");
// 获取第一个节点端口号
private static String port2 = resource.getString("es.port.two");
private static Settings settings;
//es加载一次 避免多次链接造成内存溢出 或者使用单例模式
static {
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)));
}
/**
* 创建索引 写入elasticsearch
*
* @param jsonlist
* 要创建索引的jsonlist数据
*/
public static void createIndex(List<JSONObject> jsonlist) {
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()) {
logger.info("写入索引库成功...");
} else {
logger.info("写入索引库失败...");
}
}
}
catch (Exception e) {
logger.error(e);
}
}
/**
* 根据索引id删除
*
* @param uids
* 索引id
*/
public static void deleteIndex(List<String> uids) {
for (int i = 0; i < uids.size(); i++) {
DeleteResponse dResponse = client.prepareDelete(index, type, uids.get(i)).execute().actionGet();
if (dResponse.isContextEmpty()) {
logger.info(uids.get(i) + "删除成功...");
} else {
logger.info(uids.get(i) + "删除失败...");
}
}
}
/**
* 根据索引名称删除
*
* @param indexName
* 索引库名称
*/
public static void deleteIndexLib(String indexName) {
DeleteIndexResponse dResponse = client.admin().indices().prepareDelete(indexName).execute().actionGet();
if (dResponse.isContextEmpty()) {
logger.info(indexName + "删除成功。");
} else {
logger.info(indexName + "删除失败");
}
}
/**
* @param uid
* 要更新的索引id
* @param json
* 要更新的json数据
*/
public static void updateIndex(String uid, JSONObject json) {
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()) {
logger.info(uid + "更新成功");
} else {
logger.info(uid + "更新失败");
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
logger.error(e);
}
catch (ExecutionException e) {
// TODO Auto-generated catch block
logger.error(e);
}
}
/**
* 多字段查询
*
* @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) {
searchRequestBuilder = client.prepareSearch(index);
HashMap<String, Object> map = new HashMap<String, Object>();
// 搜索结果集
List<JSONObject> resultlist = new ArrayList<JSONObject>();
QueryBuilder qb = null;
QueryBuilder qb_state = 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);
// 必要条件 查询需要显示的内容
qb_state = QueryBuilders.matchPhraseQuery("state", "1");
querybuilder.must(qb_state);
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;
}
}