1. 程式人生 > >ElasticSearch jestClient增刪改 索引基礎方法

ElasticSearch jestClient增刪改 索引基礎方法

package cn.focus.dc.app.xinfang.service.third;


import static cn.focus.dc.app.constants.AppConstants.ES_INDEX_PASSWORD;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Delete;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.mapping.GetMapping;
import io.searchbox.indices.mapping.PutMapping;


import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.google.gson.JsonObject;


import cn.focus.dc.app.exception.EsSearchException;
import cn.focus.dc.app.xinfang.model.es.qry.EsQuery;
import cn.focus.dc.app.xinfang.model.es.rst.EsResult;
import cn.focus.dc.app.xinfang.model.es.rst.Result;


@Service
public class EsAdvancedService {
private static final String PWDKEY = "X-SCE-ES-PASSWORD";
private static Logger logger = LoggerFactory.getLogger(EsAdvancedService.class);

    @Autowired
    private JestClient jestClient;
    /**
     * 建立索引
     * @param indexName
     * @return
     */
    public boolean createIndex(String indexName){
    CreateIndex createIndex = new CreateIndex(new CreateIndex.Builder(indexName));
    try{
    JestResult result = jestClient.execute(createIndex);
    if(result == null || !result.isSucceeded()){
    throw new Exception(result.getErrorMessage()+"建立索引失敗!");
    }
    }catch(Exception e){
    logger.error("",e);
    return false;
    }
    return true;
    }
    /**
     * 手動建立型別(map一旦定義建立,field只能新增,不能修改)
     * @param indexName
     * @param indexType
     * @param mappingString
     * @return
     */
    public boolean createType(String indexName, String indexType, String mappingString){
        PutMapping.Builder builder = new PutMapping.Builder(indexName, indexType, mappingString);
        builder.setHeader(PWDKEY, getSecret());
        builder.refresh(true);
        try {
            JestResult result = jestClient.execute(builder.build());
            if(result == null || !result.isSucceeded()){
            throw new RuntimeException(result.getErrorMessage()+"建立索引型別失敗!");
            }
        } catch (Exception e) {
            logger.error("",e);
            return false;
        }
        return true;
    }
    
    /**
     * 獲取索引型別mapping
     * 
     * @param typeName 型別名稱
     * @return
     */
    public String getMapping(String indexName,String typeName) {
        GetMapping.Builder builder = new GetMapping.Builder();
        builder.addIndex(indexName).addType(typeName);
        builder.setHeader("X-SCE-ES-PASSWORD", getSecret());
        try {
            JestResult result = jestClient.execute(builder.build());
            if (result != null && result.isSucceeded()) {
                return result.getSourceAsObject(JsonObject.class).toString();
            }
            logger.error("es get mapping Exception ", result.getErrorMessage());
        } catch (Exception e) {
            logger.error("", e);
        }
        return null;
    }
    /**
     * 刪除文件
     * @param indexId
     * @param indexName
     * @param indexType
     */
    public boolean deleteDoc(String indexId, String indexName, String indexType) {
        Delete.Builder builder = new Delete.Builder();
        builder.setHeader(PWDKEY, getSecret());
        builder.id(indexId);
        builder.refresh(true);
        Delete delete = builder.index(indexName).type(indexType).build();
        try {
        JestResult result = jestClient.execute(delete);
            if (result != null && !result.isSucceeded()) {
                throw new RuntimeException(result.getErrorMessage()+"刪除文件失敗!");
            }
        } catch (Exception e) {
            logger.error("",e);
            return false;
        }
        return true;
    }
    
    /**
     * 刪除型別
     * @param indexId
     * @param indexName
     * @param indexType
     */
    public boolean deleteType( String indexName, String indexType) {
        Delete.Builder builder = new Delete.Builder();
        builder.setHeader(PWDKEY, getSecret());
        builder.refresh(true);
        Delete delete = builder.index(indexName).type(indexType).build();
        try {
        JestResult result = jestClient.execute(delete);
            if (result != null && result.isSucceeded()) {
                throw new RuntimeException(result.getErrorMessage()+"刪除型別失敗!");
            }
        } catch (Exception e) {
            logger.error("",e);
            return false;
        }
        return true;
    }
    
    /**
     * 刪除索引
     * @param indexId
     * @param indexName
     * @param indexType
     */
    public boolean deleteIndex( String indexName) {
        Delete.Builder builder = new Delete.Builder();
        builder.setHeader(PWDKEY, getSecret());
        builder.refresh(true);
        Delete delete = builder.index(indexName).build();
        try {
        JestResult result = jestClient.execute(delete);
            if (result != null && result.isSucceeded()) {
                throw new RuntimeException(result.getErrorMessage()+"刪除索引失敗!");
            }
        } catch (Exception e) {
            logger.error("",e);
            return false;
        }
        return true;
    }
    /**
     * 插入或更新文件
     * @param indexId
     * @param indexObject
     * @param indexName
     * @param indexType
     * @return
     */
    public boolean insertOrUpdateDoc(String indexId, Object indexObject, String indexName, String indexType) {
        Index.Builder builder = new Index.Builder(indexObject);
        builder.setHeader(PWDKEY, getSecret());
        builder.id(indexId);
        builder.refresh(true);
        Index index = builder.index(indexName).type(indexType).build();
        try {
        JestResult result = jestClient.execute(index);
            if (result != null && !result.isSucceeded()) {
                throw new RuntimeException(result.getErrorMessage()+"插入更新索引失敗!");
            }
        } catch (Exception e) {
            logger.error("",e);
            return false;
        }
        return true;
    }
    /**
     * 通過一次查詢就可獲取查詢的結果(分頁)及總條數
     * @param classType
     * @param indexName
     * @param indexType
     * @param esQuery
     * @return
     */
    public <T extends Result> EsResult<T> search(Class<T> classType,String indexName,String indexType,EsQuery esQuery){
        try{
            Search.Builder builder = new Search.Builder(getQueryString(esQuery));
            builder.addIndex(indexName)
                          .addType(indexType)
                          .setHeader(PWDKEY, getSecret())
                          .setParameter("from", esQuery.getFrom())
                          .setParameter("size", esQuery.getSize())
                          ;
            if(esQuery.getSort()!=null){
                builder.addSort(esQuery.getSort());
            }
            JestResult jestResult = jestClient.execute(builder.build());
            int hitCount = jestResult.getJsonObject().get("hits").getAsJsonObject().get("total").getAsInt();
            EsResult<T> result = new EsResult<T>();
            result.setTotalNum(hitCount);
            result.setResultList(jestResult.getSourceAsObjectList(classType));
            return result;
        }catch(Exception e){
            throw new EsSearchException(e);
        }
    }
    
    private String getQueryString(EsQuery esQuery){
    return "{\"query\":" + esQuery.buildQuery().toString() + "}";
    }
    
    protected static String getSecret() {
        long time = System.currentTimeMillis() / 1000;
        return time + "," + DigestUtils.md5Hex(time + ES_INDEX_PASSWORD).toUpperCase();
    }
}

相關推薦

ElasticSearch jestClient刪改 索引基礎方法

package cn.focus.dc.app.xinfang.service.third; import static cn.focus.dc.app.constants.AppConstants.ES_INDEX_PASSWORD; import io.searchbo

laravel中的數據庫操作(刪改查)方法

-s delet 增刪 insert 修改 name tro des 命名空間 導入命名空間和DBnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB; public function index

MySQL刪改基礎知識

add 內連接 har ren 組合 lec 字段 傳統 efault 前幾天學習了MySQL數據庫的一些基礎知識,了解了後臺數據庫的一些基礎的數據操作:增刪改查,對於項目前後臺的數據傳遞有了些概念,總結了一些MySQL的基礎語法。 一、數據存儲形式發展和數據庫作用 根

MySQL 刪改基礎

group by sum between let 建數據庫 drop null ret limit 終端登錄mysql:   mysql -u root -p   1111aaaa 創建數據庫:   create DATABASE DBname; 刪除數據庫:   dro

python 列表(list)刪改查及方法

                                 強大自己是唯一獲得幸福的途徑,這是長遠的,而非當下的玩樂!

python 字典(dict)刪改查及方法

                                          &nb

使用kibana操作elasticsearch實現刪改

本篇部落格,本人寫的是方法,大家將對應的欄位放入對應的位置就可以了 注:elasticsearch中,索引相當於MySQL中的資料庫,型別相當於資料庫中的表,即索引名就為資料庫庫名,型別就為表名 1、建立索引 方式一: PUT /lib/ {   &nbs

SpringBoot 整合Elasticsearch 實現刪改

Elasticsearch簡介 Elasticsearch是一個基於Lucene的搜尋伺服器。 它提供了一個分散式多使用者能力的全文搜尋引擎,基於RESTful web介面。Elasticsearch是用Java開發的,並作為Apache許可條款下的開放原始碼釋出,是當前流行的企業級

mongoose 刪改基礎

###1.1 名詞解釋 Schema(模式,架構) : 一種以檔案形式儲存的資料庫模型骨架,不具備資料庫的操作能力 Mode(模型) : 由Schema釋出生成的模型,具有抽象屬性和行為的資料庫操作對 Entity(實體) : 由

elasticsearch java 刪改查 版本2

ElasticSearch(名稱太長,後面簡稱ES)作為一個搜尋引擎,目前可謂是如日中天,幾乎和solr齊駕並驅。關於他能做什麼,跟雲端計算有什麼關係,在此不再描述。但是ES的官方文件,特別是關於java的客戶端文件,真是少的可憐,甚至連個完整的增刪改的示例都沒有。在此,

UAP具體實現刪改查的方法

       UAP中對錶單的儲存、增刪改查以及自定義的分頁查詢方法如下: 1.建立controller類,對錶單值的獲取和對資料庫的儲存。具體程式碼如下: package com.sgcc.module1.pm_001; import java.io.Serializab

使用kibana給elasticsearch完成刪改查資料

首先我們啟動elasticsearch、elasticsearch-head和kibana (前提是已經安裝好了) elasticsearch的啟動只需在 cmd 中執行 elasticsearch.bat檔案 elasticsearch-head 需要安裝node.j

kibana對Elasticsearch刪改查操作,以及一些聚合查詢

kibana是一個視覺化平臺,設計出來用於和Elasticsearch一起使用的。你可以用kibana搜尋、檢視、互動存放在Elasticsearch索引裡的資料。 準備工作:Elasticsearch啟動完畢,elasticsearch-head啟動完畢 kibana 啟動完畢

Hibernate(四):Hibernate的初始化,刪改查等方法

1,Hibernate初始化類 package com.hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Sessi

MYSQL資料庫 刪改基礎語句

語法:create table tablename(column_name_1 column_type_1 constraints,column_name_2 column_type_2 constraints,column_name_3 column_type_3 constraints)

Java中刪改查通用方法

public class BaseDAO { private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private static final String URL = "jdbc:sqlserv

關於jdbc 刪改通用的方法,只需要傳sql語句和查詢條件

//第二個引數為給佔位符賦值,可以理解為一個數組 //例如executeUpdate("select *from user where id=? and pwd =?","admin","123") public int executeUpdate(String sql,O

elasticsearch document 刪改原理

對於叢集而言,任意一個node都知道document在哪個node上的(路由演算法),所以,對於client來說,請求任和一個node都是一樣的。 client選擇任一node,將增(刪、改)請求傳送到改node 改node接收到request,變為coordinating node(協調節點) coord

基於ajax的三層,實現資料庫刪改基礎(一DAL)

  三層的組成就是DAL,BLL,UI層和Model層。其中的DAL層是與資料庫連結,需要引用Model層,進行對資料的操作,但我們一般在此層不進行資料的處理。BLL層負責引用DAL和MODEL層,在

ElasticSearch刪改查API介紹

1、基本用法 Elasticsearch叢集可以包含多個索引(indices),每一個索引可以包含多個型別(types),每一個型別包含多個文件(documents),然後每個文件包含多個欄位(Fields),它是面向文件型的儲存。ES比傳統關係型資料庫,就像