欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring 操作elasticsearch查询使用方法

程序员文章站 2024-02-18 09:14:52
最近学习了一下elasticsearch使用,网上的资料又很少,真是一个头两个大。好歹最后终于了解了。留个笔记做日后查询。 package com.gooddee...

最近学习了一下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(); 
   
 
 
   
 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。