实用篇-ES-RestClient查询文档

news/2024/7/7 5:46:57 标签: elasticsearch, 大数据, 搜索引擎

一、快速入门

上面的查询文档都是依赖kibana,在浏览器页面使用DSL语句去查询es,如何用java去查询es里面的文档(数据)呢
我们通过match_all查询来演示基本的API,注意下面演示的是 'match_all查询,也叫基础查询'
首先保证你已经做好了 '实用篇-ES-环境搭建' ,创建了名为gghotel的索引库,然后开始下面的操作。如果需要浏览器操作es,那就不需要启动kibana容器

在进行下面的操作之前,确保你已经看了前面 '实用篇-ES-RestClient操作文档' 学的 '1. RestClient案例准备',然后在进行下面的操作


第一步: 在src/test/java/cn.itcast.hotel目录新建HotelSearchTest类,写入如下

package cn.itcast.hotel;

import cn.itcast.hotel.service.IHotelService;
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.QueryBuilders;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class HotelIndexTest2 {

     private RestHighLevelClient client;

     @Autowired
     private IHotelService hotelService;

     @Test
     void init(){
          System.out.println(client);
     }

     @BeforeEach
     void setUp(){
          this.client = new RestHighLevelClient(RestClient.builder(
                  //指定你Centos7部署的es的主机地址
                  HttpHost.create("http://192.168.229.129:9200")
          ));
     }

     @AfterEach
     void tearDown() throws IOException {
          this.client.close();
     }


     @Test
     void testMatchAll() throws IOException {
          //准备Request
          SearchRequest request = new SearchRequest("hotel");
          //组织DSL参数
          request.source().query(QueryBuilders.matchAllQuery());
          //发送请求,得到响应结果
          SearchResponse response = client.search(request, RequestOptions.DEFAULT);
          System.out.println(response);
     }

}

第二步: 把控制台里面我们需要的数据解析出来。返回的数据很多,我们主要是解析hits里面的数据就行了

把HotelSearchTest类修改为如下,主要的修改是sout之前做了一次解析,拿到我们想要的数据

package cn.itcast.hotel;

import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
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.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class HotelIndexTest2 {

     private RestHighLevelClient client;

     @Autowired
     private IHotelService hotelService;

     @Test
     void init(){
          System.out.println(client);
     }

     @BeforeEach
     void setUp(){
          this.client = new RestHighLevelClient(RestClient.builder(
                  //指定你Centos7部署的es的主机地址
                  HttpHost.create("http://192.168.229.129:9200")
          ));
     }

     @AfterEach
     void tearDown() throws IOException {
          this.client.close();
     }


     @Test
     void testMatchAll() throws IOException {
          //准备Request
          SearchRequest request = new SearchRequest("hotel");
          //组织DSL参数
          request.source().query(QueryBuilders.matchAllQuery());
          //发送请求,得到响应结果
          SearchResponse response = client.search(request, RequestOptions.DEFAULT);
          //下面为逐层解析json数据
          SearchHits searchHits = response.getHits();
          long total = searchHits.getTotalHits().value;
          System.out.println("共有" + total + "条数据");
          SearchHit[] hits = searchHits.getHits();
          for (SearchHit hit : hits) {
               String json = hit.getSourceAsString();
               //反系列化
               HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
               System.out.println("hotelDoc = " + hotelDoc);
          }


     }

}

二、match的三种查询

我们刚刚在第一节演示的是 match_all(也叫基本查询) 查询,下面将演示 match(也叫单字段查询) 和 multi_match(也叫多字段查询) 查询

【match 查询,也叫单字段查询】

在HotelSearchTest类添加如下

 @Test
     void testMatch() throws IOException {
          //准备Request
          SearchRequest request = new SearchRequest("hotel");
          //组织DSL参数
          request.source().query(QueryBuilders.matchQuery("name","如家"));
          //发送请求,得到响应结果
          SearchResponse response = client.search(request, RequestOptions.DEFAULT);
          //下面为逐层解析json数据
          SearchHits searchHits = response.getHits();
          long total = searchHits.getTotalHits().value;
          System.out.println("共有" + total + "条数据");
          SearchHit[] hits = searchHits.getHits();
          for (SearchHit hit : hits) {
               String json = hit.getSourceAsString();
               //反系列化
               HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
               System.out.println("hotelDoc = " + hotelDoc);
          }
     }

【multi_match 查询,也叫多字段查询】

在HotelSearchTest类添加如下

  @Test
     void testMatch() throws IOException {
          //准备Request
          SearchRequest request = new SearchRequest("hotel");
          //组织DSL参数
          request.source().query(QueryBuilders.multiMatchQuery("如家","name","business"));
          //发送请求,得到响应结果
          SearchResponse response = client.search(request, RequestOptions.DEFAULT);
          //下面为逐层解析json数据
          SearchHits searchHits = response.getHits();
          long total = searchHits.getTotalHits().value;
          System.out.println("共有" + total + "条数据");
          SearchHit[] hits = searchHits.getHits();
          for (SearchHit hit : hits) {
               String json = hit.getSourceAsString();
               //反系列化
               HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
               System.out.println("hotelDoc = " + hotelDoc);
          }
     }

总结: 要构建查询条件,只要记住一个QueryBuilders类即可

三、解析代码的抽取

我们发现对于 match、multi_match、match_all 查询,的解析部分的代码都是相同的,所以我们可以对解析部分的代码进行抽取,如下

快捷键ctrl + alt + M

  private void handleResponse(SearchResponse response) {
          //下面为逐层解析json数据
          SearchHits searchHits = response.getHits();
          long total = searchHits.getTotalHits().value;
          System.out.println("共有" + total + "条数据");
          SearchHit[] hits = searchHits.getHits();
          for (SearchHit hit : hits) {
               String json = hit.getSourceAsString();
               //反系列化
               HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
               System.out.println("hotelDoc = " + hotelDoc);
          }
     }

之后我们在test中只专注于json的获取,解析的任务交给这段代码 

四、bool和term、rang精确查询

原理同上

我们直接演示bool复合查询 

 

 @Test
     void testBool() throws IOException {
          //准备Request
          SearchRequest request = new SearchRequest("hotel");
          //组织DSL参数
          BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
          boolQuery.must(QueryBuilders.termQuery("city","杭州"));
          boolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));
          
          request.source().query(boolQuery);
          //发送请求,得到响应结果
          SearchResponse response = client.search(request, RequestOptions.DEFAULT);
          handleResponse(response);
     }

五、排序和分页

 @Test
     void testPageAndSort() throws IOException {
          int pageNum = 1;
          int pageSize = 5;
          //准备Request
          SearchRequest request = new SearchRequest("hotel");
          //组织DSL参数
          //查询所有
          request.source().query(QueryBuilders.matchAllQuery());
          //排序
          request.source().sort("price", SortOrder.ASC);
          //分页
          request.source().from(pageNum - 1).size(pageSize);

          //发送请求,得到响应结果
          SearchResponse response = client.search(request, RequestOptions.DEFAULT);
          handleResponse(response);
     }

六、高亮显示

 高亮API包括请求DSL构建和结果解析两部分,API和对应的DSL语句如下图,下图只是构建,再下面还有解析,高亮必须由构建+解析才能实现

解析,如下图 

  @Test
     void testHighLight() throws IOException {
          //准备Request
          SearchRequest request = new SearchRequest("hotel");
          //组织DSL参数
          //查询所有
          request.source().query(QueryBuilders.matchQuery("name","如家"));
          //设置高亮匹配方式
          request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
          //发送请求,得到响应结果
          SearchResponse response = client.search(request, RequestOptions.DEFAULT);
          //下面为逐层解析json数据
          SearchHits searchHits = response.getHits();
          long total = searchHits.getTotalHits().value;
          System.out.println("共有" + total + "条数据");
          SearchHit[] hits = searchHits.getHits();
          for (SearchHit hit : hits) {
               String json = hit.getSourceAsString();
               //反系列化
               HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
              //解析,获取高亮结果
               Map<String, HighlightField> highlightFields = hit.getHighlightFields();
               if(!CollectionUtils.isEmpty(highlightFields)){
                    //根据字段名获取高亮结果
                    HighlightField highlightField = highlightFields.get("name");
                    //判断高亮字段不为空
                    if(highlightField!=null){
                         //获取高亮值
                         String name = highlightField.getFragments()[0].string();
                         //覆盖非高亮结果
                         hotelDoc.setName(name);
                    }
               }
               //最终输出
               System.out.println("hotelDoc = " + hotelDoc);
          }

     }


http://www.niftyadmin.cn/n/5187050.html

相关文章

双核电脑开200线程会崩溃吗?如何解决

双核电脑开启200线程是否会崩溃&#xff0c;这取决于多个因素&#xff0c;包括电脑的具体配置、操作系统、运行的程序以及这些线程的具体任务。理解这一点很重要&#xff0c;因为“线程”这个概念和电脑的物理核心数量并不是直接对应的。 多线程与处理器核心 首先&#xff0c…

史上最全解析:从输入 URL 到页面展示到底发生了什么?

文章目录 前言整体流程浏览器输入 url内容为搜索文本内容为 urlHSTS 预检查为什么需要 HSTS 预检查HSTS 如何解决上述问题HSTS 存在的问题 baidu.com 和 www.baidu.com 区别有何影响如何解决 根据域名查询IPDNS 查询流程DNS 迭代查询和递归查询递归查询迭代查询 浏览器向服务发…

传输层——— UDP协议

文章目录 一.传输层1.再谈端口号2.端口号范围划分3.认识知名端口号4.两个问题5.netstat与iostat6.pidof 二.UDP协议1.UDP协议格式2.UDP协议的特点3.面向数据报4.UDP的缓冲区5.UDP使用注意事项6.基于UDP的应用层协议 一.传输层 在学习HTTP等应用层协议时&#xff0c;为了便于理…

有HTTP了,为什么还要有RPC

虽然HTTP是一种常用的通信协议&#xff0c;但RPC&#xff08;Remote Procedure Call&#xff09;在某些情况下仍然有其存在的意义和优势。 性能和效率&#xff1a;相比HTTP请求&#xff0c;RPC通常具有更低的延迟和更高的性能。这是因为RPC框架通常使用了一些轻量级的、二进制的…

SpringCloud微服务:Nacos的集群、负载均衡、环境隔离

目录 集群 在user-service的yml文件配置集群 启动服务 负载均衡 order-service配置集群 设置负载均衡 当本地集群的服务挂掉时 访问权重 环境隔离 1、Nacos服务分级存储模型 一级是服务&#xff0c;例如userservice 二级是集群&#xff0c;例如杭州或上海 …

嵌套的iframe页面中rem字号变小问题处理

问题原因 如果 html 的 font-size: 100px&#xff0c;那字号为0.16rem的字实际为100px * 0.16 16px 故最外层的html的字号 与iframe下的html字号 不相同时&#xff0c;则会导致iframe页面内的字体字号存在问题 解决办法 先获取外层html的font-size const fontSize par…

vue3基础学习(上)

##以前怎么玩的? ###MVC Model:Bean View:视图 Controller ##vue的ref reactive ref:必须是简单类型 reactive:必须不能是简单类型 ###创建一个Vue项目 npm init vuelatest ###生命周期 ###setup相关 ####Vue2的一些写法 -- options API ####Vue3的写法 组合式API Vu…

以太坊功能被滥用,从99,000名受害者那里窃取了6000万美元

导语&#xff1a;最近&#xff0c;以太坊的一个功能被不法分子滥用&#xff0c;导致99,000人在六个月内损失了总计6000万美元的加密货币。这一滥用行为是通过绕过钱包安全警报和篡改加密货币地址实现的。本文将为您详细介绍这一事件的背景和影响&#xff0c;并提供一些建议&…