DSL查询语法
DSL Query的分类
Elasticsearch提供了基于JSON的DSL (Domain Specific Language)来定义查询。常见的查询类型包括:
- 查询所有:查询出所有数据,一般测试用。例如:match_all
- 全文检索(full text)查询:利用分词器对用户输入内容分词,然后去倒排索引库中匹配。例如:
- match_query
- multi_match_query
- 精确查询:根据精确词条值查找数据,一般是查找keyword、数值、日期、boolean等类型字段。例如:
- ids
- range
- term
- 地理(geo)查询:根据经纬度查询。例如︰
- geo_distance
- geo_bounding_box
- 复合(compound)查询:复合查询可以将上述各种查询条件组合起来,合并查询条件。例如
- bool
- function_score
DSL Query基本语法
查询的基本语法如下:
GET /indexName/_search
{
"query": {
"查询类型": {
"查询条件": "条件值"
}
}
}
//查询所有
GET /indexName/_search{
"query": {
"match_all": {
}
}
}
全文检索查询
全文检索查询,会对用户输入内容分词,常用于搜索框搜索
match查询:全文检索查询的一种,会对用户输入内容分词,然后去倒排索引库检索,语法:
GET /indexName/_search{
"query" : {
"match" : {
"FIELD": "TEXT"
}
}
}
例如:
GET /hotel/_search
{
"query": {
"match": {
"all": "外滩如家"
}
}
}
multi_match: 与match查询类似,只不过允许同时查询多个字段,语法:
GET /indexName/_search{
"query": {
"multi_match" : {
"query" : "TEXT",
"fields" :["FIELD1","FIELD12"]
}
}
}
例如:
GET /hotel/_search
{
"query": {
"multi_match": {
"query": "外滩如家",
"fields": ["brand","business","name"]
}
}
}
match和multi_match的区别是什么?
- match:根据一个字段查询
- multi_match:根据多个字段查询,参与查询字段越多,查询性能越差
精确查询
精确查询一般是查找keyword、数值、日期、boolean等类型字段。所以不会对搜索条件分词。常见的有:
- term:根据词条精确值查询
- range:根据值的范围查询
精确查询-语法
精确查询一般是根据id、数值、keyword类型、或布尔字段来查询。语法如下:
-
term查询:
// term查询 GET /indexName/_search{ "query": { "term" : { "FIELD":{ "value" : "VALUE" } } } }
例如:
GET /hotel/_search { "query": { "term": { "city": { "value": "上海" } } } }
-
range查询:
// range查询 GET /indexName/_search{ "query" : { "range" : { "FIELD": { "gte": 10, "lte": 20 } } } }
例如:
GET /hotel/_search { "query": { "range": { "price": { "gte": 100, "lte": 300 } } } }
gt:大于
gte:大于等于
地理查询
根据经纬度查询。常见的使用场景包括:
- 携程:搜索我附近的酒店
- 滴滴:搜索我附近的出租车
- 微信:搜索我附近的人
根据经纬度查询,官方文档。例如:
-
geo_bounding_box:查询geo_point值落在某个矩形范围的所有文档
//geo_bounding_box查询 GET /indexName/_search{ "query" : { "geo_bounding_box" : { "FIELD":{ "top_left" : { "lat" : 31.1, "lon": 121.5 }, "bottom_right":{ "lat": 30.9, "lon": 121.7 } } } } }
-
geo_distance:查询到指定中心点小于某个距离值的所有文档
//geo_distance查询 GET /indexName/_search{ "query" : { "geo_distance": { "distance": "15km", "FIELD": "31.21,121.5" } } }
例如:
GET /hotel/_search { "query": { "geo_distance": { "distance": "5km", "location": "31.21,121.5" } } }
复合查询
复合(compound)查询:复合查询可以将其它简单查询组合起来,实现更复杂的搜索逻辑,例如:
- fuction score:算分函数查询,可以控制文档相关性算分,控制文档排名。例如百度竞价
相关性算分
当我们利用match查询时,文档结果会根据与搜索词条的关联度打分(_score),返回结果时按照分值降序排列。例如,我们搜索"虹桥如家",结果如下:
[
{
"_score" : 17.850193,
"_source": {
"name" :"虹桥如家酒店真不错",
}
},
{
"_score" : 12.259849,
"_source" : {
"name" : "外滩如家酒店真不错",
}
},
{
"_score" :11.91091,
"_source" : {
"name" :"迪士尼如家酒店真不错",
}
}
]
T F ( 词条频率 ) = 词条出现次数 文档中词条总数 TF(词条频率)=\frac{词条出现次数}{文档中词条总数} TF(词条频率)=文档中词条总数词条出现次数
T F − I D F 算法 I D F ( 逆文档频率 ) = l o g ( 文档总数 句含词条的文档总数 ) s c o r e = ∑ i n T F ( 词条频率 ) ∗ I D F ( 逆文档频率 ) TF-IDF算法 \\ IDF(逆文档频率)= log(\frac{文档总数}{句含词条的文档总数})\\ score =\sum_{i}^{n}{TF(词条频率)*IDF(逆文档频率)} TF−IDF算法IDF(逆文档频率)=log(句含词条的文档总数文档总数)score=i∑nTF(词条频率)∗IDF(逆文档频率)
B M 25 算法 S c o r e ( Q , d ) = ∑ i n l o g ( 1 + N − n + 0.5 n + 0.5 ) ∗ f i f i + k 1 ∗ ( 1 − b + b ∗ d l a v g d l ) BM25算法\\ Score(Q,d) = \sum_i^n{log(1+\frac{N-n+0.5}{n+0.5})}*\frac{f_i}{f_i+k_1*(1-b+b*\frac{dl}{avgdl})} BM25算法Score(Q,d)=i∑nlog(1+n+0.5N−n+0.5)∗fi+k1∗(1−b+b∗avgdldl)fi
elasticsearch中的相关性打分算法是什么?
- TF-IDF:在elasticsearch5.0之前,会随着词频增加而越来越大
- BM25:在elasticsearch5.0之后,会随着词频增加而增大,但增长曲线会趋于水平
Function Score Query
使用function score query,可以修改文档的相关性算分(query score),根据新得到的算分排序。
复合查询Boolean Query
布尔查询是一个或多个查询子句的组合。子查询的组合方式有:
- must:必须匹配每个子查询,类似“与”
- should:选择性匹配子查询,类似“或”
- must_not:必须不匹配,不参与算分,类似“非”
- filter:必须匹配,不参与算分
bool查询有几种逻辑关系?
- must:必须匹配的条件,可以理解为“与”
- should:选择性匹配的条件,可以理解为“或”
- must_not:必须不匹配的条件,不参与打分
- filter:必须匹配的条件,不参与打分
搜索结果处理
排序
elasticsearch支持对搜索结果排序,默认是根据相关度算分(_score)来排序。可以排序字段类型有: keyword类型、数值类型、地理坐标类型、日期类型等。
GET /indexName /_search
{
"query " : {
"match_all":{}
},
"sort":[
{
"FIELD": "desc" //排序字段和排序方式ASC、DESC
}
]
}
GET /indexName /_search
{
"query " : {
"match_all":{}
},
"sort":[
{
"_geo_distance" : {
"FIELD" :"纬度,经度",
"order" : "asc",
"unit" : "km"
}
}
]
}
分页
elasticsearch默认情况下只返回top10的数据。而如果要查询更多数据就需要修改分页参数了。elasticsearch中通过修改from、size参数来控制要返回的分页结果:
GET /hotel/_search{
"query": {
"match_all": {}
},
"from": 990,//分页开始的位置,默认为0
"size": 10,//期望获取的文档总数
"sort":[
{"price": "asc"}
]
}
es的数据结构使得它的分页查询不是真正的的分页
深度分页问题
ES是分布式的,所以会面临深度分页问题。例如按price排序后,获取from = 990,size =10的数据:
- 首先在每个数据分片上都排序并查询前1000条文档。
- 然后将所有节点的结果聚合,在内存中重新排序选出前1000条文档
- 最后从这1000条中,选取从990开始的10条文档
如果搜索页数过深,或者结果集(from + size)越大,对内存和CPU的消耗也越高。因此ES设定结果集查询的上限是10000
深度分页解决方案
针对深度分页,ES提供了两种解决方案,官方文档:
- search after:分页时需要排序,原理是从上一次的排序值开始,查询下一页数据。官方推荐使用的方式。
- scroll:原理将排序数据形成快照,保存在内存。官方已经不推荐使用。
from + size:
-
优点:支持随机翻页
-
缺点:深度分页问题,默认查询上限( from + size)是10000
-
场景:百度、京东、谷歌、淘宝这样的随机翻页搜索
after search:
- 优点:没有查询上限(单次查询的size不超过10000)
- 缺点:只能向后逐页查询,不支持随机翻页
- 场景:没有随机翻页需求的搜索,例如手机向下滚动翻页
scroll:
- 优点:没有查询上限(单次查询的size不超过10000)
- 缺点:会有额外内存消耗,并且搜索结果是非实时的
- 场景:海量数据的获取和迁移。从ES7.1开始不推荐,建议用after search方案。
高亮
高亮:就是在搜索结果中把搜索关键字突出显示。
原理是这样的:
- 将搜索结果中的关键字用标签标记出来
- 在页面中给标签添加css样式
GET /hotel/_search{
"query" : {
"match" : {
"FIELD":"TEXT"
}
},
"highlight":{
"fields " : { //指定要高亮的字段
"FIELD":{
"pre_tags": "<em>",//用来标记高亮字段的前置标签
"post_tags": "</em>"//用来标记高亮字段的后置标签
}
}
}
}
例如:
# 高亮查询,默认情况下,ES搜索字段必须与高亮字段一致
GET /hotel/_search
{
"query": {
"match": {
"all": "如家"
}
},
"highlight": {
"fields": {
"name": {
"require_field_match": "false"
}
}
}
}
搜索结果处理整体语法:
RestClient查询文档
快速入门
查询所有
@Test
void testMatchAll() throws IOException {
// 1.准备Request
SearchRequest request = new SearchRequest("hotel");
// 2.准备DSL
request.source().query(QueryBuilders.matchAllQuery());
// 3.发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response);
}
结果解析
@Test
void testMatchAll() throws IOException {
// 1.准备Request
SearchRequest request = new SearchRequest("hotel");
// 2.准备DSL
request.source().query(QueryBuilders.matchAllQuery());
// 3.发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 4.解析结果
SearchHits searchHits = response.getHits();
// 4.1.查询的总条数
long total = searchHits.getTotalHits().value;
System.out.println("共搜索到" + total + "条数据");
// 4.2.查询的结果数组
SearchHit[] hits = searchHits.getHits();
for (SearchHit hit : hits) {
//4.3.得到source
String json = hit.getSourceAsString();
System.out.println(json);
}
}
全文检索查询
全文检索的match和multi_match查询与match_all的API基本一致。差别是查询条件,也就是query的部分。
@Test
void testMatch() throws IOException {
// 1.准备Request
SearchRequest request = new SearchRequest("hotel");
// 2.准备DSL
request.source().query(QueryBuilders.matchQuery("all", "如家"));
// 3.发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 4.解析结果
handleResponse(response);
}
- IDEA中选中一段代码后
ctrl
+alt
+M
可以将其抽取为方法
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();
for (SearchHit hit : hits) {
//4.3.得到source
String json = hit.getSourceAsString();
System.out.println(json);
}
}
精确查询
精确查询常见的有term查询和range查询,同样利用QueryBuilders实现:
//词条查询
QueryBuilders.termQuery ("city", "杭州");
//范围查询
QueryBuilders.rangeQuery("price").gte(100).lte(150);
复合查询-boolean query
GET /hotel/_search{
"query" : {
"bool" : {
"must" : [
{
"term" : { "city" :"杭州"}}
],
"filter" : [
{
"range" : {
"price": { "lte" : 250 }
}
}
]
}
}
}
可写作:
//创建布尔查询
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//添加must条件
boolQuery.must(QueryBuilders.termQuery("city", "杭州"));
//添加filter条件
boolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));
@Test
void testBool() throws IOException {
// 1.准备Request
SearchRequest request = new SearchRequest("hotel");
// 2.准备DSL
// 2.1.准备BooleanQuery
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
// 2.2.添加term
boolQuery.must(QueryBuilders.termQuery("city", "杭州"));
// 2.3.添加range
boolQuery.must(QueryBuilders.rangeQuery("price").lte(250));
request.source().query(boolQuery);
// 3.发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 4.解析结果
handleResponse(response);
}
排序和分页
搜索结果的排序和分页是与query同级的参数,对应的API如下:
@Test
void testPageAndSort() throws IOException {
//页码,每页大小
int page = 1;
int size = 5;
// 1.准备Request
SearchRequest request = new SearchRequest("hotel");
// 2.准备DSL
// 2.1.查询query
request.source().query(QueryBuilders.matchAllQuery());
// 2.2.分页from、size
request.source().from((page - 1) * size).size(5);
// 2.3.排序sort
request.source().sort("price", SortOrder.ASC);
// 3.发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 4.解析结果
handleResponse(response);
}
高亮
高亮结果解析
@Test
void testHighlight() throws IOException {
// 1.准备Request
SearchRequest request = new SearchRequest("hotel");
// 2.准备DSL
// 2.1.查询query
request.source().query(QueryBuilders.matchQuery("all", "如家"));
// 2.2.高亮highlight
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();
for (SearchHit hit : hits) {
//4.3.得到source
String json = hit.getSourceAsString();
//反序列化
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
//获取高亮结果
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
// if (!(highlightFields == null || highlightFields.size() == 0))
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);
}
}
黑马旅游案例
搜索和分页
案例1:实现黑马旅游的酒店搜索功能,完成关键字搜索和分页
先实现其中的关键字搜索功能,实现步骤如下:
- 定义实体类,接收前端请求
- 定义controller接口,接收页面请求,调用lHotelService的search方法
- 定义IHotelService中的search方法,利用match查询实现根据关键字搜索酒店信息
步骤1:定义类,接收前端请求参数
@Data
public class RequestParams {
private String key;
private Integer page;
private Integer size;
private String sortBy;
}
@Data
public class PageResult {
private Long total;
public PageResult() {
}
public PageResult(Long total, List<HotelDoc> hotels) {
this.total = total;
this.hotels = hotels;
}
private List<HotelDoc> hotels;
}
步骤2:定义controller接口,接收前端请求
定义一个HotelController,声明查询接口,满足下列要求:
- 请求方式:Post
- 请求路径:/hotel/list
- 请求参数:对象,类型为RequestParam
- 返回值: PageResult,包含两个属性
- Long total:总条数
- List hotels:酒店数据
@MapperScan("cn.itcast.hotel.mapper")
@SpringBootApplication
public class HotelDemoApplication {
public static void main(String[] args) {
SpringApplication.run(HotelDemoApplication.class, args);
}
@Bean
public RestHighLevelClient client() {
return new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.5.131:9200")));
}
}
步骤3:定义IHotelService中的search方法,利用match查询实现根据关键字搜索酒店信息
@RestController
@RequestMapping("/hotel")
public class HotelController {
@Autowired
private HotelService hotelService;
@PostMapping("/list")
public PageResult search(@RequestBody RequestParams params) {
return hotelService.search(params);
}
}
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
@Autowired
private RestHighLevelClient client;
private PageResult handleResponse(SearchResponse response) {
// 4.解析结果
SearchHits searchHits = response.getHits();
// 4.1.查询的总条数
long total = searchHits.getTotalHits().value;
// 4.2.查询的结果数组
SearchHit[] hits = searchHits.getHits();
// 4.3遍历
List<HotelDoc> hotels = new ArrayList<>();
for (SearchHit hit : hits) {
//4.3.得到source
String json = hit.getSourceAsString();
//反序列化
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
hotels.add(hotelDoc);
}
return new PageResult(total, hotels);
}
@Override
public PageResult search(RequestParams params) {
try {
//1.准备Request
SearchRequest request = new SearchRequest("hotel");
//2.准备DSL
//2.1.关键字搜索
String key = params.getKey();
if (key == null || "".equals(key)) {
request.source().query(QueryBuilders.matchAllQuery());
} else {
request.source().query(QueryBuilders.matchQuery("all", key));
}
//2.2.分页
int page = params.getPage();
int size = params.getSize();
request.source().from((page - 1) * size).size(size);
//2.3.排序
String sortBy = params.getSortBy();
if (!(sortBy == null || "".equals(sortBy))) {
request.source().sort(sortBy, SortOrder.ASC);
}
//3.发送请求,得到响应
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//4.解析响应
return handleResponse(response);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
条件过滤
案例2:添加品牌、城市、星级、价格等过滤功能
步骤:
-
修改RequestParams类,添加brand、city、starName、minPrice、maxPrice等参数
@Data public class RequestParams { private String key; private Integer page; private Integer size; private String sortBy; private String city; private Integer minPrice; private Integer maxPrice; }
-
修改search方法的实现,在关键字搜索时,如果brand等参数存在,对其做过滤
过滤条件包括:
- city精确匹配
- brand精确匹配
- starName精确匹配
- price范围过滤
注意事项:
- 多个条件之间是AND关系,组合多条件用BooleanQuery
- 参数存在才需要过滤,做好非空判断
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
@Autowired
private RestHighLevelClient client;
private PageResult handleResponse(SearchResponse response) {
// 4.解析结果
SearchHits searchHits = response.getHits();
// 4.1.查询的总条数
long total = searchHits.getTotalHits().value;
// 4.2.查询的结果数组
SearchHit[] hits = searchHits.getHits();
// 4.3遍历
List<HotelDoc> hotels = new ArrayList<>();
for (SearchHit hit : hits) {
//4.3.得到source
String json = hit.getSourceAsString();
//反序列化
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
hotels.add(hotelDoc);
}
return new PageResult(total, hotels);
}
@Override
public PageResult search(RequestParams params) {
try {
//1.准备Request
SearchRequest request = new SearchRequest("hotel");
//2.准备DSL
//2.1query
buildBasicQuery(params, request);
//2.2.分页
int page = params.getPage();
int size = params.getSize();
request.source().from((page - 1) * size).size(size);
//2.3.排序
String sortBy = params.getSortBy();
if (!(sortBy == null || "".equals(sortBy) || "default".equals(sortBy))) {
request.source().sort(sortBy, SortOrder.ASC);
}
//3.发送请求,得到响应
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//4.解析响应
return handleResponse(response);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void buildBasicQuery(RequestParams params, SearchRequest request) throws IOException {
//构建BooleanQuery
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//关键字搜索
String key = params.getKey();
if (key == null || "".equals(key)) {
boolQuery.must(QueryBuilders.matchAllQuery());
} else {
boolQuery.must(QueryBuilders.matchQuery("all", key));
}
//city精确匹配
String city = params.getCity();
if (!(city == null || "".equals(city))) {
boolQuery.filter(QueryBuilders.termQuery("city", city));
}
//brand精确匹配
String brand = params.getBrand();
if (!(brand == null || "".equals(brand))) {
boolQuery.filter(QueryBuilders.termQuery("brand", brand));
}
//startName精确查询
String startName = params.getStartName();
if (!(startName == null || "".equals(startName))) {
boolQuery.filter(QueryBuilders.termQuery("startName", startName));
}
//价格
Integer minPrice = params.getMinPrice();
Integer maxPrice = params.getMaxPrice();
if (minPrice != null && maxPrice != null) {
boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
}
request.source().query(boolQuery);
}
}
距离排序
案例3:我附近的酒店
前端页面点击定位后,会将你所在的位置发送到后台:
我们要根据这个坐标,将酒店结果按照到这个点的距离升序排序。实现思路如下:
-
修改RequestParams参数,接收location字段
@Data public class RequestParams { private String key; private Integer page; private Integer size; private String sortBy; private String brand; private String startName; private String city; private Integer minPrice; private Integer maxPrice; private String location; }
-
修改search方法业务逻辑,如果location有值,添加根据geo_distance排序的功能
@Service public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService { @Autowired private RestHighLevelClient client; private PageResult handleResponse(SearchResponse response) { // 4.解析结果 SearchHits searchHits = response.getHits(); // 4.1.查询的总条数 long total = searchHits.getTotalHits().value; // 4.2.查询的结果数组 SearchHit[] hits = searchHits.getHits(); // 4.3遍历 List<HotelDoc> hotels = new ArrayList<>(); for (SearchHit hit : hits) { //4.3.得到source String json = hit.getSourceAsString(); //反序列化 HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class); //获取排序值 Object[] sortValues = hit.getSortValues(); if (sortValues.length > 0) { Object sortValue = sortValues[0]; hotelDoc.setDistance(sortValue); } hotels.add(hotelDoc); } return new PageResult(total, hotels); } @Override public PageResult search(RequestParams params) { try { //1.准备Request SearchRequest request = new SearchRequest("hotel"); //2.准备DSL //2.1query buildBasicQuery(params, request); //2.2.分页 int page = params.getPage(); int size = params.getSize(); request.source().from((page - 1) * size).size(size); //2.3.排序 //距离 String location = params.getLocation(); if (!(location == null || "".equals(location))) { request.source().sort(SortBuilders .geoDistanceSort("location", new GeoPoint(location)) .order(SortOrder.ASC) .unit(DistanceUnit.KILOMETERS) ); } //排序方式 String sortBy = params.getSortBy(); if (!(sortBy == null || "".equals(sortBy) || "default".equals(sortBy))) { request.source().sort(sortBy, SortOrder.ASC); } //3.发送请求,得到响应 SearchResponse response = client.search(request, RequestOptions.DEFAULT); //4.解析响应 return handleResponse(response); } catch (IOException e) { throw new RuntimeException(e); } } private void buildBasicQuery(RequestParams params, SearchRequest request) throws IOException { //构建BooleanQuery BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); //关键字搜索 String key = params.getKey(); if (key == null || "".equals(key)) { boolQuery.must(QueryBuilders.matchAllQuery()); } else { boolQuery.must(QueryBuilders.matchQuery("all", key)); } //city精确匹配 String city = params.getCity(); if (!(city == null || "".equals(city))) { boolQuery.filter(QueryBuilders.termQuery("city", city)); } //brand精确匹配 String brand = params.getBrand(); if (!(brand == null || "".equals(brand))) { boolQuery.filter(QueryBuilders.termQuery("brand", brand)); } //startName精确查询 String startName = params.getStartName(); if (!(startName == null || "".equals(startName))) { boolQuery.filter(QueryBuilders.termQuery("startName", startName)); } //价格 Integer minPrice = params.getMinPrice(); Integer maxPrice = params.getMaxPrice(); if (minPrice != null && maxPrice != null) { boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice)); } request.source().query(boolQuery); } }
广告置顶
案例4:让指定的酒店在搜索结果中排名置顶
我们给需要置顶的酒店文档添加一个标记。然后利用function score给带有标记的文档增加权重。
实现步骤分析:
-
给HotelDoc类添加isAD字段,Boolean类型
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; private Object distance; private Boolean idAD;
-
挑选几个你喜欢的酒店,给它的文档数据添加isAD字段,值为true
POST /hotel/_update/1931442052 { "doc": { "isAD":true } } POST /hotel/_update/1584362548 { "doc": { "isAD":true } } POST /hotel/_update/1630005459 { "doc": { "isAD":true } } POST /hotel/_update/1880614409 { "doc": { "isAD":true } } POST /hotel/_update/1908594080 { "doc": { "isAD":true } }
-
修改search方法,添加function score功能,给isAD值为true的酒店增加权重
private void buildBasicQuery(RequestParams params, SearchRequest request) throws IOException {
//1.构建BooleanQuery
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//关键字搜索
String key = params.getKey();
if (key == null || "".equals(key)) {
boolQuery.must(QueryBuilders.matchAllQuery());
} else {
boolQuery.must(QueryBuilders.matchQuery("all", key));
}
//city精确匹配
String city = params.getCity();
if (!(city == null || "".equals(city))) {
boolQuery.filter(QueryBuilders.termQuery("city", city));
}
//brand精确匹配
String brand = params.getBrand();
if (!(brand == null || "".equals(brand))) {
boolQuery.filter(QueryBuilders.termQuery("brand", brand));
}
//startName精确查询
String startName = params.getStartName();
if (!(startName == null || "".equals(startName))) {
boolQuery.filter(QueryBuilders.termQuery("startName", startName));
}
//价格
Integer minPrice = params.getMinPrice();
Integer maxPrice = params.getMaxPrice();
if (minPrice != null && maxPrice != null) {
boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
}
//2.算分控制
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);
}