elasticsearch的基本操作-ES的经纬度查询


ES的经纬度查询

#创建一个索引,指定一个name,location
PUT /map
{
  "settings": {
    "number_of_shards": 5,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text"
      },
      "location": {
        "type": "geo_point"
      }
    }
  }
}
#添加测试数据
POST /map/_doc/1
{
  "name": "北京站",
  "location": {
    "lat": 39.9042,
    "lon": 116.4074
  }
}
POST /map/_doc/2
{
  "name": "海淀公园",
  "location": {
    "lat": 39.991152,
    "lon": 116.302509
  }
}
POST /map/_doc/3
{
  "name": "北京动物园",
  "location": {
    "lat": 39.947468,
    "lon": 116.343184
  }
}

#geo_distence
POST /map/_search
{
  "query": {
    "geo_distance": {
      "location": {
        "lon": 116.433733,
        "lat": 39.908404
      },
      "distance": 5000,
      "distance_type": "arc"
    }
  }
}

#geo_bounding_box 矩形
POST /map/_search
{
  "query": {
    "geo_bounding_box": {
      "location": {
        "top_left": {
          "lon": 116.326943,
          "lat": 39.95499
        },
        "bottom_right": {
          "lon": 116.347783,
          "lat": 39.939281
        }
      }
    }
  }
}
#geo_polygon 多边形
POST /map/_search
{
  "query": {
    "geo_polygon": {
      "location": {
        "points": [
          {
            "lat": 39.99878,
            "lon": 116.298916
          },
          {
            "lat": 39.972576,
            "lon": 116.29561
          },
          {
            "lat": 39.984739,
            "lon": 116.327661
          }
        ]
      }
    }
  }
}
查询结果:

{
  "took": 56,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "map",
        "_id": "2",
        "_score": 1,
        "_source": {
          "name": "海淀公园",
          "location": {
            "lat": 39.991152,
            "lon": 116.302509
          }
        }
      }
    ]
  }

test2026-08-13 18:32