package com.wiwj.app.search.util;
import com.wiwj.app.common.constant.PropertyConstantsKey;
import com.wiwj.app.common.constant.PropertyTools;
import com.wiwj.app.search.conf.ElasticSearch;
import com.wiwj.app.util.Util;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* <p>Title: ElasticsearchOperUtil.java</p>
*
* <p>Package: core.util</p>
*
* <p>Description: ES操作工具類</p>
*
* @author:
*
* @date: 2017年5月10日 下午2:16:20
*
* @version: 1.0
*/
public class ElasticsearchOperUtil {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ElasticsearchOperUtil.class);
/** ESclient */
private static Client client = ElasticSearch.getInstance().getESClient();
/**
*
* @Title: deleteByType
* @Description: 刪除某一類型所有數(shù)據(jù)
* @author:
* @date: 2017年5月26日 下午4:18:21
* @param index
* @param type
* @return
*/
@SuppressWarnings("deprecation")
public static boolean deleteByType(String index,String type){
//刪除es中的視圖
MatchAllQueryBuilder allQueryBuilder = QueryBuilders.matchAllQuery();
client.prepareDeleteByQuery(index).setQuery(allQueryBuilder).setTypes(type).execute().actionGet();
return true;
}
/**
*
* @Title: queryData
* @Description: 單字段查詢
* @author:
* @date: 2017年5月10日 上午10:43:31
* @param index
* @param type
* @param primaryColumn
* @param primaryColumn_value
* @return
*/
public static List<String> queryData(String index,String type,String primaryColumn, String primaryColumn_value){
try {
BoolQueryBuilder querySql = QueryBuilders.boolQuery();
querySql.must(QueryBuilders.termQuery(primaryColumn, primaryColumn_value));
SearchRequestBuilder searchRequest = client.prepareSearch(index)
.setTypes(type).setQuery(querySql).setFrom(0).setSize(10000);
SearchResponse actionGet = searchRequest.execute().actionGet();
SearchHits hits = actionGet.getHits();
String json = "";
List<String> dataList = new ArrayList<String>();
for (SearchHit hit : hits) {
json = hit.getSourceAsString();
dataList.add(json);
}
return dataList;
} catch (Exception e) {
return null;
}
}
/**
*
* @Title: addData
* @Description: 添加數(shù)據(jù)
* @author:
* @date: 2017年5月9日 下午3:05:52
* @param index
* @param type
* @param dataJson
* @return
*/
public static boolean addData(String index,String type,String dataJson) throws Exception{
BulkRequestBuilder bulkRequest = client.prepareBulk();
IndexRequest request = client.prepareIndex(index, type,"主鍵ID")//如果不指定主鍵ID人柿,則es會生成一個隨機的主鍵ID
.setSource(dataJson).request();
bulkRequest.add(request);
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
logger.info(bulkResponse.buildFailureMessage());
return false;
}
return true;
}
/**
*
* @Title: deleteBySingleColumnConditon
* @Description: 刪除 列=value
* @author:
* @date: 2017年5月9日 下午3:01:53
* @param index
* @param type
* @param column
* @param value
* @return
*/
@SuppressWarnings("deprecation")
public static boolean deleteBySingleColumnConditon(String index,String type,String column,String value) throws Exception{
QueryBuilder query = QueryBuilders.matchQuery(column, value);
client.prepareDeleteByQuery(index).setTypes(type).setQuery(query).execute().actionGet();
return true;
}
/**
* <pre>deleteBySingleColumnConditon(根據(jù)id=id1,id2刪除)
* 創(chuàng)建人:
* 創(chuàng)建時間:2017年7月20日 上午10:51:57
* 修改人:
* 修改時間:2017年7月20日 上午10:51:57
* 修改備注:
* @param index
* @param type
* @param column
* @param value 多個條件的值集合
* @return</pre>
*/
@SuppressWarnings("deprecation")
public static boolean deleteBySingleColumnConditon(String index,String type,String column,List<String> value){
try {
QueryBuilder query = QueryBuilders.termsQuery(column, value);
client.prepareDeleteByQuery(index).setTypes(type).setQuery(query).execute().actionGet();
return true;
} catch (Exception e) {
return false;
}
}
/**
* @Title: deleteBySingleColumnConditon
* @Description: 根據(jù)多個主鍵刪除
* @author:
* @date: 2017/9/11 18:15
* @param index
* @param type
*/
public static boolean deleteByMultipleColumnConditon(String index,String type,Map<String,List> prama){
try {
BoolQueryBuilder querySql = QueryBuilders.boolQuery();
Set<Map.Entry<String, List>> entries = prama.entrySet();
for (Map.Entry<String, List> entry : entries) {
querySql.must(QueryBuilders.termsQuery(entry.getKey(), entry.getValue()));
}
client.prepareDeleteByQuery(index).setTypes(type).setQuery(querySql).execute().actionGet();
return true;
} catch (Exception e) {
return false;
}
}
/**
* 根據(jù)map多條件刪除
* @param index
* @param type
* @param prama
* @return
*/
public static boolean deleteByMultiStringColumnConditon(String index,String type,Map<String,Object> prama){
try {
BoolQueryBuilder querySql = QueryBuilders.boolQuery();
Set<Map.Entry<String, Object>> entries = prama.entrySet();
for (Map.Entry<String, Object> entry : entries) {
querySql.must(QueryBuilders.termsQuery(entry.getKey(), String.valueOf(entry.getValue())));
}
client.prepareDeleteByQuery(index).setTypes(type).setQuery(querySql).execute().actionGet();
return true;
} catch (Exception e) {
return false;
}
}
/**
*
* @Title: queryAllDataByIndexAndType
* @Description: 查詢所有數(shù)據(jù)
* @author:
* @date: 2017年5月18日 下午2:31:00
* @param index
* @param type
* @return
*/
public static List<String> queryAllDataByIndexAndType(String index,String type){
try {
BoolQueryBuilder querySql = QueryBuilders.boolQuery();
SearchRequestBuilder searchRequest = client.prepareSearch(index)
.setTypes(type).setQuery(querySql).setFrom(0).setSize(100000);
SearchResponse actionGet = searchRequest.execute().actionGet();
SearchHits hits = actionGet.getHits();
String json = "";
List<String> dataList = new ArrayList<String>();
for (SearchHit hit : hits) {
json = hit.getSourceAsString();
dataList.add(json);
}
return dataList;
} catch (Exception e) {
return null;
}
}
/**
*
* @Title: deleteData
* @Description: 根據(jù)id刪除數(shù)據(jù)
* @author:
* @date: 2017年6月22日 下午4:44:49
* @param index
* @param type
* @param ids
*/
@SuppressWarnings("unused")
public static void deleteDataByids(String index,String type, String ids) throws Exception{
String[] idArr = ids.split(",");
for (int i = 0; i < idArr.length; i++) {
DeleteResponse response = client.prepareDelete(index, type, idArr[i])
.execute()
.actionGet();
}
}
/**
* <pre>bulkSyncToEs(批量同步es)
* 創(chuàng)建人
* 創(chuàng)建時間:2017年7月20日 上午10:46:52
* 修改人:
* 修改時間:2017年7月20日 上午10:46:52
* 修改備注:
* @param list(包含三個參數(shù),index+type:當(dāng)前數(shù)據(jù)對應(yīng)的es的index+type欲逃,json為組裝好的json格式數(shù)據(jù))</pre>
*/
public static boolean bulkSyncToEs(List<Map<String,Object>> list) throws Exception{
BulkRequestBuilder bulkRequest = client.prepareBulk();
Map<String,Object> bean = null;
if(null==list || list.size()==0){
return true;
}
for (int i = 0; i < list.size(); i++) {
bean = list.get(i);
String beanJson = Util.null2String(bean.get("json"));
String index = Util.null2String(bean.get("index"));
String type = Util.null2String(bean.get("type"));
IndexRequest request = client.prepareIndex(index, type)
.setSource(beanJson).request();
bulkRequest.add(request);
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
logger.info(bulkResponse.buildFailureMessage());
return false;
}
return true;
}
/**
* <pre>bulkSyncToEs(批量同步es)
* 創(chuàng)建人:
* 創(chuàng)建時間:2017年7月20日 上午10:56:05
* 修改人
* 修改時間:2017年7月20日 上午10:56:05
* 修改備注:
* @param list 多條json格式數(shù)據(jù)集合
* @param index
* @param type</pre>
*/
public static boolean bulkSyncToEs(List<String> list, String index, String type) throws Exception{
BulkRequestBuilder bulkRequest = client.prepareBulk();
String beanJson = null;
if(null==list || list.size()==0){
return true;
}
for (int i = 0; i < list.size(); i++) {
beanJson = list.get(i);
IndexRequest request = client.prepareIndex(index, type)
.setSource(beanJson).request();
bulkRequest.add(request);
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
beanJson = bulkResponse.buildFailureMessage();
logger.info(beanJson);
return false;
}
return true;
}
/**
* 拼接過濾查詢條件
* @param querySql
* @param cityid 城市id
* @param filtertype 類型(1:已售,2:行情,3:小區(qū))
*/
public static void generateSensitiveFilterQuery(BoolQueryBuilder querySql,Integer cityid,Integer filtertype){
if(null == cityid){
return ;
}
String key_prefix;
switch (filtertype){
case 1:
key_prefix = PropertyConstantsKey.sensitivefilter_cjrecord_sale_prefix;
break;
case 2:
key_prefix = PropertyConstantsKey.sensitivefilter_market_sale_prefix;
break;
case 3:
key_prefix = PropertyConstantsKey.sensitivefilter_xiaoqu_sale_prefix;
break;
case 4:
key_prefix = PropertyConstantsKey.sensitivefilter_cjrecord_rent_prefix;
break;
default:
key_prefix = null;
break;
}
if(StringUtils.isBlank(key_prefix)){
return ;
}
String sensitive_config = PropertyTools.getProperty(key_prefix+cityid);
if(StringUtils.isNotBlank(sensitive_config)){
String [] configArr = sensitive_config.split("-");
if(configArr[2].equals("0")){
querySql.must(QueryBuilders.rangeQuery(configArr[0]).lte(configArr[1]));
}else if(configArr[2].equals("1")){
querySql.must(QueryBuilders.rangeQuery(configArr[0]).gt(configArr[1]));
}else if(configArr[2].equals("2")){
querySql.must(QueryBuilders.rangeQuery(configArr[0]).gte(configArr[1]));
}else if ((configArr[4].equals("3"))){//房價行情
BoolQueryBuilder queryhp = new BoolQueryBuilder();
queryhp.should(QueryBuilders.rangeQuery(configArr[0]).gte(configArr[1]).lte(configArr[2]));
queryhp.should(QueryBuilders.termQuery(configArr[0],configArr[3]));
querySql.must(QueryBuilders.filteredQuery(queryhp,null));
}
}
}
public static void main(String[] args) {
//ElasticsearchOperUtil.deleteDataByids("cjrecordv1", "cjrecord", "AVzOMcFvgSaZyI-JGdBi,AVzOMcFvgSaZyI-JGc15,AVzOMcFvgSaZyI-JGc1t,AVzOMcFvgSaZyI-JGdBj,AVzOMcFvgSaZyI-JGdBh");
//deleteByType(ElasticConstant.getCityIndexMap().get(20),"whExchangeHouse");
//deleteByType(ElasticConstant.getCityIndexMap().get(20),"whExchangeWebHouse");
}
}
Elasticsearch基本應(yīng)用(java)API(三)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門即舌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人挎袜,你說我怎么就攤上這事顽聂。” “怎么了宋雏?”我有些...
- 文/不壞的土叔 我叫張陵芜飘,是天一觀的道長务豺。 經(jīng)常有香客問我磨总,道長,這世上最難降的妖魔是什么笼沥? 我笑而不...
- 正文 為了忘掉前任蚪燕,我火速辦了婚禮娶牌,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘馆纳。我一直安慰自己诗良,他們只是感情好,可當(dāng)我...
- 文/花漫 我一把揭開白布鲁驶。 她就那樣靜靜地躺著鉴裹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪钥弯。 梳的紋絲不亂的頭發(fā)上径荔,一...
- 文/蒼蘭香墨 我猛地睜開眼忆肾,長吁一口氣:“原來是場噩夢啊……” “哼荸频!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起客冈,我...
- 正文 年R本政府宣布,位于F島的核電站谁不,受9級特大地震影響坐梯,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜刹帕,卻給世界環(huán)境...
- 文/蒙蒙 一吵血、第九天 我趴在偏房一處隱蔽的房頂上張望谎替。 院中可真熱鬧,春花似錦蹋辅、人聲如沸钱贯。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽秩命。三九已至,卻和暖如春褒傅,著一層夾襖步出監(jiān)牢的瞬間硫麻,已是汗流浹背。 一陣腳步聲響...
推薦閱讀更多精彩內(nèi)容
- rabbitmq官方文檔:http://www.rabbitmq.com/getstarted.html Rabb...
- 最近有個日志收集監(jiān)控的項目采用的技術(shù)棧是ELK+JAVA+Spring柳洋,客戶端語言使用的是Java,以后有機會的話...
- 分享包括故事和干貨叹坦。 故事篇 10年專業(yè)化 工作沒法選熊镣,但是可以選擇工作態(tài)度。在湛江做十年程序員募书,雖然剛?cè)肷鐣鞔眩?..
- 抽煙、喝酒莹捡、啪啪啪...這三樣?xùn)|西幾乎很多人每天都要做鬼吵,之前跟大家聊過前兩樣對健身有沒有影響了,這次我想來聊一聊最...