网站建设合同标准版/站长之家音效
Java查询ElasticSearch8.2.0文档
- 1.DSL查询文档
- 1.1.全文检索查询
- 1.2.精准查询
- 1.3.地理坐标查询
- 1.4.复合查询
- 2.排序
- 2.1.普通字段排序
- 2.2.地理坐标排序
- 3.分页
- 4.高亮
- 5.用代码查询
- 5.1. 查询所有
- 5.2.按条件查询
- 5.3.精确查询
- 5.4.组合查询
- 5.5.分页和排序查询
- 5.6.高亮显示
- 5.7.全部代码
1.DSL查询文档
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
1.1.全文检索查询
我们以查询所有为例,其中:
- 查询类型为match_all
- 没有查询条件
// 查询所有
GET /indexName/_search
{"query": {"match_all": {}}
}
其它查询无非就是查询类型、查询条件的变化。
常见的全文检索查询包括:
- match查询:单字段查询
- multi_match查询:多字段查询,任意一个字段符合条件就算符合查询条件
match查询语法如下:
GET /indexName/_search
{"query": {"match": {"FIELD": "TEXT"}}
}
mulit_match语法如下:
GET /indexName/_search
{"query": {"multi_match": {"query": "TEXT","fields": ["FIELD1", " FIELD12"]}}
}
match和multi_match的区别是什么?
- match:根据一个字段查询
- multi_match:根据多个字段查询,参与查询字段越多,查询性能越差
1.2.精准查询
精确查询一般是查找keyword、数值、日期、boolean等类型字段。所以不会对搜索条件分词。常见的有:
- term:根据词条精确值查询
- range:根据值的范围查询
因为精确查询的字段搜是不分词的字段,因此查询的条件也必须是不分词的词条。查询时,用户输入的内容跟自动值完全匹配时才认为符合条件。如果用户输入的内容过多,反而搜索不到数据。
语法说明:
// term查询
GET /indexName/_search
{"query": {"term": {"FIELD": {"value": "VALUE"}}}
}
范围查询,一般应用在对数值类型做范围过滤的时候。比如做价格范围过滤。
基本语法:
// range查询
GET /indexName/_search
{"query": {"range": {"FIELD": {"gte": 10, // 这里的gte代表大于等于,gt则代表大于"lte": 20 // lte代表小于等于,lt则代表小于}}}
}
精确查询常见的有哪些?
- term查询:根据词条精确匹配,一般搜索keyword类型、数值类型、布尔类型、日期类型字段
- range查询:根据数值范围查询,可以是数值、日期的范围
1.3.地理坐标查询
所谓的地理坐标查询,其实就是根据经纬度查询,官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-queries.html
常见的使用场景包括:
- 携程:搜索我附近的酒店
- 滴滴:搜索我附近的出租车
- 微信:搜索我附近的人
矩形范围查询,也就是geo_bounding_box查询,查询坐标落在某个矩形范围的所有文档:
查询时,需要指定矩形的左上、右下两个点的坐标,然后画出一个矩形,落在该矩形内的都是符合条件的点。
语法如下:
// 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" // 圆心}}
}
1.4.复合查询
复合(compound)查询:复合查询可以将其它简单查询组合起来,实现更复杂的搜索逻辑。常见的有两种:
- fuction score:算分函数查询,可以控制文档相关性算分,控制文档排名
- bool query:布尔查询,利用逻辑关系组合多个其它的查询,实现复杂搜索
当我们利用match查询时,文档结果会根据与搜索词条的关联度打分(_score),返回结果时按照分值降序排列。
function score 查询中包含四部分内容:
- 原始查询条件:query部分,基于这个条件搜索文档,并且基于BM25算法给文档打分,原始算分(query score)
- 过滤条件:filter部分,符合该条件的文档才会重新算分
- 算分函数:符合filter条件的文档要根据这个函数做运算,得到的函数算分(function score),有四种函数
- weight:函数结果是常量
- field_value_factor:以文档中的某个字段值作为函数结果
- random_score:以随机数作为函数结果
- script_score:自定义算分函数算法
- 运算模式:算分函数的结果、原始查询的相关性算分,两者之间的运算方式,包括:
- multiply:相乘
- replace:用function score替换query score
- 其它,例如:sum、avg、max、min
function score的运行流程如下:
- 1)根据原始条件查询搜索文档,并且计算相关性算分,称为原始算分(query score)
- 2)根据过滤条件,过滤文档
- 3)符合过滤条件的文档,基于算分函数运算,得到函数算分(function score)
- 4)将原始算分(query score)和函数算分(function score)基于运算模式做运算,得到最终结果,作为相关性算分。
因此,其中的关键点是:
- 过滤条件:决定哪些文档的算分被修改
- 算分函数:决定函数算分的算法
- 运算模式:决定最终算分结果
需求:给“如家”这个品牌的酒店排名靠前一些
翻译一下这个需求,转换为之前说的四个要点:
- 原始条件:不确定,可以任意变化
- 过滤条件:brand = “如家”
- 算分函数:可以简单粗暴,直接给固定的算分结果,weight
- 运算模式:比如求和
因此最终的DSL语句如下:
GET /hotel/_search
{"query": {"function_score": {"query": { .... }, // 原始查询,可以是任意条件"functions": [ // 算分函数{"filter": { // 满足的条件,品牌必须是如家"term": {"brand": "如家"}},"weight": 2 // 算分权重为2}],"boost_mode": "sum" // 加权模式,求和}}
}
function score query定义的三要素是什么?
- 过滤条件:哪些文档要加分
- 算分函数:如何计算function score
- 加权方式:function score 与 query score如何运算
布尔查询是一个或多个查询子句的组合,每一个子句就是一个子查询。子查询的组合方式有:
- must:必须匹配每个子查询,类似“与”
- should:选择性匹配子查询,类似“或”
- must_not:必须不匹配,不参与算分,类似“非”
- filter:必须匹配,不参与算分
需要注意的是,搜索时,参与打分的字段越多,查询的性能也越差。因此这种多条件查询时,建议这样做:
- 搜索框的关键字搜索,是全文检索查询,使用must查询,参与算分
- 其它过滤条件,采用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 } }}]}}
}
bool查询有几种逻辑关系?
- must:必须匹配的条件,可以理解为“与”
- should:选择性匹配的条件,可以理解为“或”
- must_not:必须不匹配的条件,不参与打分
- filter:必须匹配的条件,不参与打分
elasticsearch默认是根据相关度算分(_score)来排序,但是也支持自定义方式对搜索结果排序。可以排序字段类型有:keyword类型、数值类型、地理坐标类型、日期类型等。
2.排序
2.1.普通字段排序
keyword、数值、日期类型排序的语法基本一致。
语法:
GET /indexName/_search
{"query": {"match_all": {}},"sort": [{"FIELD": "desc" // 排序字段、排序方式ASC、DESC}]
}
排序条件是一个数组,也就是可以写多个排序条件。按照声明的顺序,当第一个条件相等时,再按照第二个条件排序,以此类推
2.2.地理坐标排序
地理坐标排序略有不同。
语法说明:
GET /indexName/_search
{"query": {"match_all": {}},"sort": [{"_geo_distance" : {"FIELD" : "纬度,经度", // 文档中geo_point类型的字段名、目标坐标点"order" : "asc", // 排序方式"unit" : "km" // 排序的距离单位}}]
}
这个查询的含义是:
- 指定一个坐标,作为目标点
- 计算每一个文档中,指定字段(必须是geo_point类型)的坐标 到目标点的距离是多少
- 根据距离排序
3.分页
elasticsearch 默认情况下只返回top10的数据。而如果要查询更多数据就需要修改分页参数了。elasticsearch中通过修改from、size参数来控制要返回的分页结果:
- from:从第几个文档开始
- size:总共查询几个文档
类似于mysql中的limit ?, ?
分页的基本语法如下:
GET /hotel/_search
{"query": {"match_all": {}},"from": 0, // 分页开始的位置,默认为0"size": 10, // 期望获取的文档总数"sort": [{"price": "asc"}]
}
4.高亮
高亮的语法:
GET /hotel/_search
{"query": {"match": {"FIELD": "TEXT" // 查询条件,高亮一定要使用全文检索查询}},"highlight": {"fields": { // 指定要高亮的字段"FIELD": {"pre_tags": "<em>", // 用来标记高亮字段的前置标签"post_tags": "</em>" // 用来标记高亮字段的后置标签}}}
}
注意:
- 高亮是对关键字高亮,因此搜索条件必须带有关键字,而不能是范围这样的查询。
- 默认情况下,高亮的字段,必须与搜索指定的字段一致,否则无法高亮
- 如果要对非搜索字段高亮,则需要添加一个属性:required_field_match=false
5.用代码查询
5.1. 查询所有
@Testvoid testMatchAll() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(ob -> ob.index("hotel"), HotelDoc.class);handleResponse(response);}
5.2.按条件查询
@Testvoid testMatchQuery() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(ob -> ob.index("hotel").query(q -> q.match(t -> t.field("all").query("如家"))), HotelDoc.class);response = elasticsearchClient.search(ob -> ob.index("hotel").query(q -> q.multiMatch(t -> t.fields("name", "business").query("如家"))), HotelDoc.class);handleResponse(response);}
5.3.精确查询
@Testvoid testMatchTerm() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(sr -> sr.index("hotel").query(ob -> ob.term(t -> t.field("city").value("杭州"))), HotelDoc.class);response = elasticsearchClient.search(sr -> sr.index("hotel").query(ob -> ob.range(t -> t.field("price").gte(JsonData.of(100)).lte(JsonData.of(200)))), HotelDoc.class);handleResponse(response);}
5.4.组合查询
@Testvoid testBoolMatch() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(sr -> sr.index("hotel").query(q -> q.bool(t -> t.must(ob -> ob.term(o -> o.field("city").value("上海"))).filter(ob -> ob.range(o -> o.field("price").lte(JsonData.of(250)))))), HotelDoc.class);handleResponse(response);}
5.5.分页和排序查询
@Testvoid testSortMatch() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(b -> b.index("hotel").from(0).size(10).sort(so-> so.field(ob-> ob.field("price").order(SortOrder.Asc))),HotelDoc.class);handleResponse(response);}
5.6.高亮显示
@Testvoid testHighLightMatch() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(b -> b.index("hotel").query(o -> o.match(MatchQuery.of(t -> t.field("all").query("如家")))).highlight(ob -> ob.fields("name",hf -> hf.preTags("<em>").postTags("</em>").requireFieldMatch(false))),HotelDoc.class);handleResponse(response);}
5.7.全部代码
package cn.itcast.hotel;import cn.itcast.hotel.pojo.HotelDoc;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.json.JsonData;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
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.List;
import java.util.Map;/*** @author 尹稳健~* @version 1.0* @time 2023/5/28*/
@SpringBootTest
public class HotelSearchDocumentTest {private ElasticsearchClient elasticsearchClient;@Testvoid testMatchAll() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(ob -> ob.index("hotel"), HotelDoc.class);handleResponse(response);}@Testvoid testMatchQuery() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(ob -> ob.index("hotel").query(q -> q.match(t -> t.field("all").query("如家"))), HotelDoc.class);response = elasticsearchClient.search(ob -> ob.index("hotel").query(q -> q.multiMatch(t -> t.fields("name", "business").query("如家"))), HotelDoc.class);handleResponse(response);}@Testvoid testMatchTerm() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(sr -> sr.index("hotel").query(ob -> ob.term(t -> t.field("city").value("杭州"))), HotelDoc.class);response = elasticsearchClient.search(sr -> sr.index("hotel").query(ob -> ob.range(t -> t.field("price").gte(JsonData.of(100)).lte(JsonData.of(200)))), HotelDoc.class);handleResponse(response);}@Testvoid testBoolMatch() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(sr -> sr.index("hotel").query(q -> q.bool(t -> t.must(ob -> ob.term(o -> o.field("city").value("上海"))).filter(ob -> ob.range(o -> o.field("price").lte(JsonData.of(250)))))), HotelDoc.class);handleResponse(response);}@Testvoid testSortMatch() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(b -> b.index("hotel").from(0).size(10).sort(so-> so.field(ob-> ob.field("price").order(SortOrder.Asc))),HotelDoc.class);handleResponse(response);}@Testvoid testHighLightMatch() throws IOException {SearchResponse<HotelDoc> response = elasticsearchClient.search(b -> b.index("hotel").query(o -> o.match(MatchQuery.of(t -> t.field("all").query("如家")))).highlight(ob -> ob.fields("name",hf -> hf.preTags("<em>").postTags("</em>").requireFieldMatch(false))),HotelDoc.class);handleResponse(response);}private void handleResponse(SearchResponse<HotelDoc> response) {HitsMetadata<HotelDoc> hitsMetadata = response.hits();long total = hitsMetadata.total().value();System.out.println("共搜索到" + total + "条数据");List<Hit<HotelDoc>> hits = hitsMetadata.hits();for (Hit<HotelDoc> hit : hits) {HotelDoc hotelDoc = hit.source();Map<String, List<String>> highlight = hit.highlight();if (!highlight.isEmpty()){List<String> list = highlight.get("name");String name = list.get(0);hotelDoc.setName(name);}System.out.println("hotelDoc = " + hotelDoc);}}@BeforeEachvoid setUp() {final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();Credentials creds = new UsernamePasswordCredentials("elastic", "J=9XqTBAk-2GLwd_msUx");credentialsProvider.setCredentials(AuthScope.ANY, creds);RestClient restClient = RestClient.builder(HttpHost.create("http://192.168.33.136:9200")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {@Overridepublic HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);}}).build();RestClientTransport restClientTransport = new RestClientTransport(restClient, new JacksonJsonpMapper());elasticsearchClient = new ElasticsearchClient(restClientTransport);}}