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

详解spring中使用Elasticsearch的代码实现

程序员文章站 2024-02-13 15:08:22
在使用elasticsearch之前,先给大家聊一点干货。 1.      es和solr都是作为全文搜索引擎出现的...

在使用elasticsearch之前,先给大家聊一点干货。

1.      es和solr都是作为全文搜索引擎出现的。都是基于lucene的搜索服务器。

2.   es不是可靠的存储系统,不是数据库,它有丢数据的风险。

3.  es不是实时系统,数据写入成功只是trans log成功(类似于mysql的bin log),写入成功后立刻查询查不到是正常的。因为数据此刻可能还在内存里而不是进入存储引擎里。同理,删除一条数据后也不是马上消失。写入何时可查询?es内部有一个后台线程,定时将内存中的一批数据写入到存储引擎,此后数据可见。默认后台线程一秒运行一次。该线程运行的越频繁,写入性能越低。运行的频率越低,写入的性能越高(不会无限高)。

4.    目前已知的单es集群可以存储pb级别的数据,不过这个就非常费劲了。tb级别数据没压力。

5.    如果使用es官方提供的jar包访问,需要jdk1.7及以上。

6.    使用对应的版本访问es server。如果es server端的版本是1.7,那么请使用es 1.7的client。如果es server是2.1,请使用2.1的client。

7.     es索引存在linux服务器的文件系统之上(背后是文件系统,不是类似于hdfs的分布式文件系统)

8.     es java client是线程安全的,全局构建一个即可满足读写需求,不要每次都创建es client。每次访问es都构建新的es client即会抛出次异常。

9.    非常不建议使用es的动态识别和创建的机制,因为很多情况下这并非你所需要。推荐的做法是在写数据之前仔细的创建mapping。

10.   强烈不建议在es中使用深分页。可能会导致集群不可用。

11.    es是静态分片,一旦分片数在创建索引时确定那么后继不能修改。

12.    es里提供了type,很多人以为type是物理表,一个type的数据是独立存储的;但是在es内部并不是这样,type在es内部仅仅是一个字段。所以在很多数据能分为独立index的情况下,不要放到一个index里用type去分。只有嵌套类和父子类的情况下使用type才是合理的。

13.    es并不提供原生的中文分词的能力。有第三方的中文分词的插件,比如ik等。ik是个toy分词器,有严肃的分词需求的话,请在使用es之前使用独立的分词器分好词后向es写入。

14.    es中的index,首先会进行分片,每一个分片数据一般都会有自己的副本数据,es分配分片的策略会保证同一个分片数据和自己的副本不会分配到同一个节点上。当集群中的某一节点宕机后,es的master在ping该节点时通过一定的策略会发现该节点不存活;会开启es的恢复过程

15.    es没有update的能力。所有的update都是标记删除老文档,然后重新insert一条新文档。

好了,回归正题。

首先:

增加我们的spring配置

<bean id="client" factory-bean="esclientbuilder" factory-method="init" destroy-method="close"/> 
 
  <bean id="esclientbuilder" class="com.***.esclientbuilder"> 
    <property name="clustername" value="集群名称" /> 
    <property name="nodeipinfo" value="集群地址" /> 
  </bean> 

其次:

编写我们的esclientbuilder类初始化我们的es参数

package ***; 
import java.net.inetaddress; 
import java.net.unknownhostexception; 
import java.util.hashmap; 
import java.util.map; 
import org.elasticsearch.client.client; 
import org.elasticsearch.client.transport.transportclient; 
import org.elasticsearch.common.settings.settings; 
import org.elasticsearch.common.transport.inetsockettransportaddress; 
public class esclientbuilder { 
 
 
  private string clustername; 
  private string nodeipinfo; 
  private transportclient client; 
 
  public client init(){ 
    //设置集群的名字 
    settings settings = settings.settingsbuilder() 
        .put("client.transport.sniff", false) 
        .put("cluster.name", clustername) 
        .build(); 
    //创建集群client并添加集群节点地址 
    client = transportclient.builder().settings(settings).build(); 
    map<string, integer> nodemap = parsenodeipinfo(); 
    for (map.entry<string,integer> entry : nodemap.entryset()){ 
      try { 
        client.addtransportaddress(new inetsockettransportaddress(inetaddress.getbyname(entry.getkey()), entry.getvalue())); 
      } catch (unknownhostexception e) { 
        e.printstacktrace(); 
      } 
    } 
 
    return client; 
  } 
 
  /** 
   * 解析节点ip信息,多个节点用逗号隔开,ip和端口用冒号隔开 
   * 
   * @return 
   */ 
  private map<string, integer> parsenodeipinfo(){ 
    string[] nodeipinfoarr = nodeipinfo.split(","); 
    map<string, integer> map = new hashmap<string, integer>(nodeipinfoarr.length); 
    for (string ipinfo : nodeipinfoarr){ 
      string[] ipinfoarr = ipinfo.split(":"); 
      map.put(ipinfoarr[0], integer.parseint(ipinfoarr[1])); 
    } 
    return map; 
  } 
 
  public string getclustername() { 
    return clustername; 
  } 
 
  public void setclustername(string clustername) { 
    this.clustername = clustername; 
  } 
 
  public string getnodeipinfo() { 
    return nodeipinfo; 
  } 
 
  public void setnodeipinfo(string nodeipinfo) { 
    this.nodeipinfo = nodeipinfo; 
  } 
} 

最后:

下面我们就可以写自己的service类了,此类就可以通过es的原生api来操作我们的es(这里我们展示的2.x版本的)
indexname相当于数据库名,typename相当于表名

请参考esserviceimpl.java文件

package ***; 
 
@service("esservice") 
public class esserviceimpl{ 
 
  @autowired 
  private client client; 
 
  /** 
   * 用docid获取document 
   * @param indexname 
   * @param typename 
   * @param docid 
   */ 
  private static void getwithid(string indexname, string typename, string docid) { 
    //get with id 
    getresponse gresponse = client.prepareget(indexname, typename, docid).execute().actionget(); 
    system.out.println(gresponse.getindex()); 
    system.out.println(gresponse.gettype()); 
    system.out.println(gresponse.getversion()); 
    system.out.println(gresponse.isexists()); 
    map<string, object> results = gresponse.getsource(); 
    if(results != null) { 
      for(string key : results.keyset()) { 
        object field = results.get(key); 
        system.out.println(key); 
        system.out.println(field); 
      } 
    } 
  } 
  private static void indexwithbulk(string index, string type) { 
        //指定索引名称,type名称和documentid(documentid可选,不设置则系统自动生成)创建document 
        indexrequest ir1 = new indexrequest(); 
        string source1 = "{" + "\"user\":\"kimchy\"," + "\"price\":\"6.3\"," + "\"tid\":\"20001\"," + "\"message\":\"elasticsearch\"" + "}"; 
        ir1.index(index).type(type).id("100").source(source1); 
        indexrequest ir2 = new indexrequest(); 
        string source2 = "{" + "\"user\":\"kimchy2\"," + "\"price\":\"7.3\"," + "\"tid\":\"20002\"," + "\"message\":\"elasticsearch\"" + "}"; 
        ir2.index(index).type(type).id("102").source(source2); 
        indexrequest ir3 = new indexrequest(); 
        string source3 = "{" + "\"user\":\"kimchy3\"," + "\"price\":\"8.3\"," + "\"tid\":\"20003\"," + "\"message\":\"elasticsearch\"" + "}"; 
        ir3.index(index).type(type).id("103").source(source3); 
        bulkresponse response = client.preparebulk().add(ir1).add(ir2).add(ir3).execute().actionget(); 
        bulkitemresponse[] responses = response.getitems(); 
        if(responses != null && responses.length > 0) { 
          for(bulkitemresponse r : responses) { 
            string i = r.getindex(); 
            string t = r.gettype(); 
            system.out.println(i+","+t); 
          } 
        } 
     
  } 
  private static void sumcountsearch(string indexname, string typename, 
    string sumfield, string countfield, string searchfield, string searchvalue) { 
    sumbuilder sb = aggregationbuilders.sum("sumprice").field(sumfield); 
    termquerybuilder tb = querybuilders.termquery(searchfield, searchvalue); 
    searchresponse sresponse = client.preparesearch(indexname).settypes(typename).setquery(tb).addaggregation(sb).execute().actionget(); 
    map<string, aggregation> aggmap = sresponse.getaggregations().asmap(); 
    if(aggmap != null && aggmap.size() > 0) { 
      for(string key : aggmap.keyset()) { 
        if("sumprice".equals(key)) { 
          sum s = (sum)aggmap.get(key); 
          system.out.println(key + "," + s.getvalue());   
        } 
        else if("counttid".equals(key)) { 
          statsbuilder c = (statsbuilder)aggmap.get(key); 
          system.out.println(key + "," + c.tostring()); 
        } 
      } 
    } 
  } 
  private static void updatedoc(string indexname, string typename, string id) throws ioexception, interruptedexception, executionexception { 
    updaterequest updaterequest = new updaterequest(); 
    updaterequest.index(indexname); 
    updaterequest.type(typename); 
    updaterequest.id(id); 
    updaterequest.doc(jsonbuilder().startobject().field("gender", "male").endobject()); 
    updateresponse resp = client.update(updaterequest).get(); 
    resp.getclass(); 
  } 
  private static void scrollsearch(string indexname, string typename, string... ids) { 
    idsquerybuilder qb = querybuilders.idsquery().addids(ids); 
    searchresponse sresponse = client.preparesearch(indexname) 
        .settypes(typename) 
        .setsearchtype(searchtype.scan) 
        .setquery(qb) 
        .setscroll(new timevalue(100)) 
        .setsize(50) 
        .execute() 
        .actionget(); 
    int tshards = sresponse.gettotalshards(); 
    long timecost = sresponse.gettookinmillis(); 
    int sshards = sresponse.getsuccessfulshards(); 
    system.out.println(tshards+","+timecost+","+sshards); 
     
    while (true) { 
      searchhits hits = sresponse.gethits(); 
      searchhit[] hitarray = hits.gethits(); 
      for(int i = 0; i < hitarray.length; i++) { 
        searchhit hit = hitarray[i]; 
        map<string, object> fields = hit.getsource(); 
        for(string key : fields.keyset()) { 
          system.out.println(key); 
          system.out.println(fields.get(key)); 
        } 
      } 
      sresponse = client.preparesearchscroll(sresponse.getscrollid()).setscroll(new timevalue(100)).execute().actionget(); 
      if (sresponse.gethits().gethits().length == 0) { 
        break; 
      } 
    } 
  } 
  private static void deletedocuments(string string, string string2) { 
    searchresponse sresponse = client.preparesearch(string) 
        .settypes(string2) 
        .setsearchtype(searchtype.query_then_fetch) 
        .setquery(querybuilders.matchallquery()) 
        .setfrom(0).setsize(60) 
        .execute() 
        .actionget(); 
    searchhits hits = sresponse.gethits(); 
    long count = hits.gettotalhits(); 
    searchhit[] hitarray = hits.gethits(); 
    list<string> ids = new arraylist<string>(hitarray.length); 
    for(int i = 0; i < count; i++) { 
      system.out.println("=================================="); 
      searchhit hit = hitarray[i]; 
      ids.add(hit.getid()); 
       
    } 
    for(string id : ids) { 
      deleteresponse response = client.preparedelete(string, string2, id).execute().actionget(); 
    }   
  } 
  private static void daterangesearch(string indexname, string typename, 
      string termname, string from, string to) { 
    // 构建range query 
    //2015-08-20 12:27:11 
        querybuilder qb = querybuilders.rangequery(termname).from(from).to(to); 
        searchresponse sresponse = client.preparesearch(indexname) 
            .settypes(typename) 
            // 设置search type 
            // 常用search type用:query_then_fetch 
            // query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
            .setsearchtype(searchtype.query_then_fetch) 
            // 查询的termname和termvalue 
            .setquery(qb) 
            // 设置排序field 
            .addsort(termname, sortorder.desc) 
            // 设置分页 
            .setfrom(0).setsize(60).execute().actionget(); 
        int tshards = sresponse.gettotalshards(); 
        long timecost = sresponse.gettookinmillis(); 
        int sshards = sresponse.getsuccessfulshards(); 
        system.out.println(tshards + "," + timecost + "," + sshards); 
        searchhits hits = sresponse.gethits(); 
        long count = hits.gettotalhits(); 
        searchhit[] hitarray = hits.gethits(); 
        for (int i = 0; i < count; i++) { 
          searchhit hit = hitarray[i]; 
          map<string, object> fields = hit.getsource(); 
          for (string key : fields.keyset()) { 
            system.out.println(key); 
            system.out.println(fields.get(key)); 
          } 
        } 
  } 
  private static void daterangesearch2(string indexname, string typename, 
      string termname, string from, string to) { 
    // 构建range query 
      querybuilder qb = querybuilders.rangequery(termname).from(from).to(to); 
      searchresponse sresponse = client.preparesearch(indexname) 
          .settypes(typename) 
          // 设置search type 
          // 常用search type用:query_then_fetch 
          // query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
          .setsearchtype(searchtype.query_then_fetch) 
          // 查询的termname和termvalue 
          .setquery(qb) 
          // 设置排序field 
          .addsort(termname, sortorder.desc) 
          // 设置分页 
          .setfrom(0).setsize(60).execute().actionget(); 
      int tshards = sresponse.gettotalshards(); 
      long timecost = sresponse.gettookinmillis(); 
      int sshards = sresponse.getsuccessfulshards(); 
      system.out.println(tshards + "," + timecost + "," + sshards); 
      searchhits hits = sresponse.gethits(); 
      long count = hits.gettotalhits(); 
      searchhit[] hitarray = hits.gethits(); 
      for (int i = 0; i < count; i++) { 
        searchhit hit = hitarray[i]; 
        map<string, object> fields = hit.getsource(); 
        for (string key : fields.keyset()) { 
          system.out.println(key); 
          system.out.println(fields.get(key)); 
        } 
      } 
  } 
  private static void countwithquery(string indexname, string typename, string termname, string termvalue, string sortfield, string highlightfield) { 
    //search result get source 
        countresponse cresponse = client.preparecount(indexname) 
            .settypes(typename) 
            .setquery(querybuilders.termquery(termname, termvalue)) 
            .execute() 
            .actionget(); 
        int tshards = cresponse.gettotalshards(); 
        int sshards = cresponse.getsuccessfulshards(); 
        system.out.println(tshards+","+sshards); 
        long count = cresponse.getcount();    
  } 
  private static void rangesearchwithothersearch(string indexname, string typename, 
      string termname, string min, string max, string termqueryfield) { 
    // 构建range query 
        querybuilder qb = querybuilders.rangequery(termname).from(min).to(max); 
        termquerybuilder tb = querybuilders.termquery(termname, termqueryfield); 
        boolquerybuilder bq = boolquery().must(qb).must(tb); 
        searchresponse sresponse = client.preparesearch(indexname) 
            .settypes(typename) 
            // 设置search type 
            // 常用search type用:query_then_fetch 
            // query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
            .setsearchtype(searchtype.query_then_fetch) 
            // 查询的termname和termvalue 
            .setquery(bq) 
            // 设置排序field 
            .addsort(termname, sortorder.desc) 
            // 设置分页 
            .setfrom(0).setsize(60).execute().actionget(); 
        int tshards = sresponse.gettotalshards(); 
        long timecost = sresponse.gettookinmillis(); 
        int sshards = sresponse.getsuccessfulshards(); 
        system.out.println(tshards + "," + timecost + "," + sshards); 
        searchhits hits = sresponse.gethits(); 
        long count = hits.gettotalhits(); 
        searchhit[] hitarray = hits.gethits(); 
        for (int i = 0; i < count; i++) { 
          searchhit hit = hitarray[i]; 
          map<string, object> fields = hit.getsource(); 
          for (string key : fields.keyset()) { 
            system.out.println(key); 
            system.out.println(fields.get(key)); 
          } 
        } 
  } 
  private static void termrangesearch(string indexname, string typename, 
    string termname, string min, string max, string highlightfield) { 
    querybuilder qb = querybuilders.rangequery(termname).from(min).to(max); 
    searchresponse sresponse = client.preparesearch(indexname) 
        .settypes(typename) 
        // 设置search type 
        // 常用search type用:query_then_fetch 
        // query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
        .setsearchtype(searchtype.query_then_fetch) 
        // 查询的termname和termvalue 
        .setquery(qb) 
        // 设置排序field 
        .addsort(termname, sortorder.desc) 
        //设置高亮field 
        .addhighlightedfield(highlightfield) 
        // 设置分页 
        .setfrom(0).setsize(60).execute().actionget(); 
    int tshards = sresponse.gettotalshards(); 
    long timecost = sresponse.gettookinmillis(); 
    int sshards = sresponse.getsuccessfulshards(); 
    system.out.println(tshards + "," + timecost + "," + sshards); 
    searchhits hits = sresponse.gethits(); 
    long count = hits.gettotalhits(); 
    searchhit[] hitarray = hits.gethits(); 
    for (int i = 0; i < count; i++) { 
      searchhit hit = hitarray[i]; 
      map<string, object> fields = hit.getsource(); 
      for (string key : fields.keyset()) { 
        system.out.println(key); 
        system.out.println(fields.get(key)); 
      } 
    } 
  } 
  private static void sumonefield(string indexname, string typename, string fieldname) { 
    sumbuilder sb = aggregationbuilders.sum("sum").field(fieldname); 
    //search result get source 
    searchresponse sresponse = client.preparesearch(indexname).settypes(typename).addaggregation(sb).execute().actionget(); 
    map<string, aggregation> aggmap = sresponse.getaggregations().asmap(); 
    if(aggmap != null && aggmap.size() > 0) { 
      for(string key : aggmap.keyset()) { 
        sum s = (sum)aggmap.get(key); 
        system.out.println(s.getvalue()); 
      } 
    } 
  } 
  private static void searchwithtermqueryandreturespecifiedfields(string indexname, string typename, string termname,string termvalue, string sortfield, string highlightfield,string... fields) { 
     searchrequestbuilder sb = client.preparesearch(indexname) 
        .settypes(typename) 
        // 设置search type 
        // 常用search type用:query_then_fetch 
        // query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
        .setsearchtype(searchtype.query_then_fetch) 
        // 查询的termname和termvalue 
        .setquery(querybuilders.termquery(termname, termvalue)) 
        // 设置排序field 
        .addsort(sortfield, sortorder.desc) 
        // 设置高亮field 
        .addhighlightedfield(highlightfield) 
        // 设置分页 
        .setfrom(0).setsize(60); 
    for (string field : fields) { 
      sb.addfield(field); 
    } 
    searchresponse sresponse = sb.execute().actionget(); 
    searchhits hits = sresponse.gethits(); 
    long count = hits.gettotalhits(); 
    searchhit[] hitarray = hits.gethits(); 
    for (int i = 0; i < count; i++) { 
      searchhit hit = hitarray[i]; 
      map<string, searchhitfield> fm = hit.getfields(); 
      for (string key : fm.keyset()) { 
        searchhitfield f = fm.get(key); 
        system.out.println(f.getname()); 
        system.out.println(f.getvalue()); 
      } 
    } 
  } 
  private static void searchwithids(string indexname, string typename, string sortfield, string highlightfield, string... ids) { 
    idsquerybuilder qb = querybuilders.idsquery().addids(ids); 
    searchresponse sresponse = client.preparesearch(indexname) 
        .settypes(typename) 
        //设置search type 
        //常用search type用:query_then_fetch 
        //query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
        .setsearchtype(searchtype.query_then_fetch) 
        //查询的termname和termvalue 
        .setquery(qb) 
        //设置排序field 
        .addsort(sortfield, sortorder.desc) 
        //设置高亮field 
        .addhighlightedfield(highlightfield) 
        //设置分页 
        .setfrom(0).setsize(60) 
        .execute() 
        .actionget(); 
    int tshards = sresponse.gettotalshards(); 
    long timecost = sresponse.gettookinmillis(); 
    int sshards = sresponse.getsuccessfulshards(); 
    system.out.println(tshards+","+timecost+","+sshards); 
    searchhits hits = sresponse.gethits(); 
    long count = hits.gettotalhits(); 
    searchhit[] hitarray = hits.gethits(); 
    for(int i = 0; i < count; i++) { 
      searchhit hit = hitarray[i]; 
      map<string, object> fields = hit.getsource(); 
      for(string key : fields.keyset()) { 
        system.out.println(key); 
        system.out.println(fields.get(key)); 
      } 
    } 
  } 
 
  /** 
   * 在index:indexname, type:typename中做通配符查询 
   * @param indexname 
   * @param typename 
   * @param termname 
   * @param termvalue 
   * @param sortfield 
   * @param highlightfield 
   */ 
  private static void wildcardsearch(string indexname, string typename, string termname, string termvalue, string sortfield, string highlightfield) { 
    querybuilder qb = querybuilders.wildcardquery(termname, termvalue); 
    searchresponse sresponse = client.preparesearch(indexname) 
        .settypes(typename) 
        //设置search type 
        //常用search type用:query_then_fetch 
        //query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
        .setsearchtype(searchtype.query_then_fetch) 
        //查询的termname和termvalue 
        .setquery(qb) 
        //设置排序field 
//       .addsort(sortfield, sortorder.desc) 
        //设置高亮field 
//       .addhighlightedfield(highlightfield) 
        //设置分页 
        .setfrom(0).setsize(60) 
        .execute() 
        .actionget(); 
    int tshards = sresponse.gettotalshards(); 
    long timecost = sresponse.gettookinmillis(); 
    int sshards = sresponse.getsuccessfulshards(); 
    system.out.println(tshards+","+timecost+","+sshards); 
    searchhits hits = sresponse.gethits(); 
    long count = hits.gettotalhits(); 
    searchhit[] hitarray = hits.gethits(); 
    for(int i = 0; i < count; i++) { 
      searchhit hit = hitarray[i]; 
      map<string, object> fields = hit.getsource(); 
      for(string key : fields.keyset()) { 
        system.out.println(key); 
        system.out.println(fields.get(key)); 
      } 
    } 
  } 
 
  /** 
   * 在index:indexname, type:typename中做模糊查询 
   * @param indexname 
   * @param typename 
   * @param termname 
   * @param termvalue 
   * @param sortfield 
   * @param highlightfield 
   */ 
  private static void fuzzysearch(string indexname, string typename, string termname, string termvalue, string sortfield, string highlightfield) { 
     querybuilder qb = querybuilders.fuzzyquery(termname, termvalue); 
    searchresponse sresponse = client.preparesearch(indexname) 
        .settypes(typename) 
        //设置search type 
        //常用search type用:query_then_fetch 
        //query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
        .setsearchtype(searchtype.query_then_fetch) 
        //查询的termname和termvalue 
        .setquery(qb) 
        //设置排序field 
        .addsort(sortfield, sortorder.desc) 
        //设置高亮field 
        .addhighlightedfield(highlightfield) 
        //设置分页 
        .setfrom(0).setsize(60) 
        .execute() 
        .actionget(); 
    int tshards = sresponse.gettotalshards(); 
    long timecost = sresponse.gettookinmillis(); 
    int sshards = sresponse.getsuccessfulshards(); 
    system.out.println(tshards+","+timecost+","+sshards); 
    searchhits hits = sresponse.gethits(); 
    long count = hits.gettotalhits(); 
    searchhit[] hitarray = hits.gethits(); 
    for(int i = 0; i < count; i++) { 
      searchhit hit = hitarray[i]; 
      map<string, object> fields = hit.getsource(); 
      for(string key : fields.keyset()) { 
        system.out.println(key); 
        system.out.println(fields.get(key)); 
      } 
    } 
  } 
  /** 
   * 在index:indexname, type:typename中做区间查询 
   * @param indexname 
   * @param typename 
   * @param termname 
   * @param min 
   * @param max 
   * @param highlightfield 
   */ 
  private static void numericrangesearch(string indexname, string typename, 
      string termname, double min, double max, string highlightfield) { 
    // 构建range query 
    querybuilder qb = querybuilders.rangequery(termname).from(min).to(max); 
    searchresponse sresponse = client.preparesearch(indexname) 
        .settypes(typename) 
        // 设置search type 
        // 常用search type用:query_then_fetch 
        // query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
        .setsearchtype(searchtype.query_then_fetch) 
        // 查询的termname和termvalue 
        .setquery(qb) 
        // 设置排序field 
        .addsort(termname, sortorder.desc) 
        //设置高亮field 
        .addhighlightedfield(highlightfield) 
        // 设置分页 
        .setfrom(0).setsize(60).execute().actionget(); 
    int tshards = sresponse.gettotalshards(); 
    long timecost = sresponse.gettookinmillis(); 
    int sshards = sresponse.getsuccessfulshards(); 
    system.out.println(tshards + "," + timecost + "," + sshards); 
    searchhits hits = sresponse.gethits(); 
    long count = hits.gettotalhits(); 
    searchhit[] hitarray = hits.gethits(); 
    for (int i = 0; i < count; i++) { 
      searchhit hit = hitarray[i]; 
      map<string, object> fields = hit.getsource(); 
      for (string key : fields.keyset()) { 
        system.out.println(key); 
        system.out.println(fields.get(key)); 
      } 
    } 
  } 
  /** 
   * 在索引indexname, type为typename中查找两个term:term1(termname1, termvalue1)和term2(termname2, termvalue2) 
   * @param indexname 
   * @param typename 
   * @param termname1 
   * @param termvalue1 
   * @param termname2 
   * @param termvalue2 
   * @param sortfield 
   * @param highlightfield 
   */ 
  private static void searchwithbooleanquery(string indexname, string typename, string termname1, string termvalue1,  
       string termname2, string termvalue2, string sortfield, string highlightfield) { 
    //构建boolean query 
    boolquerybuilder bq = boolquery().must(termquery(termname1, termvalue1)).must(termquery(termname2, termvalue2));   
    searchresponse sresponse = client.preparesearch(indexname) 
        .settypes(typename) 
        //设置search type 
        //常用search type用:query_then_fetch 
        //query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
        .setsearchtype(searchtype.query_then_fetch) 
        //查询的termname和termvalue 
        .setquery(bq) 
        //设置排序field 
        .addsort(sortfield, sortorder.desc) 
        //设置高亮field 
        .addhighlightedfield(highlightfield) 
        //设置分页 
        .setfrom(0).setsize(60) 
        .execute() 
        .actionget(); 
    int tshards = sresponse.gettotalshards(); 
    long timecost = sresponse.gettookinmillis(); 
    int sshards = sresponse.getsuccessfulshards(); 
    system.out.println(tshards+","+timecost+","+sshards); 
    searchhits hits = sresponse.gethits(); 
    long count = hits.gettotalhits(); 
    searchhit[] hitarray = hits.gethits(); 
    for(int i = 0; i < count; i++) { 
      searchhit hit = hitarray[i]; 
      map<string, object> fields = hit.getsource(); 
      for(string key : fields.keyset()) { 
        system.out.println(key); 
        system.out.println(fields.get(key)); 
      } 
    } 
  } 
  /** 
   * 在索引indexname, type为typename中查找term(termname, termvalue) 
   * @param indexname 
   * @param typename 
   * @param termname 
   * @param termvalue 
   * @param sortfield 
   * @param highlightfield 
   */ 
  private static void searchwithtermquery(string indexname, string typename, string termname, string termvalue, string sortfield, string highlightfield) { 
    searchresponse sresponse = client.preparesearch(indexname) 
        .settypes(typename) 
        //设置search type 
        //常用search type用:query_then_fetch 
        //query_then_fetch是先查到相关结构,然后聚合不同node上的结果后排序 
        .setsearchtype(searchtype.query_then_fetch) 
        //查询的termname和termvalue 
        .setquery(querybuilders.termquery(termname, termvalue)) 
        //设置排序field 
//       .addsort(sortfield, sortorder.desc) 
        //设置高亮field 
//       .addhighlightedfield(highlightfield) 
        //设置分页 
        .setfrom(0).setsize(60) 
        .execute() 
        .actionget(); 
    int tshards = sresponse.gettotalshards(); 
    long timecost = sresponse.gettookinmillis(); 
    int sshards = sresponse.getsuccessfulshards(); 
    searchhits hits = sresponse.gethits(); 
    long count = hits.gettotalhits(); 
    searchhit[] hitarray = hits.gethits(); 
    for(int i = 0; i < count; i++) { 
      system.out.println("=================================="); 
      searchhit hit = hitarray[i]; 
      map<string, object> fields = hit.getsource(); 
      for(string key : fields.keyset()) { 
        system.out.println(key); 
        system.out.println(fields.get(key)); 
      } 
    } 
  } 
  /** 
   * 用java的map构建document 
   */ 
  private static void indexwithmap(string indexname, string typename) { 
    map<string, object> json = new hashmap<string, object>(); 
    //设置document的field 
    json.put("user","kimchy2"); 
    json.put("postdate",new date()); 
    json.put("price",6.4); 
    json.put("message","elasticsearch"); 
    json.put("tid","10002"); 
    json.put("endtime","2015-08-25 09:00:00"); 
    //指定索引名称,type名称和documentid(documentid可选,不设置则系统自动生成)创建document 
    indexresponse response = client.prepareindex(indexname, typename, "2").setsource(json).execute().actionget(); 
    //response中返回索引名称,type名称,doc的id和版本信息 
    string index = response.getindex(); 
    string type = response.gettype(); 
    string id = response.getid(); 
    long version = response.getversion(); 
    boolean created = response.iscreated(); 
    system.out.println(index+","+type+","+id+","+version+","+created); 
  } 
 
  /** 
   * 用java字符串创建document 
   */ 
  private static void indexwithstr(string indexname, string typename) { 
    //手工构建json字符串 
    //该document包含user, postdata和message三个field 
    string json = "{" + "\"user\":\"kimchy\"," + "\"postdate\":\"2013-01-30\"," + "\"price\":\"6.3\"," + "\"tid\":\"10001\"," + "}"; 
    //指定索引名称,type名称和documentid(documentid可选,不设置则系统自动生成)创建document 
    indexresponse response = client.prepareindex(indexname, typename, "1") 
        .setsource(json) 
        .execute() 
        .actionget(); 
    //response中返回索引名称,type名称,doc的id和版本信息 
    string index = response.getindex(); 
    string type = response.gettype(); 
    string id = response.getid(); 
    long version = response.getversion(); 
    boolean created = response.iscreated(); 
    system.out.println(index+","+type+","+id+","+version+","+created); 
  } 
   
  private static void deletedocwithid(string indexname, string typename, string docid) { 
    deleteresponse dresponse = client.preparedelete(indexname, typename, docid).execute().actionget(); 
    string index = dresponse.getindex(); 
    string type = dresponse.gettype(); 
    string id = dresponse.getid(); 
    long version = dresponse.getversion(); 
    system.out.println(index+","+type+","+id+","+version); 
  } 
   
  /** 
   * 创建索引 
   * 注意:在生产环节中通知es集群的owner去创建index 
   * @param client 
   * @param indexname 
   * @param documenttype 
   * @throws ioexception 
   */ 
  private static void createindex(string indexname, string documenttype) throws ioexception { 
    final indicesexistsresponse ires = client.admin().indices().prepareexists(indexname).execute().actionget(); 
    if (ires.isexists()) { 
      client.admin().indices().preparedelete(indexname).execute().actionget(); 
    } 
    client.admin().indices().preparecreate(indexname).setsettings(settings.settingsbuilder().put("number_of_shards", 1).put("number_of_replicas", "0")).execute().actionget(); 
    xcontentbuilder mapping = jsonbuilder() 
        .startobject() 
           .startobject(documenttype) 
//           .startobject("_routing").field("path","tid").field("required", "true").endobject() 
           .startobject("_source").field("enabled", "true").endobject() 
           .startobject("_all").field("enabled", "false").endobject() 
             .startobject("properties") 
               .startobject("user") 
                 .field("store", true) 
                 .field("type", "string") 
                 .field("index", "not_analyzed") 
                .endobject() 
                .startobject("message") 
                 .field("store", true) 
                 .field("type","string") 
                 .field("index", "analyzed") 
                 .field("analyzer", "standard") 
                .endobject() 
                .startobject("price") 
                 .field("store", true) 
                 .field("type", "float") 
                .endobject() 
                .startobject("nv1") 
                 .field("store", true) 
                 .field("type", "integer") 
                 .field("index", "no") 
                 .field("null_value", 0) 
                .endobject() 
                .startobject("nv2") 
                 .field("store", true) 
                 .field("type", "integer") 
                 .field("index", "not_analyzed") 
                 .field("null_value", 10) 
                .endobject() 
                .startobject("tid") 
                 .field("store", true) 
                 .field("type", "string") 
                 .field("index", "not_analyzed") 
                .endobject() 
                .startobject("endtime") 
                 .field("type", "date") 
                 .field("store", true) 
                 .field("index", "not_analyzed") 
                 .field("format", "yyyy-mm-dd hh:mm:ss||yyyy-mm-dd't'hh:mm:ss.sssz") 
                .endobject() 
                .startobject("date") 
                 .field("type", "date") 
                .endobject() 
             .endobject() 
           .endobject() 
          .endobject(); 
    client.admin().indices() 
        .prepareputmapping(indexname) 
        .settype(documenttype) 
        .setsource(mapping) 
        .execute().actionget(); 
  } 
} 

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