1、application.yml

  1. server:
    port: ${port:40100}
    spring:
    application:
    name: xc-search-service
    xuecheng:
    elasticsearch:
    hostlist: ${eshostlist:127.0.0.1:9200} #多个结点中间用逗号分隔

    2ElasticSearchConfi
  1. 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();
    }

    }

    3test
  1. 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. NodeJs创建一个简单的服务器

    步骤: 1 //模块化引入 2 let http = require ("http"); 3 4 //创建服务器 5 http.createServer(function(requ ...

  2. celery ValueError: invalid literal for int() with base 10: '26379;sentinel'

    celery使用redis sentinel作为broker的时候,因为redis sentinel配置字符串格式解析报错 ValueError: invalid literal for int() ...

  3. C#环境变量配置及csc命令详解(转自cy88310)

     C#环境变量设置步骤: 在桌面右击[我的电脑]->[属性]->[高级]->[环境变量] 在下面的系统变量栏点击"新建" 变量名输入"csc" ...

  4. [atAGC052B]Tree Edges XOR

    定义两点的距离$d(x,y)$为$x$到$y$路径上边权异或和,则两棵树相同当且仅当$\forall 1\le i\le n$,$d(1,i)$相同 新建一个节点0,连边$(0,1)$,初始权值为0, ...

  5. [bzoj1576]安全路径

    先建立最短路径树(即跑dij每一个点向更新他的点连边),考虑一个点的答案路径一定要走过且仅走过一条非树边,枚举非树边(x,y),对于一个点k,如果它在x~lca上(y~lca的路径上同理),那么答案可 ...

  6. Java-ASM框架学习-修改类的字节码

    Tips: ASM使用访问者模式,学会访问者模式再看ASM更加清晰 ClassReader 用于读取字节码,父类是Object 主要作用: 分析字节码里各部分内容,如版本.字段等等 配合其他Visit ...

  7. java获取CPU核心数

    package ThreadTest; public class ThreadTest05 { public static void main(String[] args) { //获取CPU核心 S ...

  8. Java 操作符小记

    "在最底层,Java中的数据是通过使用操作符来操作的" (Thinking in Java) 1 算术操作符 Java 中的基本算术操作符和其他大多数程序设计语言是相同的.其中包括 ...

  9. salesforce零基础学习(一百零九)Lightning Login启用以及配置

    本篇参考:https://help.salesforce.com/s/articleView?id=sf.security_ll_overview.htm&type=5 我们在之前的篇中提到过 ...

  10. freeftpd的使用教程

    一.Freeftpd连接管理-黑名单.白名单 Freeftpd支持黑名单或白名单限制连接的客户端.同时只能使用其中之一.服务器通过客户端IP地址来判断是否允许其连接.其设置界面如下: 1.选择要使用白 ...