简介
官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-pinned-query.html
Pinned 查询用来提升所选文档的排名,使其高于匹配给定查询的文档。 此功能通常用于引导搜索者查找精选的文档,这些文档在搜索的任何 “organic” 匹配项之上被提升。 使用存储在_id字段中的文档 ID 来标识升级或“固定”的文档。
Pinned
首先我们使用如下的bulk API接口来把我们所需要的数据导入到Elasticsearch之中:
代码语言:javascript复制POST _bulk
{ "index" : { "_index" : "twitter", "_id": 1} }
{"user":"张三","message":"今儿天气不错啊,出去转转去","uid":2,"city":"北京","province":"北京","country":"中国","address":"中国北京市海淀区","location":{"lat":"39.970718","lon":"116.325747"}, "DOB":"1980-12-01"}
{ "index" : { "_index" : "twitter", "_id": 2 }}
{"user":"老刘","message":"出发,下一站云南!","uid":3,"city":"北京","province":"北京","country":"中国","address":"中国北京市东城区台基厂三条3号","location":{"lat":"39.904313","lon":"116.412754"}, "DOB":"1981-12-01"}
{ "index" : { "_index" : "twitter", "_id": 3} }
{"user":"李四","message":"happy birthday!","uid":4,"city":"北京","province":"北京","country":"中国","address":"中国北京市东城区","location":{"lat":"39.893801","lon":"116.408986"}, "DOB":"1982-12-01"}
{ "index" : { "_index" : "twitter", "_id": 4} }
{"user":"老贾","message":"123,gogogo","uid":5,"city":"北京","province":"北京","country":"中国","address":"中国北京市朝阳区建国门","location":{"lat":"39.718256","lon":"116.367910"}, "DOB":"1983-12-01"}
{ "index" : { "_index" : "twitter", "_id": 5} }
{"user":"老王","message":"Happy BirthDay My Friend!","uid":6,"city":"北京","province":"北京","country":"中国","address":"中国北京市朝阳区国贸","location":{"lat":"39.918256","lon":"116.467910"}, "DOB":"1984-12-01"}
{ "index" : { "_index" : "twitter", "_id": 6} }
{"user":"老吴","message":"好友来了都今天我生日,好友来了,什么 birthday happy 就成!","uid":7,"city":"上海","province":"上海","country":"中国","address":"中国上海市闵行区","location":{"lat":"31.175927","lon":"121.383328"}, "DOB":"1985-12-01"}
普通搜索
首先我们来做一个正常的搜索,比如寻找所有在北京的文档:
代码语言:javascript复制GET twitter/_search
{
"query": {
"match": {
"city.keyword": "北京"
}
}
}
我们可以看出来共有5条数据结果,它们的_id分别是从1到5。
那么现在的问题是:如果我想把_id为4和5的那两个文档排在查询的最前面,那么我们该如何来做呢?答案是我们是使用 pinned query。
Pinned搜索
我们可以使用如下的方式来进行查询:
代码语言:javascript复制GET twitter/_search
{
"query": {
"pinned": {
"ids": [
"4",
"5"
],
"organic": {
"match": {
"city.keyword": "北京"
}
}
}
}
}
在这一次的查询结果中,我们可以看到_id为4和5的两个文档的排名是排在最前面,它们的分数被提高了。