本地英文版地址: ../en/query-dsl-distance-feature-query.html
提高更接近提供的日期或坐标原点(origin)的文档的相关性评分。
例如,可以使用此查询为更接近某个日期或位置的文档赋予更多权重(越接近原点得分越高)。
可以使用 distance_feature 查询来查找距离某个位置最近的邻居。
还可以在 bool 搜索的 should 过滤器中使用该查询,将提升的相关性评分添加到 bool 查询的分数中。
要使用 distance_feature 查询,索引必须包含一个 date、date_nanos 或 geo_point 字段。
要了解如何为 distance_feature 查询设置索引,请尝试以下示例:
-
使用下面的字段映射来创建一个名为
items的索引:PUT /items { "mappings": { "properties": { "name": { "type": "keyword" }, "production_date": { "type": "date" }, "location": { "type": "geo_point" } } } } -
往这个索引中添加并索引几个文档:
PUT /items/_doc/1?refresh { "name" : "chocolate", "production_date": "2018-02-01", "location": [-71.34, 41.12] } PUT /items/_doc/2?refresh { "name" : "chocolate", "production_date": "2018-01-01", "location": [-71.3, 41.15] } PUT /items/_doc/3?refresh { "name" : "chocolate", "production_date": "2017-12-01", "location": [-71.3, 41.12] }
下面这个 bool 搜索返回字段 name 的值为 chocolate 的文档。
该搜索还使用 distance_feature 查询来增加字段 production_date 的值更接近 now(当前时间) 的文档的相关性评分。(以当前时间 now 为原点)
GET /items/_search
{
"query": {
"bool": {
"must": {
"match": {
"name": "chocolate"
}
},
"should": {
"distance_feature": {
"field": "production_date",
"pivot": "7d",
"origin": "now"
}
}
}
}
}
下面这个 bool 搜索返回字段 name 的值为 chocolate 的文档。
该搜索还使用 distance_feature 查询来增加字段 location 的值更接近地理位置坐标 [-71.3, 41.15] 的文档的相关性评分。(以该坐标为原点)
GET /items/_search
{
"query": {
"bool": {
"must": {
"match": {
"name": "chocolate"
}
},
"should": {
"distance_feature": {
"field": "location",
"pivot": "1000m",
"origin": [-71.3, 41.15]
}
}
}
}
}
-
field -
(必需, string) 用于计算距离的字段的名称。该字段必须符合以下标准:
-
必需是一个
date、date_nanos或者geo_point类型的字段 -
映射参数中的
index值必须为true(这个也是默认值) -
映射参数中的
doc_values值必须为true(这个也是默认值)
-
必需是一个
-
origin -
(必需, string) 用于计算距离的日期或地理坐标点的原点。
如果
field的值是date或date_nanos类型的字段,则origin的值必须是 date 格式。 支持 日期计算(Date Math),比如now-1h。如果
field的值是geo_point类型的字段,则origin的值必须是一个 地理位置坐标点。 -
pivot -
(必需, 时间单位 或 距离单位) 距离
origin(原点) 的距离,在该距离处相关性评分为boost值的一半。如果
field的值是date或者date_nanos格式的字段, 则pivot的值必须是 时间格式,比如1h或10d。如果
field的值是geo_point类型的字段,则pivot的值必须是 距离单位,比如1km或12m。 -
boost -
(可选, float) 用于乘以匹配文档的相关性评分的浮点数。 该值不能为负数。 默认为
1.0。
distance_feature 查询动态计算 origin 和文档字段值之间的距离。
然后,它使用这个距离作为一个特征来提高更接近原点的文档的 相关性评分。
distance_feature 查询按如下方式计算文档的相关性评分:
relevance score = boost * pivot / (pivot + distance)
distance 是 origin(原点) 和文档字段值之间的绝对差值。
与 function_score 查询或其他改变 相关性评分的方式不同,distance_feature 查询在 track_total_hits 参数不为 true 时会有效地跳过非竞争性命中。