Elasticsearch安装、入门、基础API操作、全文检索、精准查询、地理查询、复合查询、排序、分页、高亮、数据聚合、自动补全、数据同步、ES集群

学习资料:

通过网盘分享的文件:Elasticsearch
链接: https://pan.baidu.com/s/18BxA0BH0G–jwy95uFmFZQ 提取码: yyds

初识ES

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

正向索引

在这里插入图片描述

倒排索引

在这里插入图片描述

在这里插入图片描述

ES与MySQL 概念对比

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

安装ES

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

操作索引库

在这里插入图片描述

mapping属性

在这里插入图片描述

在这里插入图片描述

创建索引库

在这里插入图片描述

{"mappings": {"properties": {"age": {"type": "integer"},"weight": {"type": "float"},"isMarried": {"type": "boolean"},"info": {"type": "text","analyzer": "standard"},"email": {"type": "keyword"},"score": {"type": "float"},"name": {"properties": {"firstName": {"type": "text","analyzer": "standard"},"lastName": {"type": "text","analyzer": "standard"}}}}}
}

请求es


PUT http://localhost:9200/user_info
Content-Type: application/json{"mappings": {"properties": {"age": {"type": "integer"},"weight": {"type": "float"},"isMarried": {"type": "boolean"},"info": {"type": "text","analyzer": "standard"},"email": {"type": "keyword"},"score": {"type": "float"},"name": {"properties": {"firstName": {"type": "text","analyzer": "standard"},"lastName": {"type": "text","analyzer": "standard"}}}}}
}

查看、删除索引库

在这里插入图片描述

修改索引库

在这里插入图片描述

在这里插入图片描述

操作文档

添加文档

在这里插入图片描述

查看、删除文档

在这里插入图片描述

修改文档

在这里插入图片描述

在这里插入图片描述

RestClient 操作索引库

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

初始化 RestClient

在这里插入图片描述

<properties><java.version>1.8</java.version><elasticsearch.version>7.12.1</elasticsearch.version>
</properties>
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

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.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;import java.io.IOException;public class HotelIndexTest {private RestHighLevelClient client;@BeforeEachvoid setUp() {this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.150.101:9200")));}@AfterEachvoid tearDown() throws IOException {this.client.close();}@Testvoid testInit() {System.out.println(client);}}

创建索引库

在这里插入图片描述


@Test
void createHotelIndex() throws IOException {// 1.创建Request对象CreateIndexRequest request = new CreateIndexRequest("hotel");// 2.准备请求的参数:DSL语句request.source(MAPPING_TEMPLATE, XContentType.JSON);// 3.发送请求client.indices().create(request, RequestOptions.DEFAULT);
}

在这里插入图片描述

删除索引库

删除索引库


@Test
void testDeleteHotelIndex() throws IOException {// 1.创建Request对象DeleteIndexRequest request = new DeleteIndexRequest("hotel");// 2.发送请求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 ? "索引库已经存在!" : "索引库不存在!");
}

RestClient 操作文档

初始化 RestClient

private IHotelService hotelService;private RestHighLevelClient client;@BeforeEach
void setUp() {this.client = new RestHighLevelClient (RestClient.builder (HttpHost.create ("http://192.168.111.101:9200")));
}@AfterEach
void tearDown() throws IOException {this.client.close ();
}

新增文档

新增文档

索引库 实体类

数据库查询后的结果是一个Hotel类型的对象。数据库结构如下:

@Data
@TableName("tb_hotel")
public class Hotel {@TableId(type = IdType.INPUT)private Long id;private String name;private String address;private Integer price;private Integer score;private String brand;private String city;private String starName;private String business;private String longitude;private String latitude;private String pic;
}

与我们的索引库结构 存在差异

  • longitudelatitude需要合并为 location

因此,我们需要定义一个新的类型,与索引库结构吻合:


import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
public class HotelDoc {private Long id;private String name;private String address;private Integer price;private Integer score;private String brand;private String city;private String starName;private String business;private String location;private String pic;public HotelDoc(Hotel hotel) {this.id = hotel.getId();this.name = hotel.getName();this.address = hotel.getAddress();this.price = hotel.getPrice();this.score = hotel.getScore();this.brand = hotel.getBrand();this.city = hotel.getCity();this.starName = hotel.getStarName();this.business = hotel.getBusiness();this.location = hotel.getLatitude() + ", " + hotel.getLongitude();this.pic = hotel.getPic();}
}

语法说明:

POST /{索引库名}/_doc/1
{"name": "Jack","age": 21
}

在这里插入图片描述

我们导入酒店数据,基本流程一致,但是需要考虑几点变化:

  • 酒店数据来自于数据库,我们需要 先查询出来,得到hotel对象
  • hotel对象需要转为 HotelDoc对象
  • HotelDoc需要序列化为 json格式

@Test
void testAddDocument() throws IOException {// 1.根据id查询酒店数据Hotel hotel = hotelService.getById(61083L);// 2.转换为文档类型HotelDoc hotelDoc = new HotelDoc(hotel);// 3.将HotelDoc转jsonString json = JSON.toJSONString(hotelDoc);// 1.准备Request对象IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());// 2.准备Json文档request.source(json, XContentType.JSON);// 3.发送请求client.index(request, RequestOptions.DEFAULT);
}

查询文档

查询文档

在这里插入图片描述


@Test
void testGetDocumentById() throws IOException {// 1.准备RequestGetRequest request = new GetRequest("hotel", "61083");// 2.发送请求,得到响应GetResponse response = client.get(request, RequestOptions.DEFAULT);// 3.解析响应结果String json = response.getSourceAsString();HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);System.out.println(hotelDoc);
}

删除文档

删除文档

@Test
void testDeleteDocument() throws IOException {// 1.准备RequestDeleteRequest request = new DeleteRequest("hotel", "61083");// 2.发送请求client.delete(request, RequestOptions.DEFAULT);
}

修改文档

修改文档

在这里插入图片描述


@Test
void testUpdateDocument() throws IOException {// 1.准备RequestUpdateRequest request = new UpdateRequest("hotel", "61083");// 2.准备请求参数request.doc("price", "952","starName", "四钻");// 3.发送请求client.update(request, RequestOptions.DEFAULT);
}

批量导入文档

批量导入文档

批量处理BulkRequest,其本质就是 将多个普通的CRUD请求组合在一起发送。

在这里插入图片描述

其中提供了一个add方法,用来添加其他请求:
在这里插入图片描述

可以看到,能添加的请求包括:

  • IndexRequest,也就是新增
  • UpdateRequest,也就是修改
  • DeleteRequest,也就是删除
    因此Bulk中添加了多个IndexRequest,就是批量新增功能了。示例:
    在这里插入图片描述

@Test
void testBulkRequest() throws IOException {// 批量查询酒店数据List<Hotel> hotels = hotelService.list();// 1.创建RequestBulkRequest request = new BulkRequest();// 2.准备参数,添加多个新增的Requestfor (Hotel hotel : hotels) {// 2.1.转换为文档类型HotelDocHotelDoc hotelDoc = new HotelDoc(hotel);// 2.2.创建新增文档的Request对象request.add(new IndexRequest("hotel").id(hotelDoc.getId().toString()).source(JSON.toJSONString(hotelDoc), XContentType.JSON));}// 3.发送请求client.bulk(request, RequestOptions.DEFAULT);
}

DSL 查询分类

在这里插入图片描述

查询语法基本一致

GET /indexName/_search
{"query": {"查询类型": {"查询条件": "条件值"}}
}

我们以查询所有为例,其中:

  • 查询类型为 match_all
  • 没有查询条件

// 查询所有
GET /indexName/_search
{"query": {"match_all": {}}
}

其它查询无非就是 查询类型、查询条件 的变化

全文检索

在这里插入图片描述

使用场景

全文检索查询 的基本流程如下:

  • 对 用户 搜索的内容做分词,得到词条
  • 根据 词条去倒排索引库中匹配,得到文档id
  • 根据 文档id找到文档,返回给用户

比较常用的场景包括:

  • 商城的输入框搜索
  • 百度输入框搜索

因为是 拿着词条去匹配,因此参与搜索的字段也必须是 可分词的text类型的字段

基本语法
常见的全文检索查询包括:

  • match查询:单字段查询
  • multi_match查询:多字段查询,任意一个字段符合条件就算 符合查询条件

match 查询语法如下:

GET /hotel/_search
{"query": {"match": {"brand": "7天酒店"}}
}

mulit_match 语法如下:

GET /indexName/_search
{"query": {"multi_match": {"query": "TEXT","fields": ["FIELD1", " FIELD12"]}}
}

我们将brand、name、business值都利用copy_to复制到了all字段中。因此你根据三个字段搜索,和根据all字段搜索效果当然一样

但是,搜索字段越多,对查询性能影响越大,因此建议采用copy_to,然后 单字段查询的方式
总结

match和multi_match的区别是什么?

  • match:根据一个字段查询
  • multi_match:根据多个字段查询,参与查询字段越多,查询性能越差

精准查询

在这里插入图片描述
精确查询一般是 查找keyword、数值、日期、boolean等类型字段。所以不会对搜索条件分词。常见的有:

  • term:根据 词条精确值查询
  • range:根据 值的范围查询

term 查询

// term查询
GET /hotel/_search
{"query": {"term": {"brand":"7天酒店"}}
}

range 查询

GET /hotel/_search
{"query": {"range": {"price": {"gte": 100,"lte": 200}}}
}

总结

精确查询常见的有哪些?

  • term 查询:根据 词条精确匹配,一般 搜索keyword类型、数值类型、布尔类型、日期类型字段
  • range查询:根据 数值范围查询,可以是 数值、日期的范围

地理坐标查询

在这里插入图片描述

附近查询

在这里插入图片描述

GET /hotel/_search
{"query": {"geo_distance":{"distance":"15km", "location":"31.21,121.5" }}
}

复合查询

在这里插入图片描述
复合(compound)查询:复合查询可以 将其它简单查询组合起来,实现更复杂的搜索逻辑。常见的有两种:

  • fuction score算分函数查询,可以 控制文档相关性算分,控制文档排名
  • bool query布尔查询, 利用 逻辑关系组合多个其它的查询,实现复杂搜索
    算分函数查询
    利用match查询时,文档结果会根据与搜索词条的关联度打分(_score),返回结果时 按照分值降序排列

例如,我们搜索 “虹桥如家”,结果如下:


[{"_score" : 17.850193,"_source" : {"name" : "虹桥如家酒店真不错",}},{"_score" : 12.259849,"_source" : {"name" : "外滩如家酒店真不错",}},{"_score" : 11.91091,"_source" : {"name" : "迪士尼如家酒店真不错",}}
]

语法说明
在这里插入图片描述

function score的运行流程如下:

  • 1)根据原始条件查询搜索文档,并且计算相关性算分,称为原始算分(query score)
  • 2)根据过滤条件,过滤文档
  • 3)符合过滤条件的文档,基于算分函数运算,得到函数算分(function score)
  • 4)将原始算分(query score)和函数算分(function score)基于运算模式做运算,得到最终结果,作为相关性算分。

GET /hotel/_search
{"query": {"function_score": {"query": {"match": {"all": "外滩"}},"functions": [{"filter": {"range": {"price": {"gte": 100,"lte": 300}}},"weight": 10}],"boost_mode": "avg"}}
}

在这里插入图片描述

布尔查询
布尔查询 是一个或多个查询子句的组合,每一个子句就是一个子查询。子查询的组合方式有:

  • must:必须匹配每个子查询,类似 “与”
  • should:选择性匹配子查询,类似 “或”
  • must_not:必须不匹配,不参与算分,类似 “非”
  • filter:必须匹配,不参与算分

GET /hotel/_search
{"query": {"bool": {"must": [{"term": {"city": "上海" }}],"should": [{"term": {"brand": "皇冠假日" }},{"term": {"brand": "华美达" }}],"must_not": [{ "range": { "price": { "lte": 500 } }}],"filter": [{ "range": {"score": { "gte": 45 } }}]}}
}

排序

在这里插入图片描述
单字段 排序

排序 字段、排序方式 ASC、DESC


GET /hotel/_search
{"query": {"match_all": {}},"sort": [{"price": "desc"  }]
}

多字段 排序

按照 用户评价(score ) 降序排序,评价 相同的按照价格 ( price) 升序排序


GET /hotel/_search
{"query": {"match_all": {}},"sort": [{"score": "desc"},{"price": "asc"}]
}

地理坐标排序

  • unit:排序的距离单位
  • location:目标坐标点

GET /hotel/_search
{"query": {"match_all": {}},"sort": [{"_geo_distance" : {"location": "31.21,121.5", "order" : "asc","unit" : "km" }}]
}

这个查询的含义是:

  • 指定 一个坐标,作为目标点
  • 计算 每一个文档中,指定字段(必须是geo_point类型)的坐标 到 目标点的距离是多少
  • 根据距离 升序排序

分页

在这里插入图片描述

GET /hotel/_search
{"query": {"match_all": {}},"from": 0, // 分页开始的位置,默认为0"size": 10, // 期望获取的文档总数"sort": [{"price": "asc"}]
}

深度分页:

  • search after:分页时 需要排序,原理是从上一次的排序值开始,查询下一页数据。官方推荐使用的方式

高亮

什么是高亮显示呢?

我们在百度,京东搜索时,关键字会变成红色,比较醒目,这叫高亮显示:
在这里插入图片描述

在这里插入图片描述
高亮显示的实现分为两步:

  • 1)给 文档中的所有关键字都添加一个标签,例如<em>标签
  • 2)页面给<em>标签 编写CSS样式
GET /hotel/_search
{"query": {"match": {"FIELD": "TEXT" // 查询条件,高亮一定要使用全文检索查询}},"highlight": {"fields": { // 指定要高亮的字段"FIELD": {"pre_tags": "<em>",  // 用来标记高亮字段的前置标签"post_tags": "</em>" // 用来标记高亮字段的后置标签}}}
}

实现高亮

在这里插入图片描述

GET /hotel/_search
{"query": {"match": {"all": "如家"}},"highlight": {"fields": {"name": {"require_field_match": "false"}}}
}

注意:

  • 高亮是对关键字高亮,因此搜索条件必须带有关键字,而不能是范围这样的查询。
  • 默认情况下,高亮的字段,必须与搜索指定的字段一致,否则无法高亮
  • 如果要对非搜索字段高亮,则需要添加一个属性:required_field_match=false

GET /hotel/_search
{"query": {"match": {"all": "如家酒店"}},"from": 0, "size": 20, "sort": [{"price": "asc"},{"_geo_distance": {"location": "31.21,121.5","order": "asc","unit": "km"}}], "highlight": {"fields": {"name": {"require_field_match": "false"}}}
}

数据聚合

GET /hotel/_search
{"size": 0,   // 设置size为0,结果中  不包含文档,只包含聚合结果~"aggs": {    // 定义聚合"brandAgg": {  //给聚合起个名字"terms": {   // 聚合的类型,按照品牌值聚合,所以选择term"field": "brand",   // 参与聚合的字段"size": 20    // 希望获取的聚合结果数量}}}
}

在这里插入图片描述
聚合结果排序
默认情况下,Bucket聚合会统计Bucket内的文档数量,记为_count,并且按照_count降序排序。

我们可以指定order属性,自定义聚合的排序方式:


GET /hotel/_search
{"size": 0, "aggs": {"brandAgg": {"terms": {"field": "brand","order": {"_count": "asc" // 按照_count升序排列},"size": 20}}}
}

限定聚合范围
可以限定要聚合的文档范围,只要添加query条件即可

GET /hotel/_search
{"query": {"range": {"price": {"lte": 200 // 只对200元以下的文档聚合}}}, "size": 0, "aggs": {"brandAgg": {"terms": {"field": "brand","size": 20}}}
}

在这里插入图片描述

Metric聚合语法
对酒店按照品牌分组,形成了一个个桶。现在我们需要对桶内的酒店做运算,获取每个品牌的用户评分的min、max、avg等值。

这就要用到Metric聚合了,例如stat聚合:就可以获取min、max、avg等结果。

语法如下:

GET /hotel/_search
{"size": 0, "aggs": {"brandAgg": { "terms": { "field": "brand", "size": 20},"aggs": { // 是brands聚合的子聚合,也就是 分组后对每组分别计算"score_stats": { // 聚合名称"stats": { // 聚合类型,这里stats可以计算min、max、avg等"field": "score" // 聚合字段,这里是score}}}}}
}

在这里插入图片描述

数据同步

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

使用MQ 完成数据同步

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

流程如下:

  • hotel-admin对mysql数据库数据完成增、删、改后,发送MQ消息
  • hotel-demo监听MQ,接收到消息后完成elasticsearch数据修改

<!--amqp-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

package cn.itcast.hotel.constatnts;public class MqConstants {/*** 交换机*/public final static String HOTEL_EXCHANGE = "hotel.topic";/*** 监听新增和修改的队列*/public final static String HOTEL_INSERT_QUEUE = "hotel.insert.queue";/*** 监听删除的队列*/public final static String HOTEL_DELETE_QUEUE = "hotel.delete.queue";/*** 新增或修改的RoutingKey*/public final static String HOTEL_INSERT_KEY = "hotel.insert";/*** 删除的RoutingKey*/public final static String HOTEL_DELETE_KEY = "hotel.delete";
}

package cn.itcast.hotel.config;import cn.itcast.hotel.constants.MqConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MqConfig {@Beanpublic TopicExchange topicExchange(){return new TopicExchange(MqConstants.HOTEL_EXCHANGE, true, false);}@Beanpublic Queue insertQueue(){return new Queue(MqConstants.HOTEL_INSERT_QUEUE, true);}@Beanpublic Queue deleteQueue(){return new Queue(MqConstants.HOTEL_DELETE_QUEUE, true);}@Beanpublic Binding insertQueueBinding(){return BindingBuilder.bind(insertQueue()).to(topicExchange()).with(MqConstants.HOTEL_INSERT_KEY);}@Beanpublic Binding deleteQueueBinding(){return BindingBuilder.bind(deleteQueue()).to(topicExchange()).with(MqConstants.HOTEL_DELETE_KEY);}
}

发送MQ 消息

在这里插入图片描述

接收MQ 消息


void deleteById(Long id);void insertById(Long id);

@Override
public void deleteById(Long id) {try {// 1.准备RequestDeleteRequest request = new DeleteRequest("hotel", id.toString());// 2.发送请求client.delete(request, RequestOptions.DEFAULT);} catch (IOException e) {throw new RuntimeException(e);}
}@Override
public void insertById(Long id) {try {// 0.根据id查询酒店数据Hotel hotel = getById(id);// 转换为文档类型HotelDoc hotelDoc = new HotelDoc(hotel);// 1.准备Request对象IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());// 2.准备Json文档request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);// 3.发送请求client.index(request, RequestOptions.DEFAULT);} catch (IOException e) {throw new RuntimeException(e);}
}

package cn.itcast.hotel.mq;import cn.itcast.hotel.constants.MqConstants;
import cn.itcast.hotel.service.IHotelService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class HotelListener {@Autowiredprivate IHotelService hotelService;/*** 监听酒店新增或修改的业务* @param id 酒店id*/@RabbitListener(queues = MqConstants.HOTEL_INSERT_QUEUE)public void listenHotelInsertOrUpdate(Long id){hotelService.insertById(id);}/*** 监听酒店删除的业务* @param id 酒店id*/@RabbitListener(queues = MqConstants.HOTEL_DELETE_QUEUE)public void listenHotelDelete(Long id){hotelService.deleteById(id);}
}

ES 集群

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

RestClient查询文档

发起查询请求

在这里插入图片描述
这里关键的API有两个,一个是request.source(),其中包含了查询、排序、分页、高亮等所有功能:
在这里插入图片描述
另一个是QueryBuilders,其中包含match、term、function_score、bool等各种查询:
在这里插入图片描述

解析响应

一层一层地解析

在这里插入图片描述
Elasticsearch返回的结果是一个 JSON字符串,结构包含:

  • hits:命中的结果
    • total:总条数,其中的value是具体的总条数值
    • max_score:所有结果中得分最高的文档的相关性算分
    • hits:搜索结果的文档数组,其中的每个文档都是一个json对象
      • _source:文档中的原始数据,也是json对象

因此,我们解析响应结果,就是逐层解析JSON字符串,流程如下:

  • SearchHits:通过response.getHits()获取,就是JSON中的最外层的hits,代表命中的结果
    • SearchHits#getTotalHits().value:获取总条数信息
    • SearchHits#getHits():获取SearchHit数组,也就是文档数组
      • SearchHit#getSourceAsString():获取文档结果中的_source,也就是原始的json文档数据
@Test
void testMatchAll() throws IOException {// 1.准备RequestSearchRequest request = new SearchRequest("hotel");// 2.准备DSLrequest.source().query(QueryBuilders.matchAllQuery());// 3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析响应handleResponse(response);
}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);}
}

match查询

@Test
void testMatch() throws IOException {// 1.准备RequestSearchRequest request = new SearchRequest("hotel");// 2.准备DSLrequest.source().query(QueryBuilders.matchQuery("all", "如家"));// 3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析响应handleResponse(response);}

精确查询

精确查询主要是两者:

  • term:词条精确匹配
  • range:范围查询

与之前的查询相比,差异同样在查询条件,其它都一样。

查询条件构造的API如下:
在这里插入图片描述

布尔查询

@Test
void 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);}

排序、分页

排序和分页是与query同级的参数,因此同样是使用 request.source() 来设置。
在这里插入图片描述

@Test
void testPageAndSort() throws IOException {// 页码,每页大小int page = 1, size = 5;// 1.准备RequestSearchRequest request = new SearchRequest("hotel");// 2.准备DSL// 2.1.queryrequest.source().query(QueryBuilders.matchAllQuery());// 2.2.排序 sortrequest.source().sort("price", SortOrder.ASCENDING);// 2.3.分页 from、sizerequest.source().from((page - 1) * size).size(5);// 3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析响应handleResponse(response);}

距离排序

在这里插入图片描述

if (location != null && !location.equals ("")) {request.source ().sort (SortBuilders.geoDistanceSort ("location", new GeoPoint (location)).order (SortOrder.ASCENDING).unit (DistanceUnit.KILOMETERS));
}

高亮

高亮请求构建

  • 查询的DSL:其中除了查询条件,还需要添加高亮条件,同样是与query同级。
  • 结果解析:结果除了要解析 _source 文档数据,还要解析高亮结果
    在这里插入图片描述
@Test
void testHighlight() throws IOException {// 1.准备RequestSearchRequest request = new SearchRequest ("hotel");// 2.准备DSL// 2.1.queryrequest.source ().query (QueryBuilders.matchQuery ("all", "如家"));// 2.2.高亮request.source ().highlighter (new HighlightBuilder ().field ("name").requireFieldMatch (false));// 3.发送请求SearchResponse response = client.search (request, RequestOptions.DEFAULT);// 4.解析响应handleResponse (response);}

高亮结果解析

在这里插入图片描述

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);// 获取高亮结果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);}
}

算分查询

在这里插入图片描述

// 算分控制
FunctionScoreQueryBuilder functionScoreQuery =QueryBuilders.functionScoreQuery(// 原始查询,相关性算分的查询boolQuery,// function score的数组new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{// 其中的一个function score 元素new FunctionScoreQueryBuilder.FilterFunctionBuilder(// 过滤条件QueryBuilders.termQuery("isAD", true),// 算分函数ScoreFunctionBuilders.weightFactorFunction(10))});
request.source().query(functionScoreQuery);

RestAPI实现聚合

聚合条件与query条件同级别,因此需要使用request.source()来指定聚合条件。
在这里插入图片描述
聚合的结果也与查询结果不同,API也比较特殊。不过同样是 JSON逐层解析:
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.tpcf.cn/diannao/90966.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

教程:如何查看浏览器扩展程序的源码

在学习前端、自动化或扩展开发时&#xff0c;我们常常会想研究某个浏览器插件的实现逻辑。即使扩展没有公开源码&#xff0c;只要我们本地安装了它&#xff0c;就可以查看它的完整源代码进行学习。✅ 方法一&#xff1a;从浏览器插件目录提取源码 第一步&#xff1a;打开扩展程…

虚拟储能与分布式光伏协同优化:新型电力系统的灵活性解决方案

安科瑞顾强摘要&#xff1a; 在全球能源结构向低碳化、智能化加速转型的背景下&#xff0c;分布式光伏的大规模接入为电力系统带来机遇的同时&#xff0c;也因其波动性与间歇性带来了运行挑战。本文聚焦于虚拟储能系统&#xff08;Virtual Energy Storage System, VESS&#xf…

java valueOf方法

一,什么是valueOf方法?valueOf是java包装类(比如Long,Integer等)中提供的一个静态方法二,valueOf的主要作用是什么主要作用是将其他类型的数据转换为当前包装类的对象三,代码实例:咱们以Long.valueOf为例,1,他可以接受一个long类型的数值,返回对应的Long对象(把基本类型long包…

工业平板电脑 vs 消费级平板:从防护等级到使用寿命全方面对比

平板电脑已经广泛应用于各个行业。但你知道吗&#xff1f;市面上常见的“平板”其实可以分为两大类&#xff1a;工业平板电脑和消费级平板电脑。虽然它们看起来都是“平板”&#xff0c;但用途、性能和适用场景却大不相同。今天&#xff0c;我们就来聊聊这两者的区别&#xff0…

MySQL技术笔记-索引+慢 SQL+锁 全链路优化实战

目录 前言 MySQL索引 一、概述 二、索引分类 &#xff08;一&#xff09;按功能特性分类 &#xff08;二&#xff09;按存储方式分类 &#xff08;三&#xff09;按数据结构分类 &#xff08;四&#xff09;按索引字段数量分类 三、索引的优缺点 &#xff08;一&…

S7-1200 与 S7-300 PNS7-400 PN UDP 通信 TIA 相同项目

7-1200 与 S7-300 PN/S7-400 PN UDP 通信 TIA 相同项目S7-1200 与 S7-300 PN 口之间的以太网通信可以通过 UDP 协议来实现&#xff0c;使用的通信指令是在双方 CPU 调用通信-开放式用户通信TSEND_C&#xff0c;TRCV_C&#xff08;1200支持&#xff0c;300不支持&#xff09;或T…

java进阶(二)+学习笔记

面向对象设计原则1. 面向对象概念面向对象 是一种编程思想&#xff0c;面向过程是关注实现的步骤&#xff0c;每个步骤定义一个函数&#xff0c;调用函数执行即可。面向对象关注的是谁(对象)来执行&#xff0c; 把具有相同属性和行为的一类事物(对象)进行抽象成类&#…

[附源码+数据库+毕业论]基于Spring Boot+mysql+vue结合内容推荐算法的学生咨询系统

摘要 随着互联网的普及&#xff0c;学生在学习和生活中面临着海量信息&#xff0c;如何高效获取有价值的内容成为亟待解决的问题。本文基于 Spring Boot 框架&#xff0c;结合内容推荐算法&#xff0c;设计并实现了一个学生咨询系统。系统采用 Spring Boot MyBatis MySQL Vu…

DeepSeek 微调实践:DeepSeek-R1 大模型基于 MS-Swift 框架部署 / 推理 / 微调实践大全

注&#xff1a;此文章内容均节选自充电了么创始人&#xff0c;CEO兼CTO陈敬雷老师的新书《GPT多模态大模型与AI Agent智能体》&#xff08;跟我一起学人工智能&#xff09;【陈敬雷编著】【清华大学出版社】 GPT多模态大模型与AI Agent智能体书籍本章配套视频课程【陈敬雷】 文…

python基础知识pip配置pip.conf文件

pip.conf一、 INI格式二、 级别三、 文件位置四、 加载顺序五、 常用一、 INI格式 配置文件可以更改pip命令行选项的默认值&#xff0c;这个文件是使用INI格式编写的。 INI格式 主要包含三个内容&#xff1a;1.节section 2.键值对 3.注释 [section1] key1 value1 \\注释 key2…

深入理解 Java JVM

文章目录&#x1f4d5;1. JVM简介&#x1f4d5;2. JVM运行流程&#x1f4d5;3. JVM运行时数据区&#x1f4d5;4. JVM类加载✏️4.1 类加载过程✏️4.2 双亲委派模型✏️4.3 破坏双亲委派模型&#x1f4d5;5. JVM垃圾回收机制&#xff08;GC机制&#xff09;✏️5.1 判断死亡对象…

Linux内核高效之道:Slab分配器与task_struct缓存管理

前言 在Linux内核中&#xff0c;进程创建与销毁是最频繁的操作之一。想象一下&#xff1a;当系统每秒需要处理成百上千次fork()和exit()调用时&#xff0c;如何保证task_struct&#xff08;进程描述符&#xff09;的分配与释放既快速又不产生内存碎片&#xff1f;这就是Slab分配…

双esp8266-01之间UDP透传传输,自定义协议

使用AT模式的透传&#xff0c;串口打印的数据包含pd1,4,数据打印的数据不是直接将数据打印出来&#xff0c;包含了pd1,4,特殊字符&#xff0c;针对想要直接开机直接透传&#xff0c;打印数据且按照自主协议帧头的功能进行开发。1.server程序&#xff1a;/*************SERVER**…

BGP 路由优选属性(7)【MED】官方考试综合实验题【bgp】【acl】【ip-prefix】【route-policy】【icmp 环路】精讲

目录 一、MED 属性介绍 二、实验 2.1 实验目的 2.2 拓扑图 2.2 实验说明 2.3 配置脚本 2.4 验证配置 2.5 问题分析 2.7 题目需求解析 2.8 场景 1&#xff1a;只允许在 AS12 上操作 2.9 场景 2&#xff1a;只允许在 AS34 上操作 正文 一、MED 属性介绍 MED 全称 mu…

html-初级标签

一.浏览器能识别的标签 1.1 head标签里的编码和title <head><meta charset"UTF-8"><title>Title</title> </head>1.2 标题 <body><h1>Welcome to my website</h1><h2>Welcome to my website</h2><…

【八股消消乐】Kafka集群 full GC 解决方案

&#x1f60a;你好&#xff0c;我是小航&#xff0c;一个正在变秃、变强的文艺倾年。 &#x1f514;本专栏《八股消消乐》旨在记录个人所背的八股文&#xff0c;包括Java/Go开发、Vue开发、系统架构、大模型开发、具身智能、机器学习、深度学习、力扣算法等相关知识点&#xff…

《Java Web程序设计》实验报告二 学习使用HTML标签、表格、表单

目 录 一、实验目的 二、实验环境 三、实验步骤和内容 1、小组成员分工&#xff08;共计4人&#xff09; 2、实验方案 3、实验结果与分析 4、项目任务评价 四、遇到的问题和解决方法 五、实验总结 一、实验目的 1、HTML基础知识、基本概念 2、使用HTML标签、表格进行…

jenkins使用Jenkinsfile部署springboot+docker项目

文章目录前言一、前期准备二、编辑构建文件二、Jenkins构建总结前言 前面使用Jenkinsfile部署了前端vue项目&#xff0c;接着学习Jenkinsfile部署springboot项目。 一、前期准备 已经安装好centos,并且安装了jenkins和docker。本地新建springboot并上传到gitee上。 二、编辑…

使用ESM3蛋白质语言模型进行快速大规模结构预测

文章目录ESM3介绍ESM3在线使用本地使用api批量预测ESM相较于AlphaFold的优势ESM3介绍 ESM3是由EvolutionaryScale&#xff08;前Meta团队&#xff09;开发的一款蛋白质大语言模型&#xff0c;于2025年以《用语言模型模拟 5 亿年的进化》为题正式发表在Science上 文章链接: htt…

PostgreSQL 时间/日期管理详解

PostgreSQL 时间/日期管理详解 引言 PostgreSQL是一款功能强大的开源关系型数据库管理系统&#xff0c;在时间/日期管理方面具有独特的优势。本文将详细介绍PostgreSQL中时间/日期数据类型及其相关功能&#xff0c;帮助读者更好地理解和应用时间/日期管理。 时间/日期数据类型 …