0
1

More than 3 years have passed since last update.

地理的最近傍データを検索(MongoDB)

Last updated at Posted at 2020-01-27

こんにちは。
MongoDB + Python (pymongo) 利用で、与点からの最近傍データを検索する関数例です(2dsphere インデックス付与を仮定)。

$maxDistance も与えており、また何も検索されなかった場合には、定義しておいた NO_DATA を返すようにしました。推奨の API を用いるようにしました 1

NO_DATA = {}
def 2dsphere_near():
  point = [135.0, 35.0]
  query = {"loc": {"$nearSphere": {
           "$geometry": {"type": "Point", "coordinates": point},
           "$maxDistance": 1000}}}  # in meter
  for nearest_data in mycollection.find(query).limit(1):
    return nearest_data
  return NO_DATA

  1. 今回例では、$geoNear.count() をもしも使用すると現在は非推奨だそうです。なお「MongoDBの地理空間インデックス・クエリ整理」も参考になります。 

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1