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

來源:互聯網
上載者:User

標籤:mongodb   ruby   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 docend

   為了找出所有所有位置資訊在給定的多邊形邊界範圍內的文檔資訊,使用$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的空間操作到此結束

本文出自 “techFuture” 部落格,謝絕轉載!

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.