1。引入依赖

1)引入es的RestHighLevelClient依赖:

<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

2)因为SpringBoot默认的ES版本是7.6.2,所以我们需要覆盖默认的ES版本:

<properties><java.version>1.8</java.version><elasticsearch.version>7.12.1</elasticsearch.version>
</properties>

3)初始化RestHighLevelClient:

初始化的代码如下:

RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.150.101:9200")
));

2.创建索引库和删除索引库

存储的是新增索引库的语句

package cn.itcast.hotel;public class HotelConstants {public static final String MAPPING_TEMPLATE = "{\n" +"  \"mappings\": {\n" +"    \"properties\": {\n" +"      \"id\": {\n" +"        \"type\": \"keyword\"\n" +"      },\n" +"      \"name\":{\n" +"        \"type\": \"text\",\n" +"        \"analyzer\": \"ik_max_word\",\n" +"        \"copy_to\": \"all\"\n" +"      },\n" +"      \"address\":{\n" +"        \"type\": \"keyword\",\n" +"        \"index\": false\n" +"      },\n" +"      \"price\":{\n" +"        \"type\": \"integer\"\n" +"      },\n" +"      \"score\":{\n" +"        \"type\": \"integer\"\n" +"      },\n" +"      \"brand\":{\n" +"        \"type\": \"keyword\",\n" +"        \"copy_to\": \"all\"\n" +"      },\n" +"      \"city\":{\n" +"        \"type\": \"keyword\",\n" +"        \"copy_to\": \"all\"\n" +"      },\n" +"      \"starName\":{\n" +"        \"type\": \"keyword\"\n" +"      },\n" +"      \"business\":{\n" +"        \"type\": \"keyword\"\n" +"      },\n" +"      \"location\":{\n" +"        \"type\": \"geo_point\"\n" +"      },\n" +"      \"pic\":{\n" +"        \"type\": \"keyword\",\n" +"        \"index\": false\n" +"      },\n" +"      \"all\":{\n" +"        \"type\": \"text\",\n" +"        \"analyzer\": \"ik_max_word\"\n" +"      }\n" +"    }\n" +"  }\n" +"}";
}

新增和删除索引库操作

import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpPost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import java.io.IOException;@SpringBootTest
class HotelSuoYinTest {private RestHighLevelClient client;@BeforeEachvoid setup() {this.client =new RestHighLevelClient(RestClient.builder(HttpHost.create("http://101.43.94.150:9200")));}@AfterEachvoid shutdown() throws IOException {this.client.close();}
//    indices()  有这个,就是索引库的操作@Testvoid test() throws IOException {
//        创建request对象CreateIndexRequest request = new CreateIndexRequest("hotel");
//        准备请求的参数 dsl语句request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);
//        发送请求client.indices().create(request, RequestOptions.DEFAULT);}@Testvoid deltest() throws IOException {
//        创建request对象DeleteIndexRequest request = new DeleteIndexRequest("hotel");
//        发送请求client.indices().delete(request, RequestOptions.DEFAULT);}
}

判断索引库是不是存在

@Test
void testExistsHotelIndex() throws IOException {// 1.创建Request对象GetIndexRequest request = new GetIndexRequest("hotel");// 2.发送请求boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);// 3.输出System.err.println(exists ? "索引库已经存在!" : "索引库不存在!");
}

索引库操作的基本步骤:

  • 初始化RestHighLevelClient

  • 创建XxxIndexRequest。XXX是Create、Get、Delete

  • 准备DSL( Create时需要,其它是无参)

  • 发送请求。调用RestHighLevelClient#indices().xxx()方法,xxx是create、exists、delete

3.删除文档 修改文档 新增文档 批量添加文档

因为mysql查询出来的hotel信息经纬度信息是分开的,但是eleasticsearch的地理坐标要求是一个String类型,中间用逗号分开,所以要转为hotelDoc


//文档,相当于mysql中的行
//#查询一条文档(记录)的 dsl语句
//        GET /heima/_doc/1
@SpringBootTest
public class DocumentTest {private RestHighLevelClient client;@AutowiredHotelService hotelService;//    插入新数据@Testpublic void testadd() throws IOException {Hotel hotel = hotelService.getById(61083L);HotelDoc hotelDoc = new HotelDoc(hotel);
//        创建request,并指明要处理的索引是hotel,记录号是 hotelDoc.getId()IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);client.index(request, RequestOptions.DEFAULT);}//    查询某条数据@Testpublic void testquery() throws IOException {GetRequest request = new GetRequest("hotel", "61083");GetResponse response = client.get(request, RequestOptions.DEFAULT);String json = response.getSourceAsString();HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);System.out.println(hotelDoc);}//更新某条数据@Testpublic void testupdate() throws IOException {Hotel hotel = hotelService.getById(61083L);HotelDoc hotelDoc = new HotelDoc(hotel);UpdateRequest request = new UpdateRequest("hotel", "61083");request.doc("price", "952");request.doc("address", "北京饭店");client.update(request, RequestOptions.DEFAULT);}//   删除某条数据@Testvoid testDeleteDocument() throws IOException {// 1.准备RequestDeleteRequest request = new DeleteRequest("hotel", "61083");// 2.发送请求client.delete(request, RequestOptions.DEFAULT);}@Testvoid testpiliangadd() throws IOException {List<Hotel> hotels = hotelService.list();BulkRequest request = new BulkRequest();for (Hotel hotel : hotels) {HotelDoc hotelDoc = new HotelDoc(hotel);request.add(new IndexRequest("hotel").id(hotelDoc.getId() + "").source(JSON.toJSONString(hotelDoc), XContentType.JSON));}client.bulk(request, RequestOptions.DEFAULT);}@BeforeEachvoid setup() {this.client =new RestHighLevelClient(RestClient.builder(HttpHost.create("http://101.43.94.150:9200")));}@AfterEachvoid shutdown() throws IOException {this.client.close();}
}

4.查询文档

package cn.itcast.hotel;import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import java.io.IOException;
import java.util.Map;@SpringBootTest
public class QueryTest {private RestHighLevelClient client;//查询全部文档@Testvoid testmatchall() throws IOException {
//       1. 准备requestSearchRequest request = new SearchRequest("hotel");
//       2. 准备dslrequest.source().query(QueryBuilders.matchAllQuery());
//        3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);handleResponse(response);}//全文检索查询@Testvoid testquerycheck() throws IOException {
//       1. 准备requestSearchRequest request = new SearchRequest("hotel");//       2. 准备dslrequest.source().query(QueryBuilders.matchQuery("all", "如家"));
//        3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);handleResponse(response);}//boolean复合查询@Testvoid testBool() throws IOException {// 1.准备RequestSearchRequest request = new SearchRequest("hotel");// 2.准备DSL// 2.1.准备BooleanQueryBoolQueryBuilder boolQuery = QueryBuilders.boolQuery();// 2.2.添加termboolQuery.must(QueryBuilders.termQuery("city", "上海"));// 2.3.添加rangeboolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));
//        关联查询条件request.source().query(boolQuery);// 3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析响应handleResponse(response);}//查询后排序和按页查询  el的分页查询是查询所有结果之后再分页。@Testvoid testpageandsort() throws IOException {
//        页码,每页大小int pagenum = 1, pagesize = 5;// 1.准备RequestSearchRequest request = new SearchRequest("hotel");request.source().query(QueryBuilders.matchAllQuery());request.source().sort("price", SortOrder.ASC);
//       前端传过来的是页码和每页大小 ,算一下从第多少条后开始分页request.source().from((pagenum - 1) * pagesize);
//        页大小request.source().size(pagesize);// 3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析响应handleResponse(response);}//查询后高亮显示@Testvoid testhightlight() throws IOException {// 1.准备RequestSearchRequest request = new SearchRequest("hotel");request.source().query(QueryBuilders.matchQuery("brand", "如家"));
//        requireFieldMatch(false) 搜索条件brand和高亮的属性name设为不一致request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));// 3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);handleHeightLightResponse(response);}//    高亮查询private void handleHeightLightResponse(SearchResponse response) {// 4.解析响应SearchHits searchHits = response.getHits();// 4.1.获取总条数long total = searchHits.getTotalHits().value;System.out.println("共搜索到" + total + "条数据");// 4.2.文档数组SearchHit[] hits = searchHits.getHits();// 4.3.遍历for (SearchHit hit : hits) {// 获取文档sourceString json = hit.getSourceAsString();// 反序列化HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
//             获取高亮Map<String, HighlightField> highlightFields = hit.getHighlightFields();HighlightField highlightField = highlightFields.get("name");String name = highlightField.getFragments()[0].toString();hotelDoc.setName(name);System.out.println(hotelDoc);}}
// 解析响应函数private void handleResponse(SearchResponse response) {// 4.解析响应SearchHits searchHits = response.getHits();// 4.1.获取总条数long total = searchHits.getTotalHits().value;System.out.println("共搜索到" + total + "条数据");// 4.2.文档数组SearchHit[] hits = searchHits.getHits();// 4.3.遍历for (SearchHit hit : hits) {// 获取文档sourceString json = hit.getSourceAsString();// 反序列化HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
//            System.out.println("hotelDoc = " + hotelDoc);}}@BeforeEachvoid setup() {this.client =new RestHighLevelClient(RestClient.builder(HttpHost.create("http://101.43.94.150:9200")));}@AfterEachvoid shutdown() throws IOException {this.client.close();}
}

RestClient 访问elasticsearch相关推荐

  1. 通过Cerebro访问Elasticsearch

    本文以阿里云Elasticsearch为例,介绍通过Cerebro访问Elasticsearch的方法. 阿里云Elasticsearch兼容开源Elasticsearch的功能,以及Security ...

  2. Elasticsearch:创建 API key 接口访问 Elasticsearch

    在之前我的文章 "Elastic:使用Postman来访问Elastic Stack" 中我介绍了如何在应用中访问 Elasticsearch.在那里,我们使用了最基本的 Basi ...

  3. 伸缩自如的ElasticSearch——通过bboss操作和访问elasticsearch模式

    文章目录 ClientUtil 加载配置文件中的dsl来实现对es的操作模式 所有不依赖dsl的功能,或直接接收dsl模式 基本功能 配置es查询dsl 文档批量创建或者修改 http api 查询d ...

  4. Java访问Elasticsearch报错Request cannot be executed; I/O reactor status: STOPPED

    简介 使用ES过程中遇到一个Request cannot be executed; I/O reactor status: STOPPED 的异常,大概意思是和server端的连接异常终止了.开始以为 ...

  5. ElasticSearch7.2只能用localhost访问但不能用IP地址访问---ElasticSearch工作笔记027

    1.安装以后发现,在Centos7中,可以用 curl http://localhost:9200 这样来访问,但是如果通过 curl http://172.19.128.56:9200 就不能访问 ...

  6. js(jquery方式) 直接访问 elasticsearch

    尝试了下,浏览器直接通过js操作elasticsearch.这种方式无需后台服务器了,而且程序业务逻辑都在js里面,代码更新直接替换 原有js和html页面即可,快速便捷,但安全性没有任何保证. 安全 ...

  7. 微服务03 分布式搜索引擎 elasticsearch ELK kibana RestAPI 索引库 DSL查询 RestClient 黑马旅游

    分布式搜索引擎01 -- elasticsearch基础 0.学习目标 1.初识elasticsearch 1.1.了解ES 1.1.1.elasticsearch的作用 elasticsearch是 ...

  8. Elasticsearch 未授权访问漏洞验证及修复

    漏洞修复: 1.限制IP访问,禁止未授权IP访问ElasticSearch端口(默认9200). 2.通过ES插件形式来增加访问验证,需要注意增加验证后切勿使用弱口令: ①shield插件,收费,暂不 ...

  9. 【ElasticSearch】(四)—— RestClient操作ES

    目录 ​编辑 一.RestClient操作索引 环境搭建 1.导入数据 2.导入项目 3.mapping映射分析 4.初始化RestClient 1)创建索引库 1.代码解读 2.完整示例 2)删除索 ...

  10. Elasticsearch——分布式搜索引擎01(索引库、文档、RestAPI、RestClient、拼音分词器、IK分词器)

    Elasticsearch--分布式搜索引擎01(索引库.文档.RestAPI.RestClient.拼音分词器.IK分词器) 一.初识 elesticsearch 1.1 简介 1.2 倒排索引(重 ...

最新文章

  1. 2019年度最全IT吃瓜指南
  2. 10进制与16进制之间的转换 delphi
  3. Mastering the Java CLASSPATH
  4. freebsd mysql57_Freebsd7.2下Ports安装PHP5、MySql5.4、Apache22
  5. C++Opengl三维列表堆罗汉源码
  6. 闲话WPF之七(XAML的向前兼容性)
  7. 从浏览器端JavaScript代码进行服务器端日志记录
  8. 万能素材库_自媒体运营必备3款黑科技工具,一个万能素材网站,你都在用吗?...
  9. matlab单枝节匹配器,第八讲微带匹配电路单枝节匹配电路.ppt
  10. Java解析富文本rtf中文乱码
  11. w550 白屏解决办法
  12. 【端口被占用】查看占用程序,并结束占用程序、MySQL的Unable to connect to the database问题
  13. 用matplotlib高仿同花顺的K线,成交量,MACD,KDJ(一)
  14. 安徽公务员计算机专业科目真题,公务员计算机专业真题+答案安徽省考 安徽省公务员考试...
  15. 关于编程的自我介绍和规划。
  16. 怎么彻底删除SQLServer2008 卸载SQLServer200
  17. 函数的极限与连续性的关系
  18. visibilitychange关于浏览器选项卡切换事件
  19. linux中read函数读取文件夹内文件,linux下read函数
  20. 电子学——第002课:基础知识(电阻、电压、电流)

热门文章

  1. 投票程序c语言论文,c语言投票程序摘要.doc
  2. win10无法打开匿名级安全令牌_无法打开匿名级安全令牌
  3. Jmeter Ant Jenkins报告优化——jmeter.results.shanhe.me模板的response和request值为空
  4. 计算机或信息化的专业职称,信息系统项目管理师是高级职称吗?
  5. 如何用好谷歌等搜索引擎?
  6. golang幽灵蛛(pholcus)(一)
  7. 区块链浏览器构建实战
  8. Gazebo [Err] [REST.cc:205] Error in REST request 问题的解决
  9. Python爬取wfxnews 小说网站,实现批量下载小说
  10. python布尔值print_python中的用户输入布尔值