ES在項目中的測試


1、application.yml

server:
port: ${port:40100}
spring:
application:
name: xc-search-service
xuecheng:
elasticsearch:
hostlist: ${eshostlist:127.0.0.1:9200} #多個結點中間用逗號分隔


2、ElasticSearchConfi
package com.xuecheng.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* @author Administrator
* @version 1.0
**/
@Configuration
public class ElasticsearchConfig {

@Value("${xuecheng.elasticsearch.hostlist}")
private String hostlist;

@Bean
public RestHighLevelClient restHighLevelClient(){
//解析hostlist配置信息
String[] split = hostlist.split(",");
//創建HttpHost數組,其中存放es主機和端口的配置信息
HttpHost[] httpHostArray = new HttpHost[split.length];
for(int i=0;i<split.length;i++){
String item = split[i];
httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
}
//創建RestHighLevelClient客戶端
return new RestHighLevelClient(RestClient.builder(httpHostArray));
}

//項目主要使用RestHighLevelClient,對於低級的客戶端暫時不用
@Bean
public RestClient restClient(){
//解析hostlist配置信息
String[] split = hostlist.split(",");
//創建HttpHost數組,其中存放es主機和端口的配置信息
HttpHost[] httpHostArray = new HttpHost[split.length];
for(int i=0;i<split.length;i++){
String item = split[i];
httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
}
return RestClient.builder(httpHostArray).build();
}

}


3、test
package com.xuecheng.search;

import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author newcityman
* @date 2020/2/22 - 13:09
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestIndex {
@Autowired
RestClient restClient;
@Autowired
RestHighLevelClient restHighLevelClient;

//刪除索引庫
@Test
public void testDeleteIndex() throws IOException {
//刪除索引對象
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("xc_course");
//操作索引的客戶端
IndicesClient indices = restHighLevelClient.indices();
//執行刪除
DeleteIndexResponse delete = indices.delete(deleteIndexRequest);
//得到響應
boolean acknowledged = delete.isAcknowledged();
System.out.println(acknowledged);
}

//創建索引庫
@Test
public void testCreateIndex() throws IOException {
//創建索引對象
CreateIndexRequest createIndexRequest = new CreateIndexRequest("xc_course");
//設置參數
createIndexRequest.settings(Settings.builder().put("number_of_shards","1").put("number_of_replicas","0"));
//指定映射
createIndexRequest.mapping("doc","{\n" +
"\t\"properties\": {\n" +
"\t\t\"studymodel\": {\n" +
"\t\t\t\"type\": \"keyword\"\n" +
"\t\t},\n" +
"\t\t\"name\":{\n" +
"\t\t\t\"type\": \"keyword\"\n" +
"\t\t},\n" +
"\t\t\"description\":{\n" +
"\t\t\t\"type\":\"text\",\n" +
"\t\t\t\"analyzer\":\"ik_max_word\",\n" +
"\t\t\t\"search_analyzer\":\"ik_smart\"\n" +
"\t\t},\n" +
"\t\t\"pic\":{\n" +
"\t\t\t\"type\":\"text\",\n" +
"\t\t\t\"index\":false\n" +
"\t\t}\n" +
"\t}\n" +
"}", XContentType.JSON);
//操作索引對象
IndicesClient indices = restHighLevelClient.indices();
//執行創建
CreateIndexResponse createIndexResponse = indices.create(createIndexRequest);
//得到響應
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println(acknowledged);
}

//添加文檔
@Test
public void testAddDoc() throws IOException {
//文檔內容
//准備json數據
Map<String ,Object> jsonMap = new HashMap<>();
jsonMap.put("name","spring cloud實戰");
jsonMap.put("description","本課程主要從四個章節進行講解: 1.微服務架構入門 2.spring cloud 基礎入門 3.實戰Spring\n" +
"Boot 4.注冊中心eureka。");
jsonMap.put("studymodel","20101");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jsonMap.put("timestamp",dateFormat.format(new Date()));
jsonMap.put("price",5.6f);
//創建索引請求對象
IndexRequest indexRequest = new IndexRequest("xc_course","doc");
//添加文檔內容
indexRequest.source(jsonMap);
//通過client進行http的請求
IndexResponse indexResponse = restHighLevelClient.index(indexRequest);
//獲取響應結果
DocWriteResponse.Result result = indexResponse.getResult();
System.out.println(result);

}

//查詢文檔
@Test
public void testGetDoc() throws IOException{
//查詢請求對象
GetRequest getRequest = new GetRequest("xc_course", "doc", "QWe9a3ABx0F0ZHyZ2N5m");
//通過client發送查詢請求
GetResponse getResponse = restHighLevelClient.get(getRequest);
//得到文檔的內容
Map<String, Object> sourceAsMap = getResponse.getSource();
System.out.println(sourceAsMap);
}
}


免責聲明!

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



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