Elasticsearch基本應(yīng)用(java)API(三)

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");
    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末周偎,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌余境,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件灌诅,死亡現(xiàn)場離奇詭異芳来,居然都是意外死亡,警方通過查閱死者的電腦和手機猜拾,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進(jìn)店門即舌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人挎袜,你說我怎么就攤上這事顽聂。” “怎么了宋雏?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵芜飘,是天一觀的道長务豺。 經(jīng)常有香客問我磨总,道長,這世上最難降的妖魔是什么笼沥? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任蚪燕,我火速辦了婚禮娶牌,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘馆纳。我一直安慰自己诗良,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布鲁驶。 她就那樣靜靜地躺著鉴裹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪钥弯。 梳的紋絲不亂的頭發(fā)上径荔,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天,我揣著相機與錄音脆霎,去河邊找鬼总处。 笑死,一個胖子當(dāng)著我的面吹牛睛蛛,可吹牛的內(nèi)容都是我干的鹦马。 我是一名探鬼主播,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼忆肾,長吁一口氣:“原來是場噩夢啊……” “哼荸频!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起客冈,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤试溯,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后郊酒,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體遇绞,經(jīng)...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年燎窘,在試婚紗的時候發(fā)現(xiàn)自己被綠了摹闽。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡褐健,死狀恐怖付鹿,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蚜迅,我是刑警寧澤舵匾,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站谁不,受9級特大地震影響坐梯,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜刹帕,卻給世界環(huán)境...
    茶點故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一吵血、第九天 我趴在偏房一處隱蔽的房頂上張望谎替。 院中可真熱鬧,春花似錦蹋辅、人聲如沸钱贯。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽秩命。三九已至,卻和暖如春褒傅,著一層夾襖步出監(jiān)牢的瞬間硫麻,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工樊卓, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留拿愧,地道東北人。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓碌尔,卻偏偏與公主長得像浇辜,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子唾戚,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,927評論 2 355

推薦閱讀更多精彩內(nèi)容