距离特性查询
使用 distance_feature
查询来提高与特定日期或地理点更近的文档的相关性。这有助于您在搜索结果中优先显示更新或附近的内容。例如,您可以为最近制造的产品分配更多权重,或提升距离用户指定位置最近的商品。
您可以将此查询应用于包含日期或位置数据的字段。它通常与 bool
查询的 should
子句一起使用,以在不过滤结果的情况下提高相关性评分。
配置索引
在使用 distance_feature
查询之前,请确保您的索引包含以下至少一种字段类型:
在此示例中,您将配置 opening_date
和 coordinates
字段,您可以使用它们运行距离特性查询。
PUT /stores
{
"mappings": {
"properties": {
"opening_date": {
"type": "date"
},
"coordinates": {
"type": "geo_point"
}
}
}
}
向索引添加示例文档
PUT /stores/_doc/1
{
"store_name": "Green Market",
"opening_date": "2025-03-10",
"coordinates": [74.00, 40.70]
}
PUT /stores/_doc/2
{
"store_name": "Fresh Foods",
"opening_date": "2025-04-01",
"coordinates": [73.98, 40.75]
}
PUT /stores/_doc/3
{
"store_name": "City Organics",
"opening_date": "2021-04-20",
"coordinates": [74.02, 40.68]
}
示例:基于近时性提升评分
以下查询搜索 store_name
匹配 market
的文档,并提升最近开业商店的评分。
GET /stores/_search
{
"query": {
"bool": {
"must": {
"match": {
"store_name": "market"
}
},
"should": {
"distance_feature": {
"field": "opening_date",
"origin": "2025-04-07",
"pivot": "10d"
}
}
}
}
}
响应包含匹配的文档
{
"took": 4,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.2372394,
"hits": [
{
"_index": "stores",
"_id": "1",
"_score": 1.2372394,
"_source": {
"store_name": "Green Market",
"opening_date": "2025-03-10",
"coordinates": [
74,
40.7
]
}
}
]
}
}
示例:基于地理邻近性提升评分
以下查询搜索 store_name
匹配 market
的文档,并提升距离给定原点更近的结果的评分。
GET /stores/_search
{
"query": {
"bool": {
"must": {
"match": {
"store_name": "market"
}
},
"should": {
"distance_feature": {
"field": "coordinates",
"origin": [74.00, 40.71],
"pivot": "500m"
}
}
}
}
}
响应包含匹配的文档
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.2910118,
"hits": [
{
"_index": "stores",
"_id": "1",
"_score": 1.2910118,
"_source": {
"store_name": "Green Market",
"opening_date": "2025-03-10",
"coordinates": [
74,
40.7
]
}
}
]
}
}
参数
下表列出了 distance_feature
查询支持的所有顶级参数。
参数 | 必需/可选 | 描述 |
---|---|---|
field | 必需 | 用于计算距离的字段名称。必须是 date 、date_nanos 或 geo_point 字段,且 index: true (默认)和 doc_values: true (默认)。 |
origin | 必需 | 用于计算距离的原点。对于 date 字段,请使用日期或日期数学表达式(例如,now-1h );对于 geo_point 字段,请使用地理点。 |
pivot | 必需 | 从 origin 开始,在该距离处评分将获得 boost 值的一半。对于日期字段,请使用时间单位(例如,10d );对于地理字段,请使用距离单位(例如,1km )。更多信息,请参阅单位。 |
提升 | 可选 | 匹配文档相关性评分的乘数。必须是非负浮点数。默认值为 1.0 。 |
如何计算评分
The distance_feature
query calculates a document’s relevance score using the following formula
\(\text{score} = \text{boost} \cdot \frac {\text{pivot}} {\text{pivot} + \text{distance}}\),
其中 \(\text{distance}\) 是 origin
与字段值之间的绝对差值。
跳过非竞争性命中
与其他修改评分的查询(如 function_score
查询)不同,distance_feature
查询经过优化,可在禁用总命中数跟踪 (track_total_hits
) 时高效跳过非竞争性命中。