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);
}
}

猜你喜欢

转载自www.cnblogs.com/newcityboy/p/12349494.html