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

ES在项目中的测试的更多相关文章

  1. 读取另一个项目中方法的json

    A项目中的被调用方法: public class Eg1Action { public void save(){        write("{\"state\":1,\ ...

  2. 03_Android项目中读写文本文件的代码

    编写一下Android界面的项目 使用默认的Android清单文件 <?xml version="1.0" encoding="utf-8"?> & ...

  3. 如何在MVC_WebAPI项目中的APIController帮助页面添加Web测试工具测试

    本文转载自:http://www.cnblogs.com/pmars/p/3673811.html 先看效果图: 以下是原文: 如何在帮助页面添加测试工具 上一篇我在ASP.NET里面添加了一个Hel ...

  4. Atitit.mybatis的测试  以及spring与mybatis在本项目中的集成配置说明

    Atitit.mybatis的测试  以及spring与mybatis在本项目中的集成配置说明 1.1. Mybatis invoke1 1.2. Spring的数据源配置2 1.3. Mybatis ...

  5. web项目中 集合Spring&使用junit4测试Spring

    web项目中 集合Spring 问题: 如果将 ApplicationContext applicationContext = new ClassPathXmlApplicationContext(& ...

  6. JUnit测试工具在项目中的用法

    0:33 2013/6/26 三大框架整合时为什么要对项目进行junit测试: |__目的是测试配置文件对不对,能跑通就可以进行开发了 具体测试步骤: |__1.对hibernate进行测试 配置hi ...

  7. itest 开源测试管理项目中封装的下拉列表小组件:实现下拉列表使用者前后端0行代码

    导读: 主要从4个方面来阐述,1:背景:2:思路:3:代码实现:4:使用 一:封装背景       像easy ui 之类的纯前端组件,也有下拉列表组件,但是使用的时候,每个下拉列表,要配一个URL ...

  8. 【IDEA】单元测试:项目中引入JUnit测试框架+Mock简单了解

    一.Junit 使用和说明: 参考:单元测试第三弹--使用JUnit进行单元测试-HollisChuang's Blog http://www.hollischuang.com/archives/17 ...

  9. flask中的session cookie 测试 和 项目中的用户状态保持

    # -*- coding:utf-8 -*- # Author: json_steve from flask import Flask, current_app, make_response, req ...

随机推荐

  1. SQL告警,执行时间长?教你写一手好 SQL !

    博主(编码砖家)负责的项目主要采用阿里云数据库MySQL,最近频繁出现慢SQL告警,执行时间最长的竟然高达5分钟.导出日志后分析,主要原因竟然是没有命中索引和没有分页处理 . 其实这是非常低级的错误, ...

  2. python与C结构体之间二进制数据转换

    python与C结构体之间数据转换 前言 在实际应用中,可能会遇到直接和C进行二进制字节流协议通信,这时要把数据解包成python数据,如果可能,最好与C定义的结构体完全对应上. python中有2种 ...

  3. Part 61 to 63 Talking about partial class and partial method in C#

    部分类和部分方法 部分类是用partial声明的类,它允许我们把一个类分割成两个或多个类,当应用程序编译的完成的时候,多个部分类会结合成一个类,同时partial关键字也可以用于声明结构和接口. 那么 ...

  4. 菜鸡的Java笔记第二 - java 数据类型

    1.程序的本质实际上就是在于数据的处理上. JAVA中的数据类型有两类 基本数据类型:是进行内容的操作而不是内存的操作 数值型: 整型:byte(-128 ~ 127),short(-32768 ~ ...

  5. 单线程 Redis 为什么这么快,看看这篇就知道了

    Redis 作为一种 KV 缓存服务器,有着极高的性能,相对于 Memcache,Redis 支持更多种数据类型,因此在业界应用广泛. 记得刚毕业那会参加面试,面试官会问我 Redis 为什么快,由于 ...

  6. [hdu6595]Everything Is Generated In Equal Probability

    计算一对逆序对的贡献,即在n个数期望要删多少步才能删掉其中的两个数,设f(n)表示此时的期望,则有方程$f[n]=3/4+(\sum_{i=2}^{n}f[i]\cdot c(n-2,i-2))/2^ ...

  7. 多线程07.thread-join

    package com.wangwenjun.concurrency.chapter5; public class ThreadJoin3 { public static void main(Stri ...

  8. tomcat的log日志乱码解决方案

    Intellij idea Tomcat输出log中文乱码 配置tomcat在VM options添加-Dfile.encoding=UTF8 -Dsun.jnu.encoding=UTF8 重启后控 ...

  9. [NOIP2011 提高组] 观光公交

    考虑这类每次都有一类物品贡献相同的物品,求使用了 \(k\) 个物品的最优值,则有考虑考虑贪心. 每次找到一个车到的时间\(>\)最后一个人到的时间,那么找一个覆盖个数最大的地方使用它.

  10. 洛谷 P5206 - [WC2019]数树(集合反演+NTT)

    洛谷题面传送门 神仙多项式+组合数学题,不过还是被我自己想出来了( 首先对于两棵树 \(E_1,E_2\) 而言,为它们填上 \(1\sim y\) 使其合法的方案数显然是 \(y\) 的 \(E_1 ...