Elasticsearch系列(五)----JAVA客户端之TransportClient操作详解

Elasticsearch JAVA操作有三种客户端:

 

1、TransportClient

2、JestClient

3、RestClient

 

还有种是2.3中有的NodeClient,在5.5.1中好像没有了。还有种是spring-data-elasticsearch,这里先以TransportClient来讲解CRUD,所用环境为:

 

JDK1.8

ES5.5.1

TransportClient5.5.1

 

 

POM.XML文件如下:

 

[html]  view plain  copy
 
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.   <modelVersion>4.0.0modelVersion>  
  4.   <groupId>com.fendogroupId>  
  5.   <artifactId>TransportClientartifactId>  
  6.   <packaging>warpackaging>  
  7.   <version>0.0.1-SNAPSHOTversion>  
  8.   <name>TransportClient Maven Webappname>  
  9.   <url>http://maven.apache.orgurl>  
  10.     
  11.      
  12.     <properties>  
  13.         <spring.version>4.2.7.RELEASEspring.version>  
  14.     properties>  
  15.     
  16.   <dependencies>  
  17.   
  18.     <dependency>  
  19.         <groupId>junitgroupId>  
  20.         <artifactId>junitartifactId>  
  21.         <version>4.12version>  
  22.     dependency>  
  23.   
  24.       
  25.     <dependency>  
  26.         <groupId>javax.servletgroupId>  
  27.         <artifactId>javax.servlet-apiartifactId>  
  28.         <version>3.1.0version>  
  29.         <scope>providedscope>  
  30.     dependency>  
  31.     <dependency>  
  32.             <groupId>org.hibernategroupId>  
  33.             <artifactId>hibernate-validatorartifactId>  
  34.             <version>4.2.0.Finalversion>  
  35.      dependency>  
  36.           
  37.           
  38.         <dependency>  
  39.             <groupId>mysqlgroupId>  
  40.             <artifactId>mysql-connector-javaartifactId>  
  41.             <version>5.1.38version>  
  42.         dependency>  
  43.   
  44.           
  45.           
  46.       
  47.           
  48.         <dependency>  
  49.             <groupId>org.mybatisgroupId>  
  50.             <artifactId>mybatisartifactId>  
  51.             <version>3.2.5version>  
  52.         dependency>  
  53.           
  54.   
  55.           
  56.         <dependency>  
  57.             <groupId>log4jgroupId>  
  58.             <artifactId>log4jartifactId>  
  59.             <version>1.2.17version>  
  60.         dependency>  
  61.   
  62.         <dependency>  
  63.             <groupId>org.apache.logging.log4jgroupId>  
  64.             <artifactId>log4j-1.2-apiartifactId>  
  65.             <version>2.7version>  
  66.         dependency>  
  67.       
  68.         <dependency>  
  69.             <groupId>org.apache.logging.log4jgroupId>  
  70.             <artifactId>log4j-slf4j-implartifactId>  
  71.             <version>2.7version>  
  72.         dependency>  
  73.           
  74.         <dependency>  
  75.             <groupId>org.apache.logging.log4jgroupId>  
  76.             <artifactId>log4j-coreartifactId>  
  77.             <version>2.7version>  
  78.         dependency>  
  79.           
  80.           
  81.   
  82.   
  83.           
  84.         <dependency>  
  85.             <groupId>com.mchangegroupId>  
  86.             <artifactId>c3p0artifactId>  
  87.             <version>0.9.2.1version>  
  88.         dependency>  
  89.           
  90.   
  91.           
  92.         <dependency>  
  93.             <groupId>org.mybatisgroupId>  
  94.             <artifactId>mybatis-springartifactId>  
  95.             <version>1.3.0version>  
  96.         dependency>  
  97.       
  98.                   
  99.         <dependency>    
  100.             <groupId>javax.servletgroupId>    
  101.             <artifactId>jstlartifactId>    
  102.             <version>1.2version>    
  103.         dependency>    
  104.             
  105.           
  106.         <dependency>  
  107.             <groupId>com.fasterxml.jackson.coregroupId>  
  108.             <artifactId>jackson-coreartifactId>  
  109.             <version>2.9.0version>  
  110.         dependency>  
  111.         <dependency>  
  112.             <groupId>com.fasterxml.jackson.coregroupId>  
  113.             <artifactId>jackson-databindartifactId>  
  114.             <version>2.9.0version>  
  115.         dependency>  
  116.         <dependency>  
  117.             <groupId>com.fasterxml.jackson.coregroupId>  
  118.             <artifactId>jackson-annotationsartifactId>  
  119.             <version>2.9.0version>  
  120.         dependency>  
  121.           
  122.   
  123.   
  124.     <dependency>  
  125.         <groupId>com.alibabagroupId>  
  126.         <artifactId>fastjsonartifactId>  
  127.         <version>1.2.12version>  
  128.     dependency>  
  129.               
  130.               
  131.               
  132.       
  133.     <dependency>  
  134.             <groupId>org.elasticsearchgroupId>  
  135.             <artifactId>elasticsearchartifactId>  
  136.             <version>5.5.1version>  
  137.         dependency>  
  138.           
  139.           
  140.      
  141.     <dependency>  
  142.             <groupId>org.elasticsearch.clientgroupId>  
  143.             <artifactId>transportartifactId>  
  144.             <version>5.5.1version>  
  145.         dependency>  
  146.   
  147.       
  148.     <dependency>  
  149.             <groupId>org.elasticsearchgroupId>  
  150.             <artifactId>elasticsearch-analysis-ikartifactId>  
  151.             <version>5.5.1version>  
  152.         dependency>  
  153.           
  154.   
  155.           
  156.   dependencies>  
  157.     
  158.   <repositories>  
  159.         <repository>  
  160.             <id>spring-libs-snapshotid>  
  161.             <name>Spring Snapshot Repositoryname>  
  162.             <url>http://repo.spring.io/libs-snapshoturl>  
  163.         repository>  
  164.         <repository>  
  165.             <id>elasticsearch-releasesid>  
  166.             <url>https://artifacts.elastic.co/mavenurl>  
  167.             <releases>  
  168.                 <enabled>trueenabled>  
  169.             releases>  
  170.             <snapshots>  
  171.                 <enabled>falseenabled>  
  172.             snapshots>  
  173.         repository>  
  174.     repositories>  
  175.     
  176.   <build>  
  177.     <finalName>TransportClientfinalName>  
  178.          <plugins>  
  179.             <plugin>  
  180.                 <groupId>org.apache.maven.pluginsgroupId>  
  181.                 <artifactId>maven-compiler-pluginartifactId>  
  182.                 <configuration>  
  183.                     <source>1.8source>  
  184.                     <target>1.8target>  
  185.                 configuration>  
  186.             plugin>  
  187.         plugins>  
  188.   build>  
  189. project>  

 

 

详细代码如下:

 

[html]  view plain  copy
 
  1. package com.fendo.temp;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.File;  
  6. import java.io.FileReader;  
  7. import java.io.FileWriter;  
  8. import java.io.IOException;  
  9. import java.io.StringReader;  
  10. import java.net.InetAddress;  
  11. import java.net.UnknownHostException;  
  12. import java.text.SimpleDateFormat;  
  13. import java.util.ArrayList;  
  14. import java.util.Collection;  
  15. import java.util.Date;  
  16. import java.util.HashMap;  
  17. import java.util.HashSet;  
  18. import java.util.List;  
  19. import java.util.Map;  
  20. import java.util.Set;  
  21. import java.util.concurrent.ExecutionException;  
  22.   
  23. import org.elasticsearch.action.get.GetResponse;  
  24. import org.elasticsearch.action.get.MultiGetItemResponse;  
  25. import org.elasticsearch.action.get.MultiGetResponse;  
  26. import org.elasticsearch.index.query.MatchQueryBuilder;  
  27. import org.elasticsearch.action.ActionFuture;  
  28. import org.elasticsearch.action.admin.indices.analyze.AnalyzeRequest;  
  29. import org.elasticsearch.action.admin.indices.analyze.AnalyzeResponse;  
  30. import org.elasticsearch.script.Script;  
  31. import org.elasticsearch.script.ScriptType;  
  32. import org.elasticsearch.index.query.MultiMatchQueryBuilder;  
  33. import org.elasticsearch.index.query.MatchPhrasePrefixQueryBuilder;  
  34. import org.elasticsearch.index.query.MatchPhraseQueryBuilder;  
  35. import org.elasticsearch.action.search.MultiSearchResponse;  
  36. import org.apache.lucene.analysis.TokenStream;  
  37. import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;  
  38. import org.apache.lucene.search.join.ScoreMode;  
  39. import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;  
  40. import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;  
  41. import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;  
  42. import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;  
  43. import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;  
  44. import org.elasticsearch.action.bulk.BulkRequestBuilder;  
  45. import org.elasticsearch.action.bulk.BulkResponse;  
  46. import org.elasticsearch.action.delete.DeleteResponse;  
  47. import org.elasticsearch.action.index.IndexRequest;  
  48. import org.elasticsearch.action.index.IndexRequestBuilder;  
  49. import org.elasticsearch.action.index.IndexResponse;  
  50. import org.elasticsearch.action.search.SearchRequestBuilder;  
  51. import org.elasticsearch.action.search.SearchResponse;  
  52. import org.elasticsearch.action.search.SearchType;  
  53. import org.elasticsearch.action.update.UpdateRequest;  
  54. import org.elasticsearch.action.update.UpdateResponse;  
  55. import org.elasticsearch.client.Response;  
  56. import org.elasticsearch.client.transport.TransportClient;  
  57. import org.elasticsearch.common.settings.Settings;  
  58. import org.elasticsearch.common.transport.InetSocketTransportAddress;  
  59. import org.elasticsearch.common.unit.Fuzziness;  
  60. import org.elasticsearch.common.unit.TimeValue;  
  61. import org.elasticsearch.common.xcontent.XContentBuilder;  
  62. import org.elasticsearch.common.xcontent.XContentFactory;  
  63. import org.elasticsearch.index.query.BoolQueryBuilder;  
  64. import org.elasticsearch.index.query.QueryBuilder;  
  65. import org.elasticsearch.index.query.QueryBuilders;  
  66. import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;  
  67. import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;  
  68. import org.elasticsearch.search.SearchHit;  
  69. import org.elasticsearch.search.SearchHits;  
  70. import org.elasticsearch.search.aggregations.AggregationBuilder;  
  71. import org.elasticsearch.search.aggregations.AggregationBuilders;  
  72. import org.elasticsearch.search.aggregations.Aggregations;  
  73. import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;  
  74. import org.elasticsearch.search.aggregations.bucket.terms.Terms;  
  75. import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;  
  76. import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;  
  77. import org.elasticsearch.search.aggregations.metrics.sum.Sum;  
  78. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;  
  79. import org.elasticsearch.search.sort.FieldSortBuilder;  
  80. import org.elasticsearch.search.sort.SortOrder;  
  81. import org.elasticsearch.transport.client.PreBuiltTransportClient;  
  82. import org.elasticsearch.action.bulk.BackoffPolicy;  
  83. import org.elasticsearch.action.bulk.BulkItemResponse;  
  84. import org.elasticsearch.action.bulk.BulkProcessor;  
  85. import org.elasticsearch.action.bulk.BulkRequest;  
  86. import org.elasticsearch.action.bulk.BulkResponse;  
  87. import org.elasticsearch.common.unit.ByteSizeUnit;  
  88. import org.elasticsearch.common.unit.ByteSizeValue;  
  89. import org.elasticsearch.common.unit.TimeValue;  
  90.   
  91. import org.wltea.analyzer.lucene.IKAnalyzer;  
  92. import org.joda.time.DateTime;  
  93. import org.junit.Before;  
  94. import org.junit.Test;  
  95.   
  96. import com.alibaba.fastjson.JSONObject;  
  97.   
  98.   
  99.   
  100. public class TransportClientTest {  
  101.   
  102.       
  103.     private TransportClient client;  
  104.       
  105.       
  106.     private final static String article="article";  
  107.     private final static String content="content";  
  108.       
  109.     @Before  
  110.     public void getClient() throws Exception{  
  111.         //设置集群名称  
  112.         Settings settings = Settings.builder().put("cluster.name", "my-application").build();// 集群名  
  113.         //创建client  
  114.         client  = new PreBuiltTransportClient(settings)  
  115.                 .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));  
  116.     }  
  117.       
  118.     /**  
  119.      * -----------------------------------------增(创建索引,增加映射,新增文档)  
  120.      */  
  121.       
  122.       
  123.     /**  
  124.      * 创建索引的四种方法  
  125.      */  
  126.       
  127.     @Test  
  128.     public void JSON(){  
  129.         String json = "{" +  
  130.                 "\"id\":\"kimchy\"," +  
  131.                 "\"postDate\":\"2013-01-30\"," +  
  132.                 "\"message\":\"trying out Elasticsearch\"" +  
  133.             "}";  
  134.   
  135.     }  
  136.       
  137.     /**  
  138.      * 创建索引并添加映射  
  139.      * @throws IOException   
  140.      */  
  141.     @Test  
  142.     public void CreateIndexAndMapping() throws Exception{  
  143.                   
  144.         CreateIndexRequestBuilder  cib=client.admin().indices().prepareCreate(article);  
  145.             XContentBuilder mapping = XContentFactory.jsonBuilder()  
  146.                     .startObject()  
  147.                         .startObject("properties") //设置之定义字段  
  148.                           .startObject("author")  
  149.                             .field("type","string") //设置数据类型  
  150.                           .endObject()  
  151.                           .startObject("title")  
  152.                              .field("type","string")  
  153.                           .endObject()  
  154.                           .startObject("content")  
  155.                              .field("type","string")  
  156.                           .endObject()  
  157.                           .startObject("price")  
  158.                              .field("type","string")  
  159.                           .endObject()  
  160.                           .startObject("view")  
  161.                              .field("type","string")  
  162.                           .endObject()  
  163.                           .startObject("tag")  
  164.                              .field("type","string")  
  165.                           .endObject()  
  166.                           .startObject("date")  
  167.                              .field("type","date")  //设置Date类型  
  168.                              .field("format","yyyy-MM-dd HH:mm:ss") //设置Date的格式  
  169.                           .endObject()  
  170.                       .endObject()  
  171.                     .endObject();  
  172.             cib.addMapping(content, mapping);  
  173.               
  174.             CreateIndexResponse res=cib.execute().actionGet();  
  175.               
  176.             System.out.println("----------添加映射成功----------");  
  177.     }  
  178.       
  179.     /**  
  180.      *  创建索引并添加文档  
  181.      * @throws Exception  
  182.      */  
  183.     @Test  
  184.     public void addIndexAndDocument() throws Exception{  
  185.                   
  186.         Date time = new Date();  
  187.   
  188.         IndexResponse response = client.prepareIndex(article, content)  
  189.         .setSource(XContentFactory.jsonBuilder().startObject()  
  190.         .field("id","447")  
  191.         .field("author","fendo")  
  192.         .field("title","192.138.1.2")  
  193.         .field("content","这是JAVA有关的书籍")  
  194.         .field("price","20")  
  195.         .field("view","100")  
  196.         .field("tag","a,b,c,d,e,f")  
  197.         .field("date",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time))  
  198.         .endObject())  
  199.         .get();  
  200.         System.out.println("添加索引成功,版本号:"+response.getVersion());  
  201.     }  
  202.       
  203.   
  204.     /**  
  205.      * -------------------------------------Bulk---------------------------------  
  206.      */  
  207.       
  208.       
  209.     /**  
  210.      * bulkRequest  
  211.      * @throws Exception  
  212.      */  
  213.     @Test  
  214.     public void bulkRequest() throws Exception {  
  215.         BulkRequestBuilder bulkRequest = client.prepareBulk();  
  216.   
  217.         Date time = new Date();  
  218.           
  219.         // either use client#prepare, or use Requests# to directly build index/delete requests  
  220.         bulkRequest.add(client.prepareIndex(article, content, "199")  
  221.                 .setSource(XContentFactory.jsonBuilder()  
  222.                         .startObject()  
  223.                         .field("id","199")  
  224.                         .field("author","fendo")  
  225.                         .field("title","BULK")  
  226.                         .field("content","这是BULK有关的书籍")  
  227.                         .field("price","40")  
  228.                         .field("view","300")  
  229.                         .field("tag","a,b,c")  
  230.                         .field("date",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time))  
  231.                         .endObject()  
  232.                 )  
  233.         );  
  234.   
  235.         bulkRequest.add(client.prepareIndex(article,content, "101")  
  236.                 .setSource(XContentFactory.jsonBuilder()  
  237.                         .startObject()  
  238.                         .field("id","101")  
  239.                         .field("author","fendo")  
  240.                         .field("title","ACKSE")  
  241.                         .field("content","这是ACKSE有关的书籍")  
  242.                         .field("price","50")  
  243.                         .field("view","200")  
  244.                         .field("tag","a,b,c")  
  245.                         .field("date",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time))  
  246.                         .endObject()  
  247.                 )  
  248.         );  
  249.   
  250.         BulkResponse bulkResponse = bulkRequest.get();  
  251.         if (bulkResponse.hasFailures()) {  
  252.             // process failures by iterating through each bulk response item  
  253.             //System.out.println(bulkResponse.getTook());  
  254.         }  
  255.     }  
  256.       
  257.       
  258.       
  259.     /**设置自动提交文档  
  260.      * BulkProcessor  
  261.      * @throws Exception  
  262.      */  
  263.     @Test  
  264.     public void autoBulkProcessor() throws Exception {  
  265.           
  266.         BulkProcessor bulkProcessor = BulkProcessor.builder(client,  
  267.         new BulkProcessor.Listener() {  
  268.             @Override  
  269.             public void beforeBulk(long executionId,  
  270.                                    BulkRequest request) {  
  271.                 //提交前调用  
  272.       
  273.             }  
  274.       
  275.             @Override  
  276.             public void afterBulk(long executionId,  
  277.                                   BulkRequest request,  
  278.                                   BulkResponse response) {  
  279.                 //提交结束后调用(无论成功或失败)  
  280.                 System.out.println( "提交" + response.getItems().length + "个文档,用时"+ response.getTookInMillis() + "MS" + (response.hasFailures() ? " 有文档提交失败!" : ""));  
  281.       
  282.             }  
  283.       
  284.             @Override  
  285.             public void afterBulk(long executionId,  
  286.                                   BulkRequest request,  
  287.                                   Throwable failure) {  
  288.                  //提交结束且失败时调用  
  289.                  System.out.println( " 有文档提交失败!after failure=" + failure);  
  290.       
  291.             }  
  292.         })  
  293.         //当请求超过10000个(default=1000)或者总大小超过1GB(default=5MB)时,触发批量提交动作。  
  294.         .setBulkActions(10000)//文档数量达到1000时提交  
  295.         .setBulkSize(new ByteSizeValue(5, ByteSizeUnit.MB))//总文档体积达到5MB时提交   
  296.         .setFlushInterval(TimeValue.timeValueSeconds(5))//每5S提交一次(无论文档数量、体积是否达到阈值)  
  297.         .setConcurrentRequests(1)//加1后为可并行的提交请求数,即设为0代表只可1个请求并行,设为1为2个并行  
  298.         .setBackoffPolicy(  
  299.                 BackoffPolicy.exponentialBackoff(TimeValue.timeValueMillis(100), 3))  
  300.         .build();  
  301.           
  302.         //提交单个  
  303.         //String json = "{\"id\":\"66\",\"author\":\"ckse\",\"title\":\"windows编程\",\"content\":\"windows 32 API编程\",\"price\":\"99\",\"view\":\"222\",\"date\":\"2017-08-01 17:21:18\"}";  
  304.         //bulkProcessor.add(new IndexRequest("设置的index name", "设置的type name","要插入的文档的ID").source(json));//添加文档,以便自动提交  
  305.          for(int i=0;i<80080;i++){  
  306.               //业务对象  
  307.               String json = "{\"id\":\""+i+"\",\"author\":\"ckse\",\"title\":\"windows编程\",\"content\":\"windows 32 API编程\",\"price\":\"99\",\"view\":\"222\",\"date\":\"2017-08-01 17:21:18\"}";  
  308.               System.out.println(json);  
  309.               bulkProcessor.add(new IndexRequest("article", "content",""+i).source(json));//添加文档,以便自动提交  
  310.   
  311.          }  
  312.            
  313.          System.out.println("创建成功!!!");  
  314.   
  315.     }  
  316.       
  317.     //手动 批量更新  
  318.     @Test  
  319.     public void multipleBulkProcessor() throws Exception {  
  320.   
  321.          BulkRequestBuilder bulkRequest = client.prepareBulk();  
  322.          for(int i=500;i<1000;i++){  
  323.               //业务对象  
  324.               String jsons = "{\"id\":\""+i+"\",\"author\":\"ckse\",\"title\":\"windows编程\",\"content\":\"windows 32 API编程\",\"price\":\"99\",\"view\":\"222\",\"date\":\"2017-08-01 17:21:18\"}";  
  325.               IndexRequestBuilder indexRequest = client.prepareIndex("article", "content")  
  326.                       //指定不重复的ID  
  327.                       .setSource(jsons).setId(String.valueOf(i));  
  328.               //添加到builder中  
  329.               bulkRequest.add(indexRequest);  
  330.          }  
  331.          BulkResponse bulkResponse = bulkRequest.execute().actionGet();  
  332.          if (bulkResponse.hasFailures()) {  
  333.               // process failures by iterating through each bulk response item  
  334.               System.out.println(bulkResponse.buildFailureMessage());  
  335.          }  
  336.          System.out.println("创建成功!!!");   
  337.     }  
  338.       
  339.     /**  
  340.      * 使用Bulk批量添加导入数据  
  341.      *   
  342.      */  
  343.     @Test  
  344.     public void ImportBulk(){  
  345.         FileReader fr = null;  
  346.         BufferedReader bfr = null;  
  347.         String line=null;  
  348.         try {  
  349.                 File file = new File("F:\\Source\\Elasticsearch\\TransportClient\\src\\main\\resources\\bulk.txt");  
  350.                 fr=new FileReader(file);  
  351.                 bfr=new BufferedReader(fr);  
  352.                 BulkRequestBuilder bulkRequest=client.prepareBulk();  
  353.                 int count=0;  
  354.                 while((line=bfr.readLine())!=null){  
  355.                     bulkRequest.add(client.prepareIndex(article,content).setSource(line));  
  356.                     if (count%10==0) {  
  357.                         bulkRequest.execute().actionGet();  
  358.                     }  
  359.                     count++;  
  360.                 }  
  361.                 bulkRequest.execute().actionGet();  
  362.                 System.out.println("导入成功!!!");  
  363.         } catch (Exception e) {  
  364.                 e.printStackTrace();  
  365.         }finally {  
  366.             try {  
  367.                 bfr.close();  
  368.                 fr.close();  
  369.             } catch (IOException e) {  
  370.                 e.printStackTrace();  
  371.             }  
  372.         }  
  373.     }  
  374.       
  375.       
  376.     /**  
  377.      * 使用Bulk批量导出数据  
  378.      * @throws ExecutionException   
  379.      * @throws InterruptedException   
  380.      */  
  381.     @Test  
  382.     public void ExportBulk() throws Exception{  
  383.           
  384.       
  385.         QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();  
  386.         SearchResponse response = client.prepareSearch("article").setQuery(queryBuilder).get();  
  387.           
  388.         SearchHits resultHits = response.getHits();  
  389.   
  390.         System.out.println(JSONObject.toJSON(resultHits));  
  391.           
  392.         FileWriter fw=null;  
  393.         BufferedWriter bfw =null;  
  394.         try {  
  395.             File file = new File("F:\\Source\\Elasticsearch\\TransportClient\\src\\main\\resources\\bulk.txt");  
  396.             fw = new FileWriter(article);  
  397.             bfw = new BufferedWriter(fw);  
  398.   
  399.             if (resultHits.getHits().length == 0) {  
  400.                 System.out.println("查到0条数据!");  
  401.   
  402.             } else {  
  403.                 for (int i = 0; i resultHits.getHits().length; i++) {  
  404.                     String jsonStr = resultHits.getHits()[i]  
  405.                             .getSourceAsString();  
  406.                     System.out.println(jsonStr);  
  407.                     bfw.write(jsonStr);  
  408.                     bfw.write("\n");  
  409.                 }  
  410.             }  
  411.         } catch (Exception e) {  
  412.            e.printStackTrace();  
  413.         }finally {  
  414.             try {  
  415.                 bfw.close();  
  416.                 fw.close();  
  417.             } catch (IOException e) {  
  418.                 e.printStackTrace();  
  419.             }  
  420.         }  
  421.     }  
  422.       
  423.       
  424.     /**  
  425.      * -----------------------------------------删(删除索引,删除文档)  
  426.      */  
  427.       
  428.       
  429.     /**  
  430.      * 删除整个索引库  
  431.      */  
  432.     @Test  
  433.     public void deleteAllIndex(){  
  434.           
  435.         String indexName="article";  
  436.           
  437.         /**  
  438.          * 两种方式如下:  
  439.          */  
  440.           
  441.         //1)  
  442.         //可以根据DeleteIndexResponse对象的isAcknowledged()方法判断删除是否成功,返回值为boolean类型.  
  443.         DeleteIndexResponse dResponse = client.admin().indices().prepareDelete(indexName)  
  444.                 .execute().actionGet();  
  445.         System.out.println("是否删除成功:"+dResponse.isAcknowledged());  
  446.   
  447.           
  448.         //2)  
  449.         //如果传人的indexName不存在会出现异常.可以先判断索引是否存在:  
  450.         IndicesExistsRequest inExistsRequest = new IndicesExistsRequest(indexName);  
  451.           
  452.         IndicesExistsResponse inExistsResponse = client.admin().indices()  
  453.                 .exists(inExistsRequest).actionGet();  
  454.           
  455.         //根据IndicesExistsResponse对象的isExists()方法的boolean返回值可以判断索引库是否存在.  
  456.         System.out.println("是否删除成功:"+inExistsResponse.isExists());  
  457.     }  
  458.       
  459.   
  460.     /**  
  461.      * 通过ID删除  
  462.      */  
  463.     @Test  
  464.     public void deleteById(){  
  465.         DeleteResponse dResponse = client.prepareDelete(article,content, "AV49wyfCWmWw7AxKFxeb").execute().actionGet();  
  466.         if ("OK".equals(dResponse.status())) {  
  467.             System.out.println("删除成功");  
  468.         } else {  
  469.             System.out.println("删除失败");  
  470.         }  
  471.     }  
  472.       
  473.       
  474.     /**  
  475.      * 通过Query delete删除  
  476.      */  
  477.     @Test  
  478.     public void queryDelete() {  
  479. //         String guid="AV49wyfCWmWw7AxKFxeb";  
  480. //         String author="kkkkk";  
  481. //         DeleteByQueryAction.INSTANCE.newRequestBuilder(client)  
  482. //               .source(article)  
  483. //               .filter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("id", guid)).must(QueryBuilders.termQuery("author", author)).must(QueryBuilders.typeQuery(content)))  
  484. //               .get();  
  485.     }  
  486.       
  487.       
  488.     /**  
  489.      * 使用matchAllQuery删除所有文档  
  490.      */  
  491.     @Test  
  492.     public void deleteAll(){  
  493. //         DeleteByQueryAction.INSTANCE.newRequestBuilder(client)  
  494. //           .source(article)  
  495. //           .filter(QueryBuilders.matchAllQuery())  
  496. //           .get();  
  497.     }  
  498.       
  499.       
  500.     /**  
  501.      * bulk批量通过指定id删除方法  
  502.      */  
  503.     @Test  
  504.     public void batchUndercarriageFamilies() {  
  505.        List<StringpublishIds=new ArrayList<>();  
  506.        publishIds.add("AV49wyfCWmWw7AxKFxeY");  
  507.        publishIds.add("AV49wyfCWmWw7AxKFxea");  
  508.        BulkRequestBuilder builder=client.prepareBulk();  
  509.        for(String publishId:publishIds){  
  510.           System.out.println(publishId);  
  511.           builder.add(client.prepareDelete(article, content, publishId).request());  
  512.             
  513.        }  
  514.        BulkResponse bulkResponse = builder.get();  
  515.        System.out.println(bulkResponse.status());  
  516.     }  
  517.       
  518.       
  519.   
  520.       
  521.     /**  
  522.      * -----------------------------------------改()  
  523.      */  
  524.       
  525.       
  526.     /**  
  527.      * 更新文档  
  528.      * @throws Exception  
  529.      */  
  530.     @Test  
  531.     public void updateDocument() throws Exception{  
  532.           
  533.         Date time = new Date();  
  534.   
  535.         //创建修改请求  
  536.         UpdateRequest updateRequest = new UpdateRequest();  
  537.         updateRequest.index(article);  
  538.         updateRequest.type(content);  
  539.         updateRequest.id("AV4xv5gAZLX8AvCc6ZWZ");  
  540.         updateRequest.doc(XContentFactory.jsonBuilder()  
  541.         .startObject()  
  542.         .field("author","FKSE")  
  543.         .field("title","JAVA思想")  
  544.         .field("content","注意:这是JAVA有关的书籍")  
  545.         .field("date",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time))  
  546.         .endObject());  
  547.           
  548.         UpdateResponse response = client.update(updateRequest).get();  
  549.         System.out.println("更新索引成功");  
  550.     }  
  551.       
  552.       
  553.       
  554.     /**  
  555.      * -----------------------------有问题:要引入:reindex  
  556.      */  
  557.       
  558.       
  559.     /**  
  560.      * UpdateByQueryRequestBuilder  
  561.      * @throws Exception  
  562.      */  
  563.     @Test  
  564.     public void updateByQueryRequestBuilder() throws Exception {  
  565. //        UpdateByQueryRequestBuilder updateByQueryRequestBuilder = UpdateByQueryAction.INSTANCE.newRequestBuilder(client);  
  566. //        updateByQueryRequestBuilder  
  567. //                .script(new Script(ScriptType.INLINE,"painless","ctx_source.likes++",null))  
  568. //                .source()  
  569. //                .setQuery(QueryBuilders.termQuery("author","kkkkk"))  
  570. //                .setIndices(article)  
  571. //                .get();  
  572.     }  
  573.       
  574.       
  575.     /**  
  576.      * updateByQueryRequestBuilders  
  577.      */  
  578.     @Test  
  579.     public void updateByQueryRequestBuilders(){  
  580.           
  581. //      Map<String, Objectmaps=new HashMap<>();  
  582. //      maps.put("orgin_session_id", 10);  
  583. //      maps.put("orgin_session_id", 11);  
  584. //      maps.put("orgin_session_id", 12);  
  585. //      maps.put("orgin_session_id", 13);  
  586. //        
  587. //      Set<Map<String, Object>docs = new HashSet<>();  
  588. //      docs.add(maps);  
  589. //        
  590. //      UpdateByQueryRequestBuilder  ubqrb = UpdateByQueryAction.INSTANCE.newRequestBuilder(client);  
  591. //        for (Map<String, Object> doc : docs) {  
  592. //            if (doc==null || doc.isEmpty()){  
  593. //                return;  
  594. //            }  
  595. //            Script script = new Script("ctx._source.price = ctx._version");  
  596. //              
  597. //            System.out.println(doc.get("orgin_session_id"));  
  598. //              
  599. //            //BulkIndexByScrollResponse  
  600. //            BulkByScrollResponse scrollResponse = ubqrb.source(article).script(script)  
  601. //                            .filter(QueryBuilders.matchAllQuery()).get();  
  602. //            for (BulkItemResponse.Failure failure : scrollResponse.getBulkFailures()) {  
  603. //              System.out.println(failure.getMessage());  
  604. //            }  
  605. //        }  
  606.     }  
  607.       
  608.     /**  
  609.      * prepareUpdate  
  610.      * @throws Exception  
  611.      */  
  612.     @Test  
  613.     public void prepareUpdate() throws Exception {  
  614.           
  615.         XContentBuilder endObject = XContentFactory.jsonBuilder().startObject().field("author","AAAAAAAAAAAAAAA").endObject();  
  616.         UpdateResponse response = client.prepareUpdate(article, content, "AV49wyfCWmWw7AxKFxeb").setDoc(endObject).get();  
  617.         System.out.println(response.getVersion());  
  618.           
  619.     }  
  620.       
  621.       
  622.     /**  
  623.      * -----------------------------------------查()  
  624.      */  
  625.       
  626.       
  627.       
  628.     /**  
  629.      * 根据index、type、id进行查询  
  630.      */  
  631.     @Test  
  632.     public void searchByIndex(){  
  633.           
  634.         GetResponse response = client.prepareGet(article,content,"AV49wyfCWmWw7AxKFxec").execute()    
  635.                 .actionGet();    
  636.         String json = response.getSourceAsString();    
  637.         if (null != json) {    
  638.             System.out.println(json);  
  639.         } else {    
  640.             System.out.println("未查询到任何结果!");    
  641.         }    
  642.     }  
  643.       
  644.       
  645.     /**  
  646.      * 查询article索引下的所有数据   
  647.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-query-dsl-match-all-query.html'>  
  648.      * @throws Exception  
  649.      */  
  650.     @Test  
  651.     public  void matchAllQuery() throws Exception{  
  652.         QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();  
  653.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  654.         for (SearchHit searchHit : response.getHits()) {  
  655.             println(searchHit);  
  656.         }  
  657.     }  
  658.       
  659.       
  660.     /**  
  661.      * 查询article索引下的articledate的所有数据   
  662.      * @throws Exception  
  663.      */  
  664.     @Test  
  665.     public void searchmethod1() throws Exception{  
  666.         SearchResponse response = client.prepareSearch(article).setTypes(content).get();  
  667.         println(response);  
  668.         for (SearchHit  searchHit: response.getHits()) {  
  669.             println(searchHit);  
  670.         }  
  671.     }  
  672.       
  673.     /**  
  674.      * spanFirstQuery  
  675.      */  
  676.     @Test  
  677.     public void spanFirstQuery(){  
  678.           
  679.          // Span First    
  680.         QueryBuilder queryBuilder =QueryBuilders.spanFirstQuery(    
  681.                 QueryBuilders.spanTermQuery("title", "C"),  // Query    
  682.                 30000                                             // Max查询范围的结束位置    
  683.         );  
  684.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  685.         for (SearchHit searchHit : response.getHits()) {  
  686.             println(searchHit);  
  687.         }  
  688.     }  
  689.       
  690.       
  691.     /**  
  692.      * spanNearQuery  
  693.      */  
  694.     @Test  
  695.     public void spanNearQuery(){  
  696.             
  697.         // Span Near TODO NotSolved    
  698.         QueryBuilder queryBuilder =QueryBuilders.spanNearQuery(QueryBuilders.spanTermQuery("title", "C"),1000)    
  699.                 .addClause(QueryBuilders.spanTermQuery("name", "葫芦580娃")) // Span Term Queries    
  700.                 .addClause(QueryBuilders.spanTermQuery("name", "葫芦3812娃"))    
  701.                 .addClause(QueryBuilders.spanTermQuery("name", "葫芦7139娃"));  
  702.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  703.         for (SearchHit searchHit : response.getHits()) {  
  704.             println(searchHit);  
  705.         }  
  706.     }  
  707.       
  708.     /**  
  709.      * spanNotQuery  
  710.      */  
  711.     @Test  
  712.     public void spanNotQuery(){  
  713.          // Span Not TODO NotSolved    
  714.         QueryBuilder queryBuilder =QueryBuilders.spanNotQuery(QueryBuilders.spanTermQuery("title", "C"), null);    
  715.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  716.         for (SearchHit searchHit : response.getHits()) {  
  717.             println(searchHit);  
  718.         }  
  719.     }  
  720.       
  721.     /**  
  722.      * spanOrQuery  
  723.      */  
  724.     @Test  
  725.     public void spanOrQuery(){  
  726.         QueryBuilder queryBuilder =QueryBuilders.spanOrQuery(QueryBuilders.spanTermQuery("title", "C"));  
  727.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  728.         for (SearchHit searchHit : response.getHits()) {  
  729.             println(searchHit);  
  730.         }  
  731.     }  
  732.       
  733.       
  734.     public void moreLikeThisQuery(){  
  735.   
  736.     }  
  737.       
  738.      /**  
  739.      * 指定单查询条件  
  740.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-full-text-queries.html#java-query-dsl-simple-query-string-query'>  
  741.      * @throws Exception  
  742.      */  
  743.     @Test  
  744.     public  void matchQuery() throws Exception{  
  745.         QueryBuilder qb = QueryBuilders.matchQuery(  
  746.                 "title" ,   
  747.                 "C"     
  748.             );  
  749.         SearchResponse response = client.prepareSearch(article).setQuery(qb).get();  
  750.         for (SearchHit searchHit : response.getHits()) {  
  751.             println(searchHit);  
  752.         }  
  753.     }  
  754.       
  755.       
  756.   
  757.       
  758.     /**  
  759.      * termQuery 查询  
  760.      * @throws Exception  
  761.      */  
  762.     @Test  
  763.     public void termQuery() throws Exception{  
  764.   
  765.         QueryBuilder queryBuilder = QueryBuilders.termQuery("id","11");  
  766.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  767.         for (SearchHit  searchHit: response.getHits()) {  
  768.             println(searchHit);  
  769.         }  
  770.     }  
  771.   
  772.     /**  
  773.      * termQuery 查询  
  774.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-term-level-queries.html'>  
  775.      * @throws Exception  
  776.      */  
  777.     @Test  
  778.     public  void termsQuerys() throws Exception{  
  779.         QueryBuilder queryBuilder = QueryBuilders.termsQuery("id","1","2");      
  780.         SearchResponse response = client.prepareSearch("article").setQuery(queryBuilder).get();  
  781.         for (SearchHit  searchHit: response.getHits()) {  
  782.             println(searchHit);  
  783.         }  
  784.     }  
  785.       
  786.      /**  
  787.      * 范围查询RangeQuery  
  788.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-term-level-queries.html'>  
  789.      * @throws Exception  
  790.      */  
  791.     @Test  
  792.     public void rangeQuery() throws Exception{  
  793.         QueryBuilder queryBuilder = QueryBuilders.rangeQuery("price")     
  794.                 .from(1)                              
  795.                 .to(100)                               
  796.                 .includeLower(false)                   
  797.                 .includeUpper(false);  
  798.         // A simplified form using gte, gt, lt or lte  
  799.         QueryBuilder _qb = QueryBuilders.rangeQuery("price")     
  800.             .gte("10")                          
  801.             .lt("20");  
  802.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  803.         for (SearchHit  searchHit: response.getHits()) {  
  804.             println(searchHit);  
  805.         }  
  806.     }  
  807.       
  808.       
  809.     /**  
  810.      * multiMatchQuery 查询    
  811.      * multiMatchQuery针对的是多个field,当fieldNames有多个参数时,如field1和field2,那查询的结果中,要么field1中包含text,要么field2中包含text。  
  812.      */  
  813.     @Test  
  814.     public void multiMatchQuery(){  
  815.         QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery("JAVA编程思想","title", "content");  
  816.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  817.         for (SearchHit  searchHit: response.getHits()) {  
  818.             println(searchHit);  
  819.         }     
  820.     }  
  821.       
  822.     /**  
  823.      * MultiMatchQueryBuilder  
  824.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-full-text-queries.html#java-query-dsl-simple-query-string-query'>  
  825.      * @throws Exception  
  826.      */  
  827.     @Test  
  828.     public void MultiMatchQueryBuilder() throws Exception {  
  829.         MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("JAVA编程思想","title", "content");  
  830.   
  831.         multiMatchQueryBuilder.analyzer("standard");  
  832.         multiMatchQueryBuilder.cutoffFrequency(0.001f);  
  833.         multiMatchQueryBuilder.field("title",20);  
  834.         multiMatchQueryBuilder.fuzziness(Fuzziness.TWO);  
  835.         multiMatchQueryBuilder.maxExpansions(100);  
  836.         multiMatchQueryBuilder.prefixLength(10);  
  837.         multiMatchQueryBuilder.tieBreaker(20);  
  838.         multiMatchQueryBuilder.type(MultiMatchQueryBuilder.Type.BEST_FIELDS);  
  839.         multiMatchQueryBuilder.boost(20);  
  840.   
  841.   
  842.   
  843.        SearchResponse searchResponse =  client.prepareSearch()  
  844.                 .setIndices(article)  
  845.                 .setTypes(content)  
  846.                 .setQuery(multiMatchQueryBuilder)  
  847.                 .execute()  
  848.                 .actionGet();  
  849.   
  850.        for (SearchHit  searchHit: searchResponse.getHits()) {  
  851.            println(searchHit);  
  852.        }      
  853.     }  
  854.       
  855.       
  856.     /**  
  857.      * MatchQueryBuilder  
  858.      * @throws Exception  
  859.      */  
  860.     @Test  
  861.     public void MatchQueryBuilder() throws Exception {  
  862.           
  863.         MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title","JAVA编程思想");  
  864.         matchQueryBuilder.fuzziness(Fuzziness.AUTO);  
  865.         SearchResponse searchResponse = client.prepareSearch()  
  866.                 .setIndices(article)  
  867.                 .setTypes(content)  
  868.                 .setQuery(matchQueryBuilder)  
  869.                 .execute()  
  870.                 .actionGet();  
  871.         println(searchResponse);  
  872.     }  
  873.       
  874.       
  875.      /**  
  876.      * 和matchQuery一样  
  877.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-full-text-queries.html#java-query-dsl-simple-query-string-query'>  
  878.      * @throws Exception  
  879.      */  
  880.     @Test  
  881.     public  void commonTermsQuery() throws Exception{  
  882.         QueryBuilder queryBuilder = QueryBuilders.commonTermsQuery("id",      
  883.                 "1");  
  884.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  885.         for (SearchHit  searchHit: response.getHits()) {  
  886.             println(searchHit);  
  887.         }     
  888.     }  
  889.       
  890.       
  891.     /**  
  892.      * MultiGetResponse  查询多个xxx的值  
  893.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-docs-multi-get.html'>  
  894.      * @throws Exception  
  895.      */  
  896.     @Test  
  897.     public void MultiGetResponse() throws Exception {  
  898.         MultiGetResponse multiGetItemResponses = client.prepareMultiGet()  
  899.                 .add(article, content, "526")  
  900.                 .add(article, content, "572", "582", "613")  
  901.                 .get();  
  902.         for (MultiGetItemResponse itemResponse : multiGetItemResponses) {  
  903.             GetResponse response = itemResponse.getResponse();  
  904.             if (response.isExists()) {  
  905.                 String json = response.getSourceAsString();  
  906.                 System.out.println(json);  
  907.             }  
  908.         }  
  909.     }  
  910.       
  911.     /**  
  912.      * +包含 -除外  
  913.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-full-text-queries.html#java-query-dsl-simple-query-string-query'>  
  914.      * @throws Exception  
  915.      */  
  916.     @Test  
  917.     public void queryStringQuery() throws Exception{  
  918.         QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("*:*");         
  919.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  920.         for (SearchHit  searchHit: response.getHits()) {  
  921.             println(searchHit);  
  922.         }     
  923.     }  
  924.       
  925.     /**  
  926.      * +包含 -除外  
  927.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-full-text-queries.html#java-query-dsl-simple-query-string-query'>  
  928.      * @throws Exception  
  929.      */  
  930.     @Test  
  931.     public void simpleQueryStringQuery() throws Exception{  
  932.         QueryBuilder queryBuilder = QueryBuilders.simpleQueryStringQuery("+id:1");           
  933.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  934.         for (SearchHit  searchHit: response.getHits()) {  
  935.             println(searchHit);  
  936.         }     
  937.     }  
  938.   
  939.   
  940.      /**  
  941.      * existsQuery  
  942.      * 匹配含有id字段的记录  
  943.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-term-level-queries.html'>  
  944.      * @throws Exception  
  945.      */  
  946.     @Test  
  947.     public void existsQuery() throws Exception{  
  948.         QueryBuilder queryBuilder = QueryBuilders.existsQuery("id");   
  949.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  950.         for (SearchHit  searchHit: response.getHits()) {  
  951.             println(searchHit);  
  952.         }     
  953.     }  
  954.       
  955.       
  956.      /**  
  957.      * prefixQuery  匹配包含具有指定前缀的术语的文档的查询  
  958.      * 匹配title中前缀为JAVA的记录  
  959.      * 匹配分词前缀 如果字段没分词,就匹配整个字段前缀  
  960.      * 前缀匹配(比如我要查询的是192.168.1.12,但是当输入192.168、192.168.1、192.168.1.1等的情况都会有相应结果返回,只不过是个范围)  
  961.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-term-level-queries.html'>  
  962.      * @throws Exception  
  963.      */  
  964.     @Test  
  965.     public void prefixQuery() throws Exception{  
  966.         QueryBuilder queryBuilder = QueryBuilders.prefixQuery(  
  967.                 "title",      
  968.                 "192.138"       
  969.             );  
  970.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  971.         for (SearchHit  searchHit: response.getHits()) {  
  972.             println(searchHit);  
  973.         }  
  974.     }  
  975.       
  976.       
  977.     /**  
  978.      * MatchPhrasePrefixQueryBuilder  为提供的字段名称和文本创建一个类型为“PHRASE_PREFIX”的匹配查询。  
  979.      * @throws Exception  
  980.      */  
  981.     @Test  
  982.     public void MatchPhrasePrefixQueryBuilder() throws Exception {  
  983.         String key = "C++";  
  984.         MatchPhrasePrefixQueryBuilder matchPhrasePrefixQueryBuilder = QueryBuilders.matchPhrasePrefixQuery("title",key);  
  985.   
  986.         matchPhrasePrefixQueryBuilder.boost(10);  
  987.         matchPhrasePrefixQueryBuilder.analyzer("standard");  
  988.         matchPhrasePrefixQueryBuilder.slop(2);  
  989.         matchPhrasePrefixQueryBuilder.maxExpansions(100);  
  990.   
  991.         SearchResponse searchResponse = client.prepareSearch()  
  992.                 .setIndices(article)  
  993.                 .setTypes(content)  
  994.                 .setQuery(matchPhrasePrefixQueryBuilder)  
  995.                 .execute()  
  996.                 .actionGet();  
  997.         for (SearchHit  searchHit: searchResponse.getHits()) {  
  998.             println(searchHit);  
  999.         }  
  1000.     }  
  1001.       
  1002.   
  1003.     /**  
  1004.      * wildcardQuery  
  1005.      * 通配符  
  1006.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-term-level-queries.html'>  
  1007.      * @throws Exception  
  1008.      */  
  1009.     @Test  
  1010.     public void wildcardQuery() throws Exception{  
  1011.         QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("author", "*e");//J?V*  
  1012.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  1013.         for (SearchHit  searchHit: response.getHits()) {  
  1014.             println(searchHit);  
  1015.         }  
  1016.     }  
  1017.   
  1018.     /**  
  1019.      * fuzzyQuery  使用模糊查询匹配文档的查询  
  1020.      * @throws Exception  
  1021.      */  
  1022.     @Test  
  1023.     public  void fuzzyQuery() throws Exception{  
  1024.         QueryBuilder queryBuilder = QueryBuilders.fuzzyQuery(  
  1025.                 "author",       
  1026.                 "e"      
  1027.             );  
  1028.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  1029.         for (SearchHit  searchHit: response.getHits()) {  
  1030.             println(searchHit);  
  1031.         }  
  1032.     }  
  1033.   
  1034.   
  1035.     /**  
  1036.      * boolQuery 匹配与其他查询的布尔组合匹配的文档的查询。  
  1037.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-compound-queries.html'>  
  1038.      * @throws Exception  
  1039.      */  
  1040.     @Test  
  1041.     public void BoostQuery() throws Exception{  
  1042.         BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()  
  1043.                 .should(QueryBuilders.termQuery("author","eeee")).boost(100) //设置此查询的权重。 匹配此查询的文件(除正常权重之外)的得分乘以提供的提升。  
  1044.                 .should(QueryBuilders.termQuery("id","AV5NF_Dbhqf-jFOFkksT").boost(1));  
  1045.   
  1046.         SearchResponse response=client.prepareSearch("article").setQuery(boolQueryBuilder).execute().get();  
  1047.         for (SearchHit  searchHit: response.getHits()) {  
  1048.             println(searchHit);  
  1049.         }  
  1050.           
  1051.     }  
  1052.       
  1053.       
  1054.     /**  
  1055.      * boolQuery  
  1056.      * @throws Exception  
  1057.      */  
  1058.     @Test  
  1059.     public void boolQuery() throws Exception {  
  1060.         QueryBuilder qb = QueryBuilders.boolQuery()  
  1061.                 .must(QueryBuilders.termQuery("author", "eeee"))  
  1062.                 .must(QueryBuilders.termQuery("title", "JAVA思想"))  
  1063.                 .mustNot(QueryBuilders.termQuery("content", "C++")) //添加不得出现在匹配文档中的查询。  
  1064.                 .should(QueryBuilders.termQuery("id", "AV5NF_Dbhqf-jFOFkksT"))//添加应该与返回的文档匹配的子句。 对于具有no的布尔查询,子句必须一个或多个SHOULD子句且必须与文档匹配,用于布尔值查询匹配。 不允许null值。  
  1065.                 .filter(QueryBuilders.termQuery("price", "30.3"));//添加一个查询,必须出现在匹配的文档中,但会不贡献得分。 不允许null值。  
  1066.         SearchResponse response=client.prepareSearch().setQuery(qb).execute().actionGet();  
  1067.           
  1068.         for (SearchHit  searchHit: response.getHits()) {  
  1069.             println(searchHit);  
  1070.         }  
  1071.     }  
  1072.       
  1073.   
  1074.     /**  
  1075.      * boostingQuery  
  1076.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-compound-queries.html'>  
  1077.      * @throws Exception  
  1078.      */  
  1079.     @Test  
  1080.     public void boostingQuery() throws Exception {  
  1081.         QueryBuilder qb = QueryBuilders.boostingQuery(  
  1082.                 QueryBuilders.termQuery("id","AV5NF_Dbhqf-jFOFkksR"),  
  1083.                 QueryBuilders.termQuery("title","C"))  
  1084.                 .negativeBoost(0.2f);//设置负增强因子。  
  1085.         SearchResponse response=client.prepareSearch().setQuery(qb).execute().actionGet();  
  1086.           
  1087.         for (SearchHit  searchHit: response.getHits()) {  
  1088.             println(searchHit);  
  1089.         }  
  1090.     }  
  1091.       
  1092.       
  1093.       
  1094.     /**  
  1095.      * constantScoreQuery  
  1096.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-compound-queries.html'>  
  1097.      * @throws Exception  
  1098.      */  
  1099.     @Test  
  1100.     public void constantScoreQuery() throws Exception {  
  1101.         QueryBuilder qb = QueryBuilders.constantScoreQuery(  
  1102.                 QueryBuilders.termQuery("title","C")  
  1103.         ).boost(2.0f);  
  1104.         SearchResponse response=client.prepareSearch().setQuery(qb).execute().actionGet();  
  1105.         for (SearchHit  searchHit: response.getHits()) {  
  1106.             println(searchHit);  
  1107.         }  
  1108.     }  
  1109.       
  1110.     /**  
  1111.      * disMaxQuery  
  1112.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-compound-queries.html'>  
  1113.      * @throws Exception  
  1114.      */  
  1115.     @Test  
  1116.     public void disMaxQuery() throws Exception {  
  1117.         QueryBuilder qb = QueryBuilders.disMaxQuery()  
  1118.                 .add(QueryBuilders.termQuery("id", "512"))  
  1119.                 .add(QueryBuilders.termQuery("author", "ckse"))  
  1120.                 .boost(1.2f)  
  1121.                 .tieBreaker(0.7f);  
  1122.         SearchResponse response=client.prepareSearch().setQuery(qb).execute().actionGet();  
  1123.         for (SearchHit  searchHit: response.getHits()) {  
  1124.             println(searchHit);  
  1125.         }  
  1126.     }  
  1127.       
  1128.       
  1129.     /**  
  1130.      * functionScoreQuery  
  1131.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-compound-queries.html'>  
  1132.      * @throws Exception  
  1133.      */  
  1134.     @Test  
  1135.     public void functionScoreQuery() throws Exception {  
  1136.         FunctionScoreQueryBuilder.FilterFunctionBuilder[] functions = {  
  1137.                 new FunctionScoreQueryBuilder.FilterFunctionBuilder(  
  1138.                         QueryBuilders.matchQuery("id", "512"),  
  1139.                         ScoreFunctionBuilders.randomFunction("ABCDEF")),  
  1140.                 new FunctionScoreQueryBuilder.FilterFunctionBuilder(  
  1141.                         ScoreFunctionBuilders.exponentialDecayFunction("age", 0L, 1L))  
  1142.         };  
  1143.         QueryBuilder qb = QueryBuilders.functionScoreQuery(functions);  
  1144.         SearchResponse response=client.prepareSearch().setQuery(qb).execute().actionGet();  
  1145.         for (SearchHit  searchHit: response.getHits()) {  
  1146.             println(searchHit);  
  1147.         }  
  1148.     }  
  1149.       
  1150.       
  1151.     /**  
  1152.      * regexpQuery 匹配包含具有指定正则表达式的术语的文档的查询。  
  1153.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-term-level-queries.html'>  
  1154.      * @throws Exception  
  1155.      */  
  1156.     @Test  
  1157.     public void regexpQuery() throws Exception {  
  1158.         QueryBuilder qb = QueryBuilders.regexpQuery(  
  1159.                 "title",  
  1160.                 "*J");  
  1161.         SearchResponse response=client.prepareSearch().setQuery(qb).execute().actionGet();  
  1162.         for (SearchHit  searchHit: response.getHits()) {  
  1163.             println(searchHit);  
  1164.         }  
  1165.     }  
  1166.       
  1167.     /**  
  1168.      * typeQuery  
  1169.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-term-level-queries.html'>  
  1170.      * @throws Exception  
  1171.      */  
  1172.     @Test  
  1173.     public  void typeQuery() throws Exception{  
  1174.         QueryBuilder queryBuilder = QueryBuilders.typeQuery("data");  
  1175.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  1176.         for (SearchHit  searchHit: response.getHits()) {  
  1177.             println(searchHit);  
  1178.         }  
  1179.     }  
  1180.   
  1181.     /**  
  1182.      * idsQuery  
  1183.      * 类型是可选的  
  1184.      * 指定type和id进行查询。  
  1185.      * <href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-term-level-queries.html'>  
  1186.      * @throws Exception  
  1187.      */  
  1188.     @Test  
  1189.     public  void idsQuery() throws Exception{  
  1190.         QueryBuilder queryBuilder = QueryBuilders.idsQuery(content)   
  1191.                 .addIds("512", "520", "531");  
  1192.         SearchResponse response = client.prepareSearch(article).setQuery(queryBuilder).get();  
  1193.         for (SearchHit  searchHit: response.getHits()) {  
  1194.             println(searchHit);  
  1195.         }  
  1196.     }  
  1197.       
  1198.     /**  
  1199.      * group 分组查询  
  1200.      */  
  1201.     @Test  
  1202.     public void group(){  
  1203.   
  1204.       
  1205.     }  
  1206.       
  1207.     /**  
  1208.      * Aggregation  
  1209.      */  
  1210.     @Test  
  1211.     public void Aggregation()  
  1212.     {  
  1213.   
  1214.         BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();    
  1215.         //添加时间范围过滤    
  1216.         boolQueryBuilder.must(QueryBuilders.rangeQuery("@timestamp").format("yyyy-MM-dd HH:mm:ss").gte("").lte(""));    
  1217.         AggregationBuilder aggregationBuilder = AggregationBuilders  
  1218.                 //terms(查询字段别名).field(分组字段)   
  1219.                 .terms("").field("")    
  1220.                 .order(Terms.Order.aggregation("", false))    
  1221.                 .size(10)    
  1222.                 .subAggregation(AggregationBuilders.count("").field(""));    
  1223.         SearchRequestBuilder searchRequestBuilder = client.prepareSearch("article").setTypes("articledate")    
  1224.                 .setQuery(boolQueryBuilder)    
  1225.                 .addAggregation(aggregationBuilder)    
  1226.                 .setSize(0);    
  1227.     
  1228.         SearchResponse sr = searchRequestBuilder.execute().actionGet();    
  1229.         Terms genders = sr.getAggregations().get("");//统计字段别名  
  1230.         for (Terms.Bucket entry : genders.getBuckets())   
  1231.         {   
  1232.           System.out.println((String) entry.getKey()+"-("+entry.getDocCount()+")");   
  1233.         }  
  1234.           
  1235.           
  1236.         //如想group by 时间,并且按天来进行分组  
  1237.         AggregationBuilder aggregation = AggregationBuilders    
  1238.                 .dateHistogram("agg")    
  1239.                 .field("@timestamp")    
  1240.                 .format("yyyy-MM-dd")    
  1241.                 .dateHistogramInterval(DateHistogramInterval.DAY);   
  1242.         //可能有新需求,group by 时间,姓名  
  1243.         //AggregationBuilder nameAgg = AggregationBuilders.terms(姓名别名).field(姓名).size(10);    
  1244.         //aggregation.subAggregation(nameAgg);   
  1245.           
  1246.         //可以能需要进行名称统计,但是需要distinct  
  1247.         //aggregation.subAggregation(AggregationBuilders.cardinality(别名).field(姓名))   
  1248.           
  1249.         //其他如下  
  1250. //        (1)统计某个字段的数量    
  1251. //        ValueCountBuilder vcb=  AggregationBuilders.count("count_uid").field("uid");    
  1252. //      (2)去重统计某个字段的数量(有少量误差)    
  1253. //       CardinalityBuilder cb= AggregationBuilders.cardinality("distinct_count_uid").field("uid");    
  1254. //      (3)聚合过滤    
  1255. //      FilterAggregationBuilder fab= AggregationBuilders.filter("uid_filter").filter(QueryBuilders.queryStringQuery("uid:001"));    
  1256. //      (4)按某个字段分组    
  1257. //      TermsBuilder tb=  AggregationBuilders.terms("group_name").field("name");    
  1258. //      (5)求和    
  1259. //      SumBuilder  sumBuilder= AggregationBuilders.sum("sum_price").field("price");    
  1260. //      (6)求平均    
  1261. //      AvgBuilder ab= AggregationBuilders.avg("avg_price").field("price");    
  1262. //      (7)求最大值    
  1263. //      MaxBuilder mb= AggregationBuilders.max("max_price").field("price");     
  1264. //      (8)求最小值    
  1265. //      MinBuilder min= AggregationBuilders.min("min_price").field("price");    
  1266. //      (9)按日期间隔分组    
  1267. //      DateHistogramBuilder dhb= AggregationBuilders.dateHistogram("dh").field("date");    
  1268. //      (10)获取聚合里面的结果    
  1269. //      TopHitsBuilder thb=  AggregationBuilders.topHits("top_result");    
  1270. //      (11)嵌套的聚合    
  1271. //      NestedBuilder nb= AggregationBuilders.nested("negsted_path").path("quests");    
  1272. //      (12)反转嵌套    
  1273. //      AggregationBuilders.reverseNested("res_negsted").path("kps ");    
  1274.           
  1275.           
  1276.     }  
  1277.       
  1278.       
  1279.     /**  
  1280.      * MultiSearchResponse 多字段检索  
  1281.      */  
  1282.     @Test  
  1283.     public void MultiSearchResponse(){  
  1284.           
  1285.           
  1286.         SearchRequestBuilder srb1 = client.prepareSearch().setQuery(QueryBuilders.queryStringQuery("JAVA"));  
  1287.         SearchRequestBuilder srb2 = client.prepareSearch().setQuery(QueryBuilders.matchQuery("title", "C"));  
  1288.   
  1289.         MultiSearchResponse sr = client.prepareMultiSearch().add(srb1).add(srb2).get();  
  1290.   
  1291.         for (MultiSearchResponse.Item item : sr.getResponses()) {  
  1292.             SearchResponse response = item.getResponse();  
  1293.             for (SearchHit searchHit : response.getHits()) {  
  1294.                 println(searchHit);  
  1295.             }  
  1296.         }  
  1297.     }  
  1298.       
  1299.       
  1300.       
  1301.       
  1302.     /**  
  1303.      * 复杂查询  
  1304.      */  
  1305.     @Test  
  1306.     public void complexSearch1(){  
  1307.         int page=1;  
  1308.         int pageSize=10;  
  1309.         String keyword="";  
  1310.           
  1311.         BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery();  
  1312.           
  1313.         if(keyword!=null&&!keyword.equals("")){  
  1314.            QueryBuilder nameBuilder=QueryBuilders.matchQuery("zuName", keyword).analyzer("ik_max_word").boost(10);  
  1315.            QueryBuilder labelBuilder=QueryBuilders.matchQuery("zuLabelName", keyword).analyzer("ik_max_word").boost(10);  
  1316.            QueryBuilder categoryBuilder=QueryBuilders.matchQuery("categoryName", keyword).analyzer("ik_max_word").boost(10);  
  1317.            boolQueryBuilder.should(nameBuilder).should(labelBuilder).should(categoryBuilder);  
  1318.         }else{  
  1319.            boolQueryBuilder.must(QueryBuilders.matchAllQuery());  
  1320.         }  
  1321.         SearchResponse response=client.prepareSearch("article").setTypes("articledate")  
  1322.               .setQuery(boolQueryBuilder)  
  1323.               .setFrom((page-1)*pageSize).setSize(pageSize)  
  1324.               .setExplain(true)  
  1325.               .get();  
  1326.   
  1327.         SearchHits hits=response.getHits();  
  1328.     }  
  1329.       
  1330.     /**  
  1331.      * 复杂查询2  
  1332.      */  
  1333.     @Test  
  1334.     public void complexSearch2(){  
  1335.           
  1336.         String relatedValue="fendo";  
  1337.         String userId="1234";  
  1338.         int page=1;  
  1339.         int pageSize=10;  
  1340.           
  1341.         BoolQueryBuilder builders=new BoolQueryBuilder();  
  1342.         //加上条件  
  1343.         builders.must(QueryBuilders.termQuery("userId", userId));  
  1344.         if(relatedValue=="fendo"){  
  1345.            builders.must(QueryBuilders.nestedQuery("related4ZuValue",  
  1346.                  QueryBuilders.boolQuery()  
  1347.                           .must(QueryBuilders.termQuery("related4ZuValue.nameValue", ""))  
  1348.                           //.must(QueryBuilders.rangeQuery("endTime").lte(LongformStringDate(System.currentTimeMillis())))  
  1349.                  ,ScoreMode.None));  
  1350.         }else{  
  1351.            builders.must(QueryBuilders.nestedQuery("related4ZuValue", QueryBuilders.termQuery("related4ZuValue.nameValue", ""),   
  1352.                  ScoreMode.None));  
  1353.         }  
  1354.         SearchResponse response=client.prepareSearch("article").setTypes("articledate")  
  1355.               .setQuery(builders).setFrom((page-1)*pageSize)  
  1356.               .setSize(pageSize)  
  1357.               .get();  
  1358.         SearchHits hits=response.getHits();  
  1359.     }  
  1360.       
  1361.       
  1362.     /**  
  1363.      * 取查询结果总和count  
  1364.      */  
  1365.     @Test  
  1366.     public void countSum() {  
  1367.           
  1368.            int relatedValue=1;  
  1369.            String userId="111";  
  1370.            BoolQueryBuilder builders=new BoolQueryBuilder();  
  1371.            builders.must(QueryBuilders.termQuery("userId", userId));  
  1372.            if(relatedValue==1){  
  1373.                builders.must(QueryBuilders.nestedQuery("related4ZuValue",QueryBuilders.boolQuery()  
  1374.                          .must(QueryBuilders.termQuery("related4ZuValue.nameValue", "123"))  
  1375.                          .must(QueryBuilders.rangeQuery("endTime").lte(""))  
  1376.                 ,ScoreMode.None));  
  1377.                                
  1378.            }else{  
  1379.               builders.must(QueryBuilders.nestedQuery("related4ZuValue", QueryBuilders.termQuery("related4ZuValue.nameValue", "111"),   
  1380.                     ScoreMode.None));  
  1381.            }  
  1382.            SearchResponse response=client.prepareSearch("article").setTypes("articledate")  
  1383.                  .setQuery(builders)  
  1384.                  .setSize(1)  
  1385.                  .get();  
  1386.            SearchHits hits=response.getHits();  
  1387.            System.out.println(hits.getTotalHits());  
  1388.         }  
  1389.       
  1390.       
  1391.       
  1392.     /**  
  1393.      * 聚合求和sum  
  1394.      * @param keyword  
  1395.      * @param startTime  
  1396.      * @param endTime  
  1397.      */  
  1398.     @Test  
  1399.     public void getPlatformZuOrdersTotalAmount() {  
  1400.           
  1401.            String keyword="";  
  1402.            String startTime="";  
  1403.            String endTime="";  
  1404.           
  1405.            BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery();  
  1406.            if(keyword==null||keyword.equals("")){  
  1407.               QueryBuilder queryBuilder=QueryBuilders.matchAllQuery();  
  1408.               boolQueryBuilder.must(queryBuilder);  
  1409.            }else{  
  1410.               QueryBuilder zuNameBuilder=QueryBuilders.matchQuery("zuName", keyword);  
  1411.               QueryBuilder buyerNameBuilder=QueryBuilders.matchQuery("buyerName", keyword);  
  1412.               QueryBuilder sellerNameBuilder=QueryBuilders.matchQuery("sellerName", keyword);  
  1413.               boolQueryBuilder.should(zuNameBuilder).should(buyerNameBuilder).should(sellerNameBuilder);  
  1414.                 
  1415.            }  
  1416.            if(!startTime.equals("")){  
  1417.               QueryBuilder addTimeBuilder=QueryBuilders.rangeQuery("addTime").from(startTime).to(endTime);  
  1418.               boolQueryBuilder.must(addTimeBuilder);  
  1419.            }  
  1420.            SearchResponse response=client.prepareSearch("article").setTypes("articledate")  
  1421.                  .setQuery(boolQueryBuilder)  
  1422.                  .addAggregation(AggregationBuilders.sum("price").field("price"))  
  1423.                  .get();  
  1424.            Sum sum=response.getAggregations().get("price");  
  1425.            System.out.println(sum.getValue());  
  1426.         }  
  1427.       
  1428.       
  1429.     /**  
  1430.      * ---------------------------分页  
  1431.      */  
  1432.       
  1433.       
  1434.     /**  
  1435.      * 使用Scroll方法分页  
  1436.      */  
  1437.     @Test  
  1438.     public void queryPageScroll(){  
  1439.           
  1440.         QueryBuilder qb = QueryBuilders.termQuery("id", "1");  
  1441.   
  1442.         SearchResponse scrollResp = client.prepareSearch("article")  
  1443.                 .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)  
  1444.                 .setScroll(new TimeValue(60000))  
  1445.                 .setQuery(qb)  
  1446.                 .setSize(1).get();   
  1447.         do {  
  1448.             for (SearchHit hit : scrollResp.getHits().getHits()) {  
  1449.                 println(hit);  
  1450.             }  
  1451.             scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();  
  1452.         } while(scrollResp.getHits().getHits().length != 0);   
  1453.     }  
  1454.       
  1455.       
  1456.     /**  
  1457.      * 分页  
  1458.      * @throws Exception  
  1459.      */  
  1460.     @Test  
  1461.     public void fenye() throws Exception {  
  1462.   
  1463.         SearchResponse response = client.prepareSearch("article")  
  1464.                 .setQuery(QueryBuilders.matchAllQuery())  
  1465.                 .setFrom(10)   
  1466.                 .setSize(20)  
  1467.                 .execute().actionGet();  
  1468.         for (SearchHit searchHit : response.getHits()) {  
  1469.             println(searchHit);  
  1470.         }  
  1471.   
  1472.     }  
  1473.       
  1474.       
  1475.     /**  
  1476.      * 高亮  
  1477.      * @throws Exception  
  1478.      */  
  1479.     @Test  
  1480.     public void highlighter() throws Exception{  
  1481.   
  1482.   
  1483.          QueryBuilder matchQuery = QueryBuilders.matchQuery("author", "fendo");  
  1484.             HighlightBuilder hiBuilder=new HighlightBuilder();  
  1485.             hiBuilder.preTags("<h2>");  
  1486.             hiBuilder.postTags("h2>");  
  1487.             hiBuilder.field("author");  
  1488.             // 搜索数据  
  1489.             SearchResponse response = client.prepareSearch("article")  
  1490.                     .setQuery(matchQuery)  
  1491.                     .highlighter(hiBuilder)  
  1492.                     .execute().actionGet();  
  1493.             for (SearchHit searchHit : response.getHits()) {  
  1494.                 println(searchHit);  
  1495.             }  
  1496.     }  
  1497.       
  1498.       
  1499.       
  1500.       
  1501.       
  1502.     /**  
  1503.      * ---------------------------分词器  
  1504.      */  
  1505.       
  1506.     /**  
  1507.      * AnalyzeRequest 分词器  
  1508.      * <href='https://www.elastic.co/guide/cn/elasticsearch/guide/current/standard-tokenizer.html'>  
  1509.      * @throws Exception  
  1510.      */  
  1511.     @Test  
  1512.     public void AnalyzeRequest() throws Exception {  
  1513.         AnalyzeRequest analyzeRequest = new AnalyzeRequest();  
  1514.         analyzeRequest.text("My œsophagus caused a débâcle");  
  1515.         /**  
  1516.          * whitespace (空白字符)分词器按空白字符 —— 空格、tabs、换行符等等进行简单拆分  
  1517.          * letter 分词器 ,采用另外一种策略,按照任何非字符进行拆分  
  1518.          * standard 分词器使用 Unicode 文本分割算法  
  1519.          */  
  1520.         analyzeRequest.addTokenFilter("standard");  
  1521.         analyzeRequest.addCharFilter("asciifolding");  
  1522.         ActionFuture<AnalyzeResponseanalyzeResponseActionFuture =  client.admin().indices().analyze(analyzeRequest);  
  1523.         List<AnalyzeResponse.AnalyzeTokenanalyzeTokens =  analyzeResponseActionFuture.actionGet().getTokens();  
  1524.         for (AnalyzeResponse.AnalyzeToken analyzeToken : analyzeTokens){  
  1525.             System.out.println(analyzeToken.getTerm());  
  1526.         }  
  1527.     }  
  1528.       
  1529.     /**  
  1530.      * IK分词器  
  1531.      * @param args  
  1532.      * @throws IOException  
  1533.      */  
  1534.     public  void IKAnalyzer(String []args) throws IOException {  
  1535.         Settings settings  = Settings.EMPTY;  
  1536.         IKAnalyzer analyzer = new IKAnalyzer();  
  1537.         String text = "中华人民共和国国歌";  
  1538.         StringReader stringReader = new StringReader(text);  
  1539.         TokenStream tokenStream = analyzer.tokenStream("",stringReader);  
  1540.         tokenStream.reset();  
  1541.         CharTermAttribute term=tokenStream.getAttribute(CharTermAttribute.class);  
  1542.         while(tokenStream.incrementToken()){  
  1543.             System.out.print(term.toString()+"—");  
  1544.         }  
  1545.         stringReader.close();  
  1546.         tokenStream.close();  
  1547.     }  
  1548.      
  1549.     /**  
  1550.      * 输出结果SearchResponse  
  1551.      * @param response  
  1552.      */  
  1553.     public static void println(SearchResponse response){  
  1554.         System.err.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");  
  1555.         System.err.println(  
  1556.                 "getFailedShards : " + response.getFailedShards() + "\n" +  
  1557.                 "getNumReducePhases : " + response.getNumReducePhases() + "\n" +  
  1558.                 "getScrollId : " + response.getScrollId() +  "\n" +  
  1559.                 "getTookInMillis : " + response.getTookInMillis() + "\n" +   
  1560.                 "getTotalShards : " + response.getTotalShards() +  "\n" +  
  1561.                 "getAggregations : " + response.getAggregations() + "\n" +   
  1562.                 "getProfileResults : " + response.getProfileResults() + "\n" +   
  1563.                 "getShardFailures : " + response.getShardFailures() + "\n" +   
  1564.                 "getSuggest : " + response.getSuggest() + "\n" +   
  1565.                 "getTook : " + response.getTook() + "\n" +   
  1566.                 "isTerminatedEarly : " + response.isTerminatedEarly() + "\n" +   
  1567.                 "isTimedOut : " + response.isTimedOut() + "\n" +   
  1568.                 "remoteAddress : " + response.remoteAddress() + "\n" +   
  1569.                 "status : " + response.status() + "\n" +   
  1570.                 "getHits : " + response.getHits()   
  1571.                 );  
  1572.     }  
  1573.   
  1574.     /**  
  1575.      * 输出结果SearchResponse  
  1576.      * @param response  
  1577.      */  
  1578.     public static void println(SearchHit searchHit){  
  1579.         System.err.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");  
  1580.         System.err.println(   
  1581.                 "docId : " + searchHit.docId() + "\n" +  
  1582.                 "getId : " + searchHit.getId() + "\n" +  
  1583.                 "getIndex : " + searchHit.getIndex()+ "\n" +  
  1584.                 "getScore : " + searchHit.getScore() + "\n" +  
  1585.                 "getSourceAsString : " + searchHit.getSourceAsString() + "\n" +  
  1586.                 "getType : " + searchHit.getType() + "\n" +  
  1587.                 "getVersion : " + searchHit.getVersion() + "\n" +  
  1588.                 "fieldsOrNull : " + searchHit.fieldsOrNull() + "\n" +  
  1589.                 "getExplanation : " + searchHit.getExplanation() + "\n" +  
  1590.                 "getFields : " + searchHit.getFields() + "\n" +  
  1591.                 "highlightFields : " + searchHit.highlightFields() + "\n" +  
  1592.                 "hasSource : " + searchHit.hasSource()  
  1593.                 );  
  1594.     }  
  1595.   
  1596.       
  1597. }  

 

完整项目如下:http://download.csdn.net/download/u011781521/9964499

转载于:https://www.cnblogs.com/a-du/p/9172272.html

你可能感兴趣的:(Elasticsearch系列(五)----JAVA客户端之TransportClient操作详解)