springBoot配置elasticsearch搜索


1、本地安裝elasticsearch服務,具體過程見上一篇文章(安裝和配置elasticsearch服務集群)

2、修改項目中pom文件,引入搜索相關jar包

<!-- elasticsearch相關jar包開始 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
	</dependency>
     <!-- 鏈接數據庫用的jar包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- elasticsearch相關jar包結束 -->

2、在application.yml文件中添加elasticsearch配置信息

spring: 
  #elasticsearch配置
data:
elasticsearch: #ElasticsearchProperties
cluster-name: elastic #默認為elasticsearh
cluster-nodes: 192.168.97.88:9300,192.168.97.88:9301 #配置es節點信息,逗號分隔,如果沒有指定,則啟動ClientNode

  

3、編寫elasticsearch操作的相關類

  (1)、獲取elasticsearch客戶端

//獲取elasticsearch客戶端
String hostName = "192.168.97.88" ; //本地elasticsearch的yml配置文件中寫的IP地址
Integer port = 9200 ; //遠程鏈接的端口號為9200
RestClient restClient = RestClient.builder(new HttpHost(hostName, port)).build();
/*
//如果想要獲取阿里雲上的elasticsearch客戶端,代碼如下
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("阿里雲elasticsearch用戶名", "阿里雲elasticsearch密碼"));
RestClient restClient = RestClient.builder(new HttpHost("阿里雲elasticsearch的ip", 9200))
                       .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                          @Override
                          public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                              return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                          }
                      }).setMaxRetryTimeoutMillis(5 * 60 * 1000)  //設置超時時間
                   .build();
*/

  

  (2)、查看索引是否存在 (索引必須為全小寫)

//查看 demoIndex 索引是否存在
Response isExist = restClient.performRequest("HEAD","/demoindex" , Collections.<String, String>emptyMap());
System.out.println(isExist.getStatusLine().getStatusCode());

  (3)、索引不存在,創建索引

//查看 demoIndex 索引是否存在
Response isExist = restClient.performRequest("HEAD","/demoindex" , Collections.<String, String>emptyMap());
int status = isExist.getStatusLine().getStatusCode();
if( status == 404){
    //不存在索引,創建索引
    String method = "PUT";
    String endpoint = "demoindex";
    Response response = restClient.performRequest(method, "/" + endpoint);
    System.out.println(EntityUtils.toString(response.getEntity()));
}

  (4)、索引已經創建存在,我們接下來進行索引的  增刪改查  操作

       ①、新增索引數據

//手動拼寫一個符合要求的json串   json串的格式為:{"field1":"value1","field2":"value2"}
String json = "{" +
     "\"user\":\"kimchy\"," +
     "\"postDate\":\"2013-01-30\"," +
     "\"message\":\"trying out Elasticsearch\"" +
     "}";
HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON);
//發送一個請求,將json轉換的實體發送到es,並常見索引,索引主鍵id=1
Response indexResponse = restClient.performRequest(
       "PUT",
       "/" + "demoindex" + "/" + "demoindex" + "/1",
       Collections.<String, String>emptyMap(),
       entity);
//獲取結果中的實體,查看是否新增成功
System.out.println(EntityUtils.toString(indexResponse.getEntity()));

  得到如下結果圖,表示成功

  

       ②、批量新增索引數據 ( bulk )

//批量添加索引數據
//手動拼寫一個符合要求的json串
// json串的格式為:
// { "index" : { "_id" : "1" }}   //這里為手動賦值id,也可以{ "index" : { }}為es自動設置id   id相同時后添加的數據會覆蓋之前添加的數據
// {"field1":"value1","field2":"value2"}
// { "index" : { "_id" : "2" }}
// {"field1":"value1","field2":"value2"}
String json = "{ \"index\" : { \"_id\" : \"1\" }} \n" +
        "{" +
        "\"user\":\"kimchy1\"," +
        "\"postDate\":\"2013-01-30\"," +
        "\"message\":\"trying out Elasticsearch1\"" +
        "} \n";  //一定要加換行
json += "{ \"index\" : { \"_id\" : \"2\" }} \n" +
        "{" +
        "\"user\":\"kimchy2\"," +
        "\"postDate\":\"2014-01-30\"," +
        "\"message\":\"trying out Elasticsearch2\"" +
        "}";
//將字符串轉換成http實體
HttpEntity entity = new NStringEntity(json,ContentType.APPLICATION_JSON);
//發送請求,並的到處理結果
Response response = restClient.performRequest("POST","/demoindex/demoindex/_bulk",Collections.singletonMap("pretty","true"),entity);
//獲取結果中的實體,查看是否新增成功
System.out.println(EntityUtils.toString(response.getEntity()));

  得到如下結果圖,則表示批量插入成功;若紅框裱起來的位置為update表示修改成功

  

       ③、修改單個索引時去執行插入單個索引,將主鍵id設置為需要更改的索引id即可

       ④、刪除指定索引

//刪除指定id索引
Response deleteResponse = restClient.performRequest(
        "DELETE",
        "/demoindex/demoindex/3", //刪除id為 3 的索引
        Collections.<String, String>emptyMap());
System.out.println(EntityUtils.toString(deleteResponse.getEntity()));

  得到如下結果,表示刪除成功

  ⑤、根據屬性來刪除對應索引

//根據屬性值來刪除索引
//刪除user="kimchy2"的索引
String queryString = "{\n" +
        "  \"query\": {\n" +
        "\"match_phrase\":  {\"user\": \"kimchy2\"}\n" +
        "}\n" +
        "}\n";
HttpEntity entity = new NStringEntity(queryString, ContentType.APPLICATION_JSON);
Response deleteResponse = restClient.performRequest(
        "POST",
        "/demoindex/demoindex/_delete_by_query",
        Collections.<String, String>emptyMap(),entity);
System.out.println((EntityUtils.toString(deleteResponse.getEntity())));

  得到如下結果圖表示刪除成功

  ⑥、刪除所有索引數據

//刪除所有索引數據
String queryString = "";
queryString = "{\n" +
        "  \"query\": {\n" +
        "\"match_all\":  {}\n" +
        "}\n" +
        "}\n";
HttpEntity entity = new NStringEntity(queryString, ContentType.APPLICATION_JSON);
Response deleteResponse = restClient.performRequest(
        "POST",
        "/demoindex/demoindex/_delete_by_query",
        Collections.<String, String>emptyMap(),entity);
System.out.println(EntityUtils.toString(deleteResponse.getEntity()));

  ⑦、搜索索引中的數據

//查詢索引數據
String queryStr = "{ \n" +
                      "\"query\" : { \n" +
                           "\"match_phrase\": { \"user\": { \"query\" : \"kimchy1\", \"boost\" :\"5\" }}}\n" +
                      "}\n" +
                  "}";
HttpEntity entity = new NStringEntity(queryStr, ContentType.APPLICATION_JSON);
Response response = restClient.performRequest("GET", "/demoindex/demoindex/" + "_search",Collections.singletonMap("pretty", "true"),entity);
System.out.println(EntityUtils.toString(response.getEntity()));

  得到查詢結果

 

    有關更多查詢匹配方式請看下一篇文章


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM