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;
}
与我们的索引库结构 存在差异
:
- longitude和latitude需要合并为 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逐层解析: