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. 大爽Python入门教程 1-4 习题

    大爽Python入门公开课教案 点击查看教程总目录 1 [思考]方向变换 小明同学站在平原上,面朝北方,向左转51次之后(每次只转90度), 小明面朝哪里?小明转过了多少圈? (360度为一圈,圈数向 ...

  2. 菜鸡的Java笔记 第三十四 Annotation

    Annotation        多例模式特点:            1. 多例类可以有多个实例            2. 多例类必须自己创建自己的实例,并管理自己的实例,和向外界提供自己的实例 ...

  3. 【linux系统】命令学习(五)linux三剑客 grep \ awk \ sed

    grep----基于正则表达式查找满足条件的行 1.内容检索 获取行 grep pattern file 获取内容 grep -o pattern file 获取上下文grep -A -B -C pa ...

  4. 生产服务GC调优实践基本流程总结

    Photo by Pixabay from Pexels 本文作者:夜色微光 - 博客园 (cnblogs.com) 前言 对Java虚拟机进行性能调优是一个非常宽泛的话题,在实践上也是非常棘手的过程 ...

  5. [atARC116F]Deque Game

    假设两个操作者分别为$A$和$B$,其中$A$希望最大.$B$希望最小 (并不默认$A$为整局游戏的先手,仅是最终的结果考虑$A$为先手时) 记第$i$个队列第$j$个元素为$a_{i,j}$(其中$ ...

  6. SpringCloud升级之路2020.0.x版-41. SpringCloudGateway 基本流程讲解(2)

    本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 我们继续分析上一节提到的 WebHandler,经过将请求封装成 ServerWebExc ...

  7. vue 3 学习笔记 (八)——provide 和 inject 用法及原理

    在父子组件传递数据时,通常使用的是 props 和 emit,父传子时,使用的是 props,如果是父组件传孙组件时,就需要先传给子组件,子组件再传给孙组件,如果多个子组件或多个孙组件使用时,就需要传 ...

  8. HTML四种定位-粘滞定位

    粘滞定位 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset=&q ...

  9. 『MdOI R1』Treequery

    我们可以思考怎么做呢. 首先我们需要进行一些分类讨论: 我们先思考一下如果所有关键点都在 \(p\) 的子树内, 那显然是所有关键点的 \(Lca\) 到 \(p\) 距离. 如果所有关键点一些在 \ ...

  10. Codeforces 1332G - No Monotone Triples(数据结构综合)

    Codeforces 题目传送门 & 洛谷题目传送门 首先打表即可发现对于任意长度 \(\ge 5\) 的序列总存在一个 Monotone triple,证明不会实在不行直接 \(5^5\) ...