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的空間操作到此結束

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章