Elasticsearch系列(七)----JAVA客户端之RestClient操作详解

482 阅读11分钟
原文链接: blog.csdn.net

elasticsearch 5.0引入了一个新的客户端 RestClient ,使用HTTP API elasticsearch代替内部协议, RestClient 初始化方法是线程安全的,最理想的客户端生命周期是与应用相同,在应用停止服务之前应该关闭客户端链接,释放资源。


[html] view plain copy print?
  1. 初始化客户端  
  2. RestClient restClient = RestClient.builder(  
  3.             new HttpHost("xxxx", 9800, "http"),  
  4.             new HttpHost("xxxx", 9800, "http")).build();  
  5.   
  6. 关闭客户端连接  
  7. restClient.close();  
    初始化客户端
    RestClient restClient = RestClient.builder(
                new HttpHost("xxxx", 9800, "http"),
                new HttpHost("xxxx", 9800, "http")).build();

    关闭客户端连接
    restClient.close();

RestClient完整示例如下:

[html] view plain copy print?
  1. package com.fendo.RestClient;  
  2.   
  3.   
  4. import java.io.IOException;  
  5. import java.util.Collections;  
  6.   
  7. import org.apache.http.HttpEntity;  
  8. import org.apache.http.HttpHost;  
  9. import org.apache.http.auth.AuthScope;  
  10. import org.apache.http.auth.UsernamePasswordCredentials;  
  11. import org.apache.http.client.CredentialsProvider;  
  12. import org.apache.http.entity.ContentType;  
  13. import org.apache.http.impl.client.BasicCredentialsProvider;  
  14. import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;  
  15. import org.apache.http.nio.entity.NStringEntity;  
  16. import org.apache.http.util.EntityUtils;  
  17. import org.elasticsearch.action.search.SearchResponse;  
  18. import org.elasticsearch.client.Response;  
  19. import org.elasticsearch.client.RestClient;  
  20. import org.elasticsearch.client.RestClientBuilder;  
  21. import org.elasticsearch.index.query.QueryBuilder;  
  22. import org.elasticsearch.index.query.QueryBuilders;  
  23. import org.junit.Before;  
  24. import org.junit.Test;  
  25.   
  26. /**  
  27.  * Elasticserach RestClient示例  
  28.  * @author fendo  
  29.  *  
  30.  */  
  31. public class Rest {  
  32.   
  33.     private static RestClient restClient;  
  34.       
  35.       
  36.       
  37.     public void getRestClient(){  
  38.           
  39.         final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();  
  40.         credentialsProvider.setCredentials(AuthScope.ANY,  
  41.                 new UsernamePasswordCredentials("elastic", "changeme"));  
  42.           
  43.         restClient = RestClient.builder(new HttpHost("localhost",9200,"http"))  
  44.                 .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {  
  45.                     @Override  
  46.                     public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {  
  47.                         return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);  
  48.                     }  
  49.                 }).build();  
  50.           
  51.     }  
  52.       
  53.     @Before  
  54.     public void getRest(){  
  55.         restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();   
  56.     }  
  57.       
  58.   
  59.   
  60.     /**  
  61.      * 查看api信息  
  62.      * @throws Exception  
  63.      */  
  64.     @Test  
  65.     public void CatApi() throws Exception{  
  66.         String method = "GET";  
  67.         String endpoint = "/_cat";  
  68.         Response response = restClient.performRequest(method,endpoint);  
  69.         System.out.println(EntityUtils.toString(response.getEntity()));  
  70.     }  
  71.       
  72.     /**  
  73.      * 创建索引  
  74.      * @throws Exception  
  75.      */  
  76.     @Test  
  77.     public void CreateIndex() throws Exception{  
  78.         String method = "PUT";  
  79.         String endpoint = "/test-index";  
  80.         Response response = restClient.performRequest(method,endpoint);  
  81.         System.out.println(EntityUtils.toString(response.getEntity()));  
  82.     }  
  83.       
  84.     /**  
  85.      * 创建文档  
  86.      * @throws Exception  
  87.      */  
  88.     @Test  
  89.     public void CreateDocument()throws Exception{  
  90.   
  91.         String method = "PUT";  
  92.         String endpoint = "/test-index/test/1";  
  93.         HttpEntity entity = new NStringEntity(  
  94.                 "{\n" +  
  95.                         "    \"user\" : \"kimchy\",\n" +  
  96.                         "    \"post_date\" : \"2009-11-15T14:12:12\",\n" +  
  97.                         "    \"message\" : \"trying out Elasticsearch\"\n" +  
  98.                         "}", ContentType.APPLICATION_JSON);  
  99.   
  100.         Response response = restClient.performRequest(method,endpoint, Collections. <String, String>emptyMap(),entity);  
  101.         System.out.println(EntityUtils.toString(response.getEntity()));  
  102.     }  
  103.       
  104.     /**  
  105.      * 获取文档  
  106.      * @throws Exception  
  107.      */  
  108.     @Test  
  109.     public void getDocument()throws Exception{  
  110.         String method = "GET";  
  111.         String endpoint = "/test-index/test/1";  
  112.         Response response = restClient.performRequest(method,endpoint);  
  113.         System.out.println(EntityUtils.toString(response.getEntity()));  
  114.     }  
  115.       
  116.       
  117.     /**  
  118.      * 查询所有数据  
  119.      * @throws Exception  
  120.      */  
  121.     @Test  
  122.     public void QueryAll() throws Exception {  
  123.         String method = "POST";  
  124.         String endpoint = "/test-index/test/_search";  
  125.         HttpEntity entity = new NStringEntity("{\n" +  
  126.                 "  \"query\": {\n" +  
  127.                 "    \"match_all\": {}\n" +  
  128.                 "  }\n" +  
  129.                 "}", ContentType.APPLICATION_JSON);  
  130.   
  131.         Response response = restClient.performRequest(method,endpoint,Collections. <String, String>emptyMap(),entity);  
  132.         System.out.println(EntityUtils.toString(response.getEntity()));  
  133.     }  
  134.       
  135.     /**  
  136.      * 根据ID获取  
  137.      * @throws Exception  
  138.      */  
  139.     @Test  
  140.     public void QueryByField() throws Exception {  
  141.         String method = "POST";  
  142.         String endpoint = "/test-index/test/_search";  
  143.         HttpEntity entity = new NStringEntity("{\n" +  
  144.                 "  \"query\": {\n" +  
  145.                 "    \"match\": {\n" +  
  146.                 "      \"user\": \"kimchy\"\n" +  
  147.                 "    }\n" +  
  148.                 "  }\n" +  
  149.                 "}", ContentType.APPLICATION_JSON);  
  150.   
  151.         Response response = restClient.performRequest(method,endpoint,Collections. <String, String>emptyMap(),entity);  
  152.         System.out.println(EntityUtils.toString(response.getEntity()));  
  153.     }  
  154.       
  155.     /**  
  156.      * 更新数据  
  157.      * @throws Exception  
  158.      */  
  159.     @Test  
  160.     public void UpdateByScript() throws Exception {  
  161.         String method = "POST";  
  162.         String endpoint = "/test-index/test/1/_update";  
  163.         HttpEntity entity = new NStringEntity("{\n" +  
  164.                 "  \"doc\": {\n" +  
  165.                 "    \"user\":\"大美女\"\n" +  
  166.                 "   }\n" +  
  167.                 "}", ContentType.APPLICATION_JSON);  
  168.         Response response = restClient.performRequest(method,endpoint,Collections. <String, String>emptyMap(),entity);  
  169.         System.out.println(EntityUtils.toString(response.getEntity()));  
  170.     }  
  171.       
  172.       
  173.     @Test  
  174.     public void GeoBoundingBox() throws IOException {  
  175.         String method = "POST";  
  176.         String endpoint = "/attractions/restaurant/_search";  
  177.         HttpEntity entity = new NStringEntity("{\n" +  
  178.                 "  \"query\": {\n" +  
  179.                 "    \"match_all\": {}\n" +  
  180.                 "  },\n" +  
  181.                 "  \"post_filter\": {\n" +  
  182.                 "    \"geo_bounding_box\": {\n" +  
  183.                 "      \"location\": {\n" +  
  184.                 "        \"top_left\": {\n" +  
  185.                 "          \"lat\": 39.990481,\n" +  
  186.                 "          \"lon\": 116.277144\n" +  
  187.                 "        },\n" +  
  188.                 "        \"bottom_right\": {\n" +  
  189.                 "          \"lat\": 39.927323,\n" +  
  190.                 "          \"lon\": 116.405638\n" +  
  191.                 "        }\n" +  
  192.                 "      }\n" +  
  193.                 "    }\n" +  
  194.                 "  }\n" +  
  195.                 "}", ContentType.APPLICATION_JSON);  
  196.         Response response =  restClient.performRequest(method,endpoint,Collections.<String, String >emptyMap(),entity);  
  197.         System.out.println(EntityUtils.toString(response.getEntity()));  
  198.     }  
  199. }  
package com.fendo.RestClient;


import java.io.IOException;
import java.util.Collections;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Before;
import org.junit.Test;

/**
 * Elasticserach RestClient示例
 * @author fendo
 *
 */
public class Rest {

	private static RestClient restClient;
	
	
	
	public void getRestClient(){
		
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("elastic", "changeme"));
	    
        restClient = RestClient.builder(new HttpHost("localhost",9200,"http"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                }).build();
        
	}
	
	@Before
	public void getRest(){
		restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build(); 
	}
	


	/**
	 * 查看api信息
	 * @throws Exception
	 */
	@Test
	public void CatApi() throws Exception{
        String method = "GET";
        String endpoint = "/_cat";
        Response response = restClient.performRequest(method,endpoint);
        System.out.println(EntityUtils.toString(response.getEntity()));
	}
	
	/**
	 * 创建索引
	 * @throws Exception
	 */
	@Test
	public void CreateIndex() throws Exception{
        String method = "PUT";
        String endpoint = "/test-index";
        Response response = restClient.performRequest(method,endpoint);
        System.out.println(EntityUtils.toString(response.getEntity()));
	}
	
	/**
	 * 创建文档
	 * @throws Exception
	 */
	@Test
	public void CreateDocument()throws Exception{

        String method = "PUT";
        String endpoint = "/test-index/test/1";
        HttpEntity entity = new NStringEntity(
                "{\n" +
                        "    \"user\" : \"kimchy\",\n" +
                        "    \"post_date\" : \"2009-11-15T14:12:12\",\n" +
                        "    \"message\" : \"trying out Elasticsearch\"\n" +
                        "}", ContentType.APPLICATION_JSON);

        Response response = restClient.performRequest(method,endpoint, Collections.<String, String>emptyMap(),entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
	}
	
	/**
	 * 获取文档
	 * @throws Exception
	 */
	@Test
	public void getDocument()throws Exception{
        String method = "GET";
        String endpoint = "/test-index/test/1";
        Response response = restClient.performRequest(method,endpoint);
        System.out.println(EntityUtils.toString(response.getEntity()));
	}
	
	
	/**
	 * 查询所有数据
	 * @throws Exception
	 */
    @Test
    public void QueryAll() throws Exception {
        String method = "POST";
        String endpoint = "/test-index/test/_search";
        HttpEntity entity = new NStringEntity("{\n" +
                "  \"query\": {\n" +
                "    \"match_all\": {}\n" +
                "  }\n" +
                "}", ContentType.APPLICATION_JSON);

        Response response = restClient.performRequest(method,endpoint,Collections.<String, String>emptyMap(),entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }
	
    /**
     * 根据ID获取
     * @throws Exception
     */
    @Test
    public void QueryByField() throws Exception {
        String method = "POST";
        String endpoint = "/test-index/test/_search";
        HttpEntity entity = new NStringEntity("{\n" +
                "  \"query\": {\n" +
                "    \"match\": {\n" +
                "      \"user\": \"kimchy\"\n" +
                "    }\n" +
                "  }\n" +
                "}", ContentType.APPLICATION_JSON);

        Response response = restClient.performRequest(method,endpoint,Collections.<String, String>emptyMap(),entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }
    
    /**
     * 更新数据
     * @throws Exception
     */
    @Test
    public void UpdateByScript() throws Exception {
        String method = "POST";
        String endpoint = "/test-index/test/1/_update";
        HttpEntity entity = new NStringEntity("{\n" +
                "  \"doc\": {\n" +
                "    \"user\":\"大美女\"\n" +
                "	}\n" +
                "}", ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(method,endpoint,Collections.<String, String>emptyMap(),entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }
    
    
    @Test
    public void GeoBoundingBox() throws IOException {
        String method = "POST";
        String endpoint = "/attractions/restaurant/_search";
        HttpEntity entity = new NStringEntity("{\n" +
                "  \"query\": {\n" +
                "    \"match_all\": {}\n" +
                "  },\n" +
                "  \"post_filter\": {\n" +
                "    \"geo_bounding_box\": {\n" +
                "      \"location\": {\n" +
                "        \"top_left\": {\n" +
                "          \"lat\": 39.990481,\n" +
                "          \"lon\": 116.277144\n" +
                "        },\n" +
                "        \"bottom_right\": {\n" +
                "          \"lat\": 39.927323,\n" +
                "          \"lon\": 116.405638\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}", ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(method,endpoint,Collections.<String, String>emptyMap(),entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }
}

完整示例: download.csdn.net/download/u0…