1. 程式人生 > >Ruby操作MongoDB(進階十一)--空間資訊搜尋Geospatial Search

Ruby操作MongoDB(進階十一)--空間資訊搜尋Geospatial Search



  上篇博文中介紹了,文字搜尋的相應功能。

  MongoDB資料庫為空間資訊的處理操作提供了一系列的索引和查詢機制。本篇博文將在Ruby驅動上展示如何建立和適用空間索引。下面的例項使用了test資料庫中的一個叫做restaurants的簡單集合。

 下面是restaurants集合

{
 "address":{
       "building":"1007",
       "coord":[-73.856077,40.848447],
       "street":"Morris Park Ave",
       "zipcode":"10462"
 },
 "borough":"Bronx",
 "cuisine":"Bakery",
 "grades":{
     {"date":{"$date":1393804800000},"grade":"A","score":2},
     {"date":{"$date":1299152000000},"grade":"B","score":14},
 },
 "name":"Morris Park Bake Shop",
 "restaurant_id":"30075445"
}

  下面的程式碼在address.coord欄位上建立了一個2dsphere的索引。

client=Mongo::Client.new(['127.0.0.1:27017'],:database=>'test')
client[:restaurant].indexes.create_one({'address.coord'=>'2dsphere'})

  一旦建立了這個索引,就可以在上面使用諸如$near,$geoWithin,$geoIntersects操作符。下面的例子中展示瞭如何通$near操作符在集合中找到所有距離座標距離不超過500米的飯店

client=Mongo::Client.new(['127.0.0.1:27017'],:database=>'test')
collection=client[:restaurants]
collection.find(
         {'address.coord'=>
             {
                "$near"=>{
                      "$geometry"=>{
                         {"$type"=>"Point","coordinates"=>[-73.96,40.78]},
                         "$maxDistance"=>500
                      }
                }
             }
        }).each do |doc|
        p doc
end

   為了找出所有所有位置資訊在給定的多邊形邊界範圍內的文件資訊,使用$geoWithIn操作符。

client=Mongo::Client.new(['mongodb://127.0.0.1:27017/test'])
collection=client[:restaurants]

collection.find(
               {
                  "address.coord"=>{
                     {"$geoWithIn"=>
                        { "$geometry"=>
                           {"type"=>"Ploygon",
                           "corrdinates"=>[[[-73,48],[-74,41],[-72,39],[-73,40]]]
                           }
                         }
                     }
                  }
               }
               ).each do |doc|
               p doc
 end

MongoDB的空間操作到此結束