91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

spring 操作elasticsearch查詢使用方法

發布時間:2020-09-03 02:23:09 來源:腳本之家 閱讀:420 作者:GOODDEEP 欄目:編程語言

最近學習了一下elasticsearch使用,網上的資料又很少,真是一個頭兩個大。好歹最后終于了解了。留個筆記做日后查詢。

package com.gooddeep.dev.elasticsearch.commons.dao; 
 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 
 
import org.elasticsearch.action.ActionFuture; 
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; 
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; 
import org.elasticsearch.action.search.SearchResponse; 
import org.elasticsearch.client.Client; 
import org.elasticsearch.cluster.health.ClusterHealthStatus; 
import org.elasticsearch.common.text.Text; 
import org.elasticsearch.index.query.BoolQueryBuilder; 
import org.elasticsearch.index.query.QueryBuilders; 
import org.elasticsearch.search.SearchHit; 
import org.elasticsearch.search.highlight.HighlightBuilder; 
import org.elasticsearch.search.highlight.HighlightBuilder.Field; 
import org.elasticsearch.search.sort.FieldSortBuilder; 
import org.elasticsearch.search.sort.SortOrder; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.domain.Page; 
import org.springframework.data.domain.PageImpl; 
import org.springframework.data.domain.PageRequest; 
import org.springframework.data.domain.Pageable; 
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; 
import org.springframework.data.elasticsearch.core.SearchResultMapper; 
import org.springframework.data.elasticsearch.core.query.Criteria; 
import org.springframework.data.elasticsearch.core.query.CriteriaQuery; 
import org.springframework.data.elasticsearch.core.query.DeleteQuery; 
import org.springframework.data.elasticsearch.core.query.IndexQuery; 
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder; 
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; 
import org.springframework.data.elasticsearch.core.query.SearchQuery; 
import org.springframework.data.elasticsearch.core.query.StringQuery; 
import org.springframework.stereotype.Component; 
 
import com.gooddeep.dev.core.helper.PropertyHelper; 
import com.gooddeep.dev.core.helper.UuidHelper; 
import com.gooddeep.dev.core.model.BasePage; 
import com.gooddeep.dev.elasticsearch.commons.model.EsBaseBean; 
import com.gooddeep.dev.elasticsearch.commons.service.EsBaseService; 
 
@Component("esBaseDao") 
public abstract class EsBaseDaoImpl<T> implements EsBaseDao<T> { 
 
  private Logger logger = LoggerFactory.getLogger(EsBaseService.class); 
 
  @Autowired 
  private ElasticsearchTemplate elasticsearchTemplate; 
 
  @Autowired 
  private Client esClient; 
 
   
  /** 
   * 插入或等新,需要有id,id需要自己生成 
   *  
   * @param tList 
   * @return 
   */ 
  public boolean insertOrUpdate(List<T> tList) { 
    List<IndexQuery> queries = new ArrayList<IndexQuery>(); 
    for (T t : tList) { 
      String id = ((EsBaseBean) t).getId(); 
      if (id == null) { 
        id = UuidHelper.getRandomUUID(); 
        ((EsBaseBean) t).setId(id); 
      } 
      IndexQuery indexQuery = new IndexQueryBuilder().withId(id).withObject(t).build(); 
      queries.add(indexQuery); 
    } 
    elasticsearchTemplate.bulkIndex(queries); 
    return true; 
  } 
 
  /** 
   * 插入或更新 
   *  
   * @param t 
   * @return 
   */ 
  public boolean insertOrUpdate(T t) { 
 
    String id = ((EsBaseBean) t).getId(); 
    if (id == null) { 
      id = UuidHelper.getRandomUUID(); 
      ((EsBaseBean) t).setId(id); 
    } 
    try { 
      IndexQuery indexQuery = new IndexQueryBuilder().withId(id).withObject(t).build(); 
      elasticsearchTemplate.index(indexQuery); 
      return true; 
    } catch (Exception e) { 
      logger.error("insert or update user info error.", e); 
      return false; 
    } 
  } 
 
  /** 
   * 刪除 
   *  
   * @param id 
   * @return 
   */ 
  public boolean deleteById(String id) { 
    try { 
      elasticsearchTemplate.delete(getEntityClass(), id); 
      return true; 
    } catch (Exception e) { 
      logger.error("delete " + getEntityClass() + " by id " + id 
          + " error.", e); 
      return false; 
    } 
  } 
   
  /** 
   * 刪除ids 
   * @param idList 
   * @return 
   */ 
  @Override 
  public boolean deleteByIds(List<String> idList) { 
    try { 
       CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); 
       criteriaQuery.setIds(idList); 
       elasticsearchTemplate.delete(criteriaQuery, getEntityClass()); 
      return true; 
    } catch (Exception e) { 
      e.printStackTrace(); 
      return false; 
    } 
  } 
 
 
  /** 
   * 根據條件查詢 
   * @param filedContentMap 不能為null 
   * @return 
   */ 
  public boolean deleteByQuery(Map<String,Object> filedContentMap) { 
    try { 
      DeleteQuery dq = new DeleteQuery(); 
       
      BoolQueryBuilder qb=QueryBuilders. boolQuery(); 
      if(filedContentMap!=null) 
        for (String key : filedContentMap.keySet()) {//字段查詢 
          qb.must(QueryBuilders.matchQuery(key,filedContentMap.get(key))); 
        } 
      dq.setQuery(qb);; 
      elasticsearchTemplate.delete(dq, getEntityClass());; 
      return true; 
    } catch (Exception e) { 
      e.printStackTrace(); 
      return false; 
    } 
  } 
  /** 
   * 檢查健康狀態 
   *  
   * @return 
   */ 
  public boolean ping() { 
    try { 
      ActionFuture<ClusterHealthResponse> health = esClient.admin() 
          .cluster().health(new ClusterHealthRequest()); 
      ClusterHealthStatus status = health.actionGet().getStatus(); 
      if (status.value() == ClusterHealthStatus.RED.value()) { 
        throw new RuntimeException( 
            "elasticsearch cluster health status is red."); 
      } 
      return true; 
    } catch (Exception e) { 
      logger.error("ping elasticsearch error.", e); 
      return false; 
    } 
  } 
 
  /** 
   * 條件查詢 
   *  
   * @param searchfields 
   *      查詢字段 
   * @param filedContentMap 
   *      字段和查詢內容 
   * @param sortField 
   *      排序 字段 
   * @param order 
   *      排序 
   * @param from 
   * @param size 
   * @return 
   */ 
  @Override 
  public BasePage<T> queryPage(Map<String,Object> filedContentMap, final List<String> heightFields, String sortField, SortOrder order, BasePage<T>basePage) { 
     
    Field[] hfields=new Field[0]; 
    if(heightFields!=null) 
    { 
      hfields = new Field[heightFields.size()]; 
      for (int i = 0; i < heightFields.size(); i++) { 
        hfields[i] = new HighlightBuilder.Field(heightFields.get(i)).preTags("<em style='color:red'>").postTags("</em>").fragmentSize(250); 
      } 
    } 
    NativeSearchQueryBuilder nsb = new NativeSearchQueryBuilder().withHighlightFields(hfields);//高亮字段 
    if (sortField != null && order != null)//排序 
      nsb.withSort(new FieldSortBuilder(sortField).ignoreUnmapped(true).order(order)); 
    if (basePage != null)//分頁 
      nsb.withPageable(new PageRequest(basePage.getPageNo(), basePage.getPageSize())); 
    BoolQueryBuilder qb=QueryBuilders. boolQuery(); 
    for (String key : filedContentMap.keySet()) {//字段查詢 
      qb.must(QueryBuilders.matchQuery(key,filedContentMap.get(key))); 
       
    } 
    //userKey=78e48b85e94911e0d285f4eec990d556 
    //fa6e9c5bb24a21807c59e5fd3b609e12 
    nsb.withQuery(qb); 
    SearchQuery searchQuery = nsb.build();//查詢建立 
 
    Page<T> page = null; 
    if (heightFields!=null&&heightFields.size() > 0) {//如果設置高亮 
      page = elasticsearchTemplate.queryForPage(searchQuery, 
          getEntityClass(), new SearchResultMapper() { 
            @SuppressWarnings("unchecked") 
            @Override 
            public <T> Page<T> mapResults(SearchResponse response,Class<T> clazz, Pageable pageable) { 
              List<T> chunk = new ArrayList<T>(); 
              for (SearchHit searchHit : response.getHits()) { 
                if (response.getHits().getHits().length <= 0) { 
                  return null; 
                } 
 
                Map<String, Object> entityMap = searchHit.getSource(); 
                for (String highName : heightFields) { 
                  Text text[]=searchHit.getHighlightFields().get(highName).fragments(); 
                  if(text.length>0) 
                  { 
                    String highValue = searchHit.getHighlightFields().get(highName).fragments()[0].toString(); 
                    entityMap.put(highName, highValue); 
                  } 
                } 
                chunk.add((T) PropertyHelper.getFansheObj( 
                    getEntityClass(), entityMap)); 
              } 
              if (chunk.size() > 0) { 
                return new PageImpl<T>((List<T>) chunk); 
              } 
              return new PageImpl<T>(new ArrayList<T>()); 
            } 
 
          }); 
    } else//如果不設置高亮 
    { 
      logger.info("#################"+qb.toString()); 
      page = elasticsearchTemplate.queryForPage(searchQuery,getEntityClass()); 
    } 
     
 
  // List<T> ts = page.getContent(); 
 
    basePage.setTotalRecord(page.getTotalElements()); 
    basePage.setResults(page.getContent()); 
    return basePage; 
  } 
 
   
  @Override 
  public List<T> queryList(Map<String, Object> filedContentMap,final List<String> heightFields, String sortField, SortOrder order) { 
    Field[] hfields=new Field[0]; 
    if(heightFields!=null) 
    { 
      hfields = new Field[heightFields.size()]; 
      for (int i = 0; i < heightFields.size(); i++) { 
        //String o="{\"abc\" : \"[abc]\"}"; 
        hfields[i] = new HighlightBuilder.Field(heightFields.get(i)).preTags("<em>").postTags("</em>").fragmentSize(250); 
      } 
    } 
    NativeSearchQueryBuilder nsb = new NativeSearchQueryBuilder().withHighlightFields(hfields);//高亮字段 
    if (sortField != null && order != null)//排序 
      nsb.withSort(new FieldSortBuilder(sortField).ignoreUnmapped(true).order(order)); 
    BoolQueryBuilder qb=QueryBuilders. boolQuery(); 
    for (String key : filedContentMap.keySet()) {//字段查詢 
      qb.must(QueryBuilders.matchQuery(key,filedContentMap.get(key))); 
       
    } 
    nsb.withQuery(qb); 
    SearchQuery searchQuery = nsb.build();//查詢建立 
    Page<T> page = null; 
    if (heightFields!=null&&heightFields.size() > 0) {//如果設置高亮 
      page = elasticsearchTemplate.queryForPage(searchQuery, 
          getEntityClass(), new SearchResultMapper() { 
            @SuppressWarnings("unchecked") 
            @Override 
            public <T> Page<T> mapResults(SearchResponse response,Class<T> clazz, Pageable pageable) { 
              List<T> chunk = new ArrayList<T>(); 
              for (SearchHit searchHit : response.getHits()) { 
                if (response.getHits().getHits().length <= 0) { 
                  return null; 
                } 
 
                Map<String, Object> entityMap = searchHit.getSource(); 
                for (String highName : heightFields) { 
                  String highValue = searchHit.getHighlightFields().get(highName).fragments()[0].toString(); 
                  entityMap.put(highName, highValue); 
                } 
                chunk.add((T) PropertyHelper.getFansheObj(getEntityClass(), entityMap)); 
              } 
              if (chunk.size() > 0) { 
                return new PageImpl<T>((List<T>) chunk); 
              } 
              return null; 
            } 
 
          }); 
    } else//如果不設置高亮 
      page = elasticsearchTemplate.queryForPage(searchQuery,getEntityClass()); 
     
    return page.getContent(); 
  } 
  /** 
   * 本類查詢 
   *  
   * @param id 
   * @return 
   */ 
  public T queryById(String id) { 
    StringQuery stringQuery = new StringQuery("id=" + id); 
    T t = elasticsearchTemplate.queryForObject(stringQuery, 
        getEntityClass()); 
    return t; 
 
  } 
 
   
   
  public ElasticsearchTemplate getElasticsearchTemplate() { 
    return elasticsearchTemplate; 
  } 
 
 
  public Client getEsClient() { 
    return esClient; 
  } 
 
 
 
  /** 
   * 得到類型 
   *  
   * @return 
   */ 
  public abstract Class<T> getEntityClass(); 
  /** 
   * 添加各自類的影射 
   */ 
  public abstract void putClassMapping(); 
   
 
 
   
 
} 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

嘉黎县| 贵定县| 闵行区| 秭归县| 彰化市| 谢通门县| 垫江县| 安泽县| 阳信县| 陕西省| 太和县| 南阳市| 浪卡子县| 正蓝旗| 扶沟县| 遵义县| 玛沁县| 应用必备| 通辽市| 苍南县| 黄梅县| 珠海市| 武汉市| 海盐县| 石柱| 大理市| 都江堰市| 诸城市| 金坛市| 凤城市| 山丹县| 山东省| 石景山区| 长寿区| 游戏| 东明县| 靖远县| 通许县| 永平县| 太谷县| 海伦市|