AI自媒体写作平台推荐:按每天交稿量选写作和排期工具
2026-11-28
2026-11-27 0
要给门店列表增加半径筛选与距离排序,可以预先声明 geo_point,并保留 index 与 doc_values 的默认值。前者支撑空间过滤,后者供排序和聚合读取坐标。使用常规 _source 可以回读输入时的表达。实验采用 Elasticsearch 9.2.5 和三家模拟门店。
门店坐标可通过 location、location_column 和 location_stored 三个字段并排验证。三者分别沿用默认配置、仅保留列式坐标、仅单独保存字段。在 Kibana 的 Dev Tools Console 按顺序执行,并选一个尚未使用的演示索引名。
PUT /shops-geo-demo
{
"mappings": {
"properties": {
"location": {"type": "geo_point"},
"location_column": {"type": "geo_point", "index": false},
"location_stored": {
"type": "geo_point", "index": false,
"doc_values": false, "store": true
}
}
}
}三家门店分别用对象、数组和字符串传值。对象用 lat、lon 属性指明含义,数组按“经度、纬度”排列,逗号分隔的字符串按“纬度、经度”排列。GeoJSON Point 和 WKT POINT 同样采用经度在前的顺序。若把上海样例数组的顺序写反,121.48 会被当成纬度,默认设置会拒绝该坐标。
POST /shops-geo-demo/_bulk?refresh=wait_for
{"index":{"_id":"1"}}
{"location":{"lat":31.2304,"lon":121.4737},"location_column":{"lat":31.2304,"lon":121.4737},"location_stored":{"lat":31.2304,"lon":121.4737}}
{"index":{"_id":"2"}}
{"location":[121.48,31.235],"location_column":[121.48,31.235]}
{"index":{"_id":"3"}}
{"location":"31.30,121.50","location_column":"31.30,121.50"}门店搜索页通常要同时筛选和排序,直接查询 location 即可。将过滤中心设为门店 1 的位置,预期命中门店 1、2,第三家位于 2 公里以外。实测两条命中的排序值分别为 0 和约 0.788 公里。响应使用 docvalue_fields 返回列式坐标,并用 _source: false 省去原始文档。
GET /shops-geo-demo/_search
{
"_source": false,
"query": {
"geo_distance": {
"distance": "2km",
"location": {"lat":31.2304,"lon":121.4737}
}
},
"sort": [
{"_geo_distance": {
"location": {"lat":31.2304,"lon":121.4737},
"order": "asc", "unit": "km"
}}
],
"docvalue_fields": ["location"]
}如果这个坐标只有少量距离过滤请求,可以将 index 设为 false 并保留 doc values。下方使用 location_column 重跑查询,实测仍按 1、2 返回。两条请求是在同一份小样本上核对功能,查询代价取决于数据规模与分布。
GET /shops-geo-demo/_search
{
"_source": false,
"query": {
"geo_distance": {
"distance": "2km",
"location_column": {"lat":31.2304,"lon":121.4737}
}
},
"sort": [
{"_geo_distance": {
"location_column": {"lat":31.2304,"lon":121.4737},
"order": "asc", "unit": "km"
}}
],
"docvalue_fields": ["location_column"]
}如果页面通过其他字段定位门店,只需要单独取一个已保存的坐标,可设置 store: true 并请求 stored_fields。示例用文档 ID 定位门店 1,fields 中会出现 location_stored,实测值为字符串数组 ["31.2304, 121.4737"]。这个配置已关闭空间索引和 doc values,适用于独立取值。
GET /shops-geo-demo/_search
{
"_source": false,
"query": {"ids": {"values": ["1"]}},
"stored_fields": ["location_stored"]
}如果页面要拿回调用方提交的坐标表达,读取常规 _source 即可。门店 2 的 location 仍为 [121.48,31.235]。切换到 synthetic _source 时应重验回显契约,地理点会以存储精度重建,多个点可能按纬度、经度排序。
GET /shops-geo-demo/_doc/2| 门店业务需要 | 选项 | 作用与代价 |
|---|---|---|
| 附近门店经常按范围过滤 | index: true | Lucene 空间点索引使用 BKD 树,加快地理过滤。 |
| 按距离排序、地理聚合或按列读取 | doc_values: true | 列式坐标按文档访问,index 关闭时仍可做示例中的距离过滤,但通常更慢。 |
| 只读取单独保存的字段 | store: true | 通过 stored_fields 取出,额外占用存储。 |
| 回显输入 JSON 中的坐标 | 常规 _source | 可保留输入的数组、字符串或对象表达。 |

doc values 返回的坐标为什么末位有变化? Lucene 将经纬度分别编码为 32 位整数,经纬度都会经过量化。需要原始 JSON 数值与表达时,读取常规 _source。
已有 location 是普通对象怎么办? 创建带 geo_point 映射的新索引,把旧文档转换为受支持的坐标表示后重新索引,核对命中及坐标顺序再切换读取。